class OneDisplayWeather {
    constructor(container, options = {}) {
      this.container = container; // Use the passed container directly
      this.city = options.city || 'London';
      this.theme = options.theme || 'light'; // 'light' or 'dark'
      this.units = options.units || 'metric';
      this.options = options;
      this.weatherData = null;
      this.instanceID = `weather-widget-${Math.random().toString(36).substring(2, 9)}`;
      this.injectScopedCSS();
    }
  
    injectScopedCSS() {
      const isDark = this.theme === 'dark';
      const textColor = isDark ? '#ffffff' : '#333333';
      /* const bgColor = isDark ? '#222222' : '#f5f5f5'; */
      const cardBg = isDark ? 'rgba(51,51,51,0.7)' : 'rgba(255,255,255,0.7)';
      const primaryColor = isDark ? '#ffffff' : '#333333';
      const borderColor = isDark ? '#444444' : '#e0e0e0';
  
      const styles = `
        .${this.instanceID} {
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
          color: ${textColor};
          background-color: transparent;
          border-radius: 12px;
          padding: 16px;
          box-sizing: border-box;
          height: 100%;
          width: 100%;
          display: flex;
          flex-direction: column;
          font-size: ${this.options.fontSize}
        }
  
        .${this.instanceID} .weather-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;
        }
        
        .${this.instanceID} h2 {
          margin: 0;
          font-size: 0.4em;
          font-weight: 600;
        }
  
        .${this.instanceID} .last-updated {
          font-size: 0.4em;
          opacity: 0.8;
        }
        
        .${this.instanceID} .current-weather {
          background-color: ${cardBg} !important;
          background-opacity: 0.9 !important;
          border: 1px solid ${primaryColor} !important;

        }
  
        .${this.instanceID} .current-temp {
          font-size: 1em;
          font-weight: 700;
          color: ${primaryColor};
          line-height: 1;
        }
  
        .${this.instanceID} .current-details {
          display: flex;
          flex-direction: column;
          gap: 4px;
        }
  
        .${this.instanceID} .current-description {
          font-size: 0.5em;
          text-transform: capitalize;
          font-weight: 500;
        }
  
        .${this.instanceID} .current-extra {
          font-size: 0.9rem;
          opacity: 0.8;
          display: flex;
          gap: 8px;
        }
  
        .${this.instanceID} .current-icon {
          font-size: 1.4em;
        }

          
        .${this.instanceID} .current-day-name {
          font-size: 1em;
          font-weight: 600;
          margin-bottom: 8px;
          color: ${primaryColor};
        }
  
        .${this.instanceID} .forecast-container {
          flex: 1;
          display: flex;
          overflow: hidden;
        }
  
        .${this.instanceID} .forecast {
          flex: 1;
          display: grid;
          grid-auto-flow: column;
          grid-auto-columns: 1fr;
          gap: 8px;
        }
  
        .${this.instanceID} .forecast.vertical {
          grid-auto-flow: row;
          grid-auto-rows: 1fr;
        }
  
        .${this.instanceID} .forecast-day {
          background-color: ${cardBg};
          border-radius: 8px;
          padding: 12px;
          border: 1px solid ${borderColor};
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          text-align: center;
        }
  
        .${this.instanceID} .forecast-day.today {
          background-color: ${isDark ? 'rgba(77, 171, 247, 0.1)' : 'rgba(25, 113, 194, 0.1)'};
        }
  
        .${this.instanceID} .day-name {
          font-size: 1em;
          font-weight: 600;
          margin-bottom: 8px;
          color: ${primaryColor};
        }
  
        .${this.instanceID} .forecast-icon {
          font-size: 1.3em;
          margin-bottom: 8px;
        }
  
        .${this.instanceID} .forecast-temp {
          font-size: 0.8em;
          font-weight: 600;
          margin-bottom: 4px;
        }
  
        .${this.instanceID} .forecast-description {
          font-size: 0.4em;
          opacity: 0.8;
          margin-bottom: 4px;
          text-transform: capitalize;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
  
        .${this.instanceID} .forecast-rain {
          font-size: 0.4em;
          color: ${primaryColor};
        }
  
        .${this.instanceID} .compact-view {
          display: flex;
          align-items: center;
          justify-content: center;
          height: 100%;
          gap: 16px;
        }
  
        .${this.instanceID} .compact-temp {
          font-size: 2rem;
          font-weight: 700;
          color: ${primaryColor};
        }
  
        .${this.instanceID} .compact-icon {
          width: 48px;
          height: 48px;
        }



        

        .${this.instanceID} .current-weather-forecast-container {
          height: 100%;
          width: 100%;
          
        }

        .${this.instanceID} .current-weather-forecast {
        height: 100%;
        }

        .${this.instanceID} .current-weather-forecast.vertical {
          flex-direction: column;
        }

        .${this.instanceID} .current-weather-forecast-day {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 100%;
        }

        /* Horizontal layout (wide widget) */
        .${this.instanceID} .current-weather-forecast:not(.vertical) .current-weather-forecast-day {
          flex-direction: row;
          gap: 20px;
        }

        .${this.instanceID} .current-weather-forecast:not(.vertical) .current-weather-forecast-temp {
          font-size: 1em;
          font-weight: bold;
          min-width: 60px;
          text-align: center;
        }

        .${this.instanceID} .current-weather-forecast:not(.vertical) .current-weather-forecast-icon {
          font-size: 1em;
        }

        /* Vertical layout (tall widget) */
        .${this.instanceID} .current-weather-forecast.vertical .current-weather-forecast-day {
          gap: 5px;
        }

        .${this.instanceID} .current-weather-forecast.vertical .current-weather-forecast-temp {
          font-size: 1em;
          font-weight: bold;
        }

        .${this.instanceID} .current-weather-forecast.vertical .current-weather-forecast-icon {
          font-size: 1em;
        }

        /* Common styles for both layouts */
        .${this.instanceID} .current-weather-forecast-description {
          font-size: 0.7em;
          text-align: center;
          text-transform: capitalize;
          opacity: 0.9;
        }


        



      `;
  
      const styleTag = document.createElement('style');
      styleTag.innerHTML = styles;
      document.head.appendChild(styleTag);
    }
  
    async fetchWeatherData() {
      try {
        // Get coordinates for the city
        const geoResponse = await axios.get('https://geocoding-api.open-meteo.com/v1/search', {
          params: {
            name: this.city,
            count: 1,
            language: 'en'
          }
        });
  
        if (!geoResponse.data.results || geoResponse.data.results.length === 0) {
          throw new Error('City not found');
        }
  
        const { latitude, longitude, timezone } = geoResponse.data.results[0];
  
        // Get weather data
        const weatherResponse = await axios.get('https://api.open-meteo.com/v1/forecast', {
          params: {
            latitude,
            longitude,
            current_weather: true,
            daily: 'weathercode,temperature_2m_max,temperature_2m_min,precipitation_sum,precipitation_probability_max',
            temperature_unit: this.units === 'metric' ? 'celsius' : 'fahrenheit',
            timezone
          }
        });
  
        this.weatherData = weatherResponse.data;
        this.weatherData.timezone = timezone;
        this.render();
      } catch (error) {
        console.error('Error fetching weather data:', error);
        this.container.innerHTML = `<div class="weather-widget ${this.instanceID}">
          <div class="weather-error">Unable to fetch weather data for ${this.city}</div>
        </div>`;
      }
    }
  
    render() {
        if (!this.weatherData || !this.weatherData.current_weather) return;
        

        this.container.innerHTML = '';

        // Create basic container first
        const weatherWidget = document.createElement('div');
        weatherWidget.className = `weather-widget ${this.instanceID}`;
        weatherWidget.innerHTML = '<div style="display:contents"></div>'; // Temporary content
        this.container.appendChild(weatherWidget);

        // Now measure (after DOM insertion)
        const parent = this.container.parentElement;
        const containerWidth = parent.offsetWidth;
        const containerHeight = parent.offsetHeight;
        const isWide = containerWidth / containerHeight > 1.5;
        const isVerySmall = containerWidth < 200 || containerHeight < 100;
      
        // Now measure (after DOM insertion)
        /* const containerWidth = this.container.offsetWidth;
        const containerHeight = this.container.offsetHeight;
        const isWide = containerWidth / containerHeight > 1.5;
        const isVerySmall = containerWidth < 200 || containerHeight < 100; */
      
        // Generate appropriate content
        const now = new Date();
        const today = now.toISOString().split('T')[0];
        const { current_weather, daily } = this.weatherData;
        if(this.options.currentWeather) {
          weatherWidget.innerHTML = `
            <div class="current-weather-forecast-container">
              <div class="current-weather-forecast ${isWide ? '' : 'vertical'}">
                <div class="current-weather-forecast-day current-weather-card">
                  ${isWide ? `
                    <div class="current-weather-forecast-temp">${Math.round(current_weather.temperature)}°</div>
                    <i class="wi ${this.getWeatherIcon(current_weather.weathercode)} current-weather-forecast-icon"></i>
                  ` : `
                    <i class="wi ${this.getWeatherIcon(current_weather.weathercode)} current-weather-forecast-icon"></i>
                    <div class="current-weather-forecast-temp">${Math.round(current_weather.temperature)}°</div>
                  `}
                  
                  ${this.options.showDescription ? `<div class="current-weather-forecast-description">${this.getWeatherDescription(current_weather.weathercode)}</div>` : ''}
                  ${current_weather.precipitation > 0 ? 
                    `<div class="current-weather-forecast-rain">${Math.round(current_weather.precipitation * 10) / 10}mm</div>` : 
                    '<div class="current-weather-forecast-rain">&nbsp;</div>'}
                </div>
              </div>
            </div>
          `;
        } else {
          if (isVerySmall) {
            weatherWidget.innerHTML = `
              <div class="compact-view">
                <i class="wi ${this.getWeatherIcon(current_weather.weathercode)} compact-icon"></i>
                <span class="compact-temp">${Math.round(current_weather.temperature)}°</span>
              </div>
            `;
          } else {
            weatherWidget.innerHTML = `
              <div class="weather-header">
                <h2>${this.city}</h2>
                <div class="last-updated">${now.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</div>
              </div>
              

              
              <div class="forecast-container">
                <div class="forecast ${isWide ? '' : 'vertical'}">

                    <div class="forecast-day current-weather">
                      <div class="day-name">Now</div>
                      <i class="wi ${this.getWeatherIcon(current_weather.weathercode)} forecast-icon"></i>
                      <div class="forecast-temp">${Math.round(current_weather.temperature)}°</div>
                      ${this.options.showDescription ? `<div class="forecast-description">${this.getWeatherDescription(current_weather.weathercode)}</div>` : ''}
                      <div class="forecast-rain">&nbsp;</div>
                    </div>

                  ${daily.time.map((day, index) => `
                    <div class="forecast-day ${day === today ? 'current-weather' : ''}">
                      <div class="day-name">${day === today ? 'Today' : new Date(day).toLocaleDateString('en-US', { weekday: 'short' })}</div>
                      <i class="wi ${this.getWeatherIcon(daily.weathercode[index])} forecast-icon"></i>
                      <div class="forecast-temp">${Math.round(daily.temperature_2m_max[index])}°/${Math.round(daily.temperature_2m_min[index])}°</div>
                      ${this.options.showDescription ? `<div class="forecast-description">${this.getWeatherDescription(daily.weathercode[index])}</div>` : ''}
                      ${daily.precipitation_sum[index] > 0 ? 
                        `<div class="forecast-rain">${Math.round(daily.precipitation_sum[index]*10)/10}mm</div>` : 
                        '<div class="forecast-rain">&nbsp;</div>'}
                    </div>
                  `).join('')}
                </div>
              </div>
            `;
          }
        }

      }
  
    getWeatherDescription(code) {
      const weatherDescriptions = {
        0: 'Clear sky', 1: 'Mainly clear', 2: 'Partly cloudy', 3: 'Overcast',
        45: 'Fog', 48: 'Rime fog', 51: 'Light drizzle', 53: 'Moderate drizzle',
        55: 'Dense drizzle', 56: 'Light freezing drizzle', 57: 'Dense freezing drizzle',
        61: 'Slight rain', 63: 'Moderate rain', 65: 'Heavy rain',
        66: 'Light freezing rain', 67: 'Heavy freezing rain', 71: 'Slight snow',
        73: 'Moderate snow', 75: 'Heavy snow', 77: 'Snow grains', 80: 'Slight rain showers',
        81: 'Moderate rain showers', 82: 'Violent rain showers', 85: 'Slight snow showers',
        86: 'Heavy snow showers', 95: 'Thunderstorm', 96: 'Thunderstorm with hail',
        99: 'Thunderstorm with heavy hail'
      };
      return weatherDescriptions[code] || 'Unknown weather';
    }
  
    getWeatherIcon(code) {
      const iconMappings = {
        0: 'wi-day-sunny', 1: 'wi-day-sunny-overcast', 2: 'wi-day-cloudy', 3: 'wi-cloudy',
        45: 'wi-fog', 48: 'wi-fog', 51: 'wi-sprinkle', 53: 'wi-sprinkle', 55: 'wi-sprinkle',
        56: 'wi-rain-mix', 57: 'wi-rain-mix', 61: 'wi-rain', 63: 'wi-rain', 65: 'wi-rain',
        66: 'wi-rain-mix', 67: 'wi-rain-mix', 71: 'wi-snow', 73: 'wi-snow', 75: 'wi-snow',
        77: 'wi-snow-wind', 80: 'wi-showers', 81: 'wi-showers', 82: 'wi-showers',
        85: 'wi-snow', 86: 'wi-snow', 95: 'wi-thunderstorm', 96: 'wi-storm-showers',
        99: 'wi-storm-showers'
      };
  
      // Use night icons when appropriate
      const hour = new Date().getHours();
      const isNight = hour < 6 || hour > 18;
      
      if (isNight) {
        if (code === 0) return 'wi-night-clear';
        if (code === 1) return 'wi-night-alt-partly-cloudy';
        if (code === 2) return 'wi-night-alt-cloudy';
      }
      
      return iconMappings[code] || 'wi-na';
    }
  
    start() {
      this.fetchWeatherData();
      // Refresh every 30 minutes
      this.refreshInterval = setInterval(() => this.fetchWeatherData(), 1 * 60 * 1000);
      //this.refreshInterval = setInterval(() => this.fetchWeatherData(), 30 * 60 * 1000);
    }
  
    destroy() {
      clearInterval(this.refreshInterval);
      this.container.innerHTML = '';
    }
  }