// Weather widget dialog: mode/provider/units settings, location (single-
// city modes) or a city list (multi_city mode), and the rendered
// preview. Not a page-load script -- frame_layout.js fetches this
// widget's dialog HTML fragment, injects it into the shared <dialog>,
// points window.FRAME_API at this specific widget
// (/api/frames/{id}/widgets/{widget_id}), then calls initWeatherDialog().

// Only one of "Location" (current/hourly/daily -- one city) or "Cities"
// (multi_city -- a list) is ever relevant at a time; the interval/days
// rows are each specific to one mode too.
function updateWeatherFieldVisibility() {
  const mode = document.getElementById('weather_mode').value;
  document.getElementById('weather-hourly-interval-row').style.display = mode === 'hourly' ? '' : 'none';
  document.getElementById('weather-daily-days-row').style.display = mode === 'daily' ? '' : 'none';
  document.getElementById('weather-location-section').style.display = mode === 'multi_city' ? 'none' : '';
  document.getElementById('weather-cities-section').style.display = mode === 'multi_city' ? '' : 'none';
}

function addWeatherWidgetCityRow(label) {
  const list = document.getElementById('weather-widget-city-list');
  const empty = document.getElementById('weather-widget-city-empty');
  if (empty) empty.remove();
  const li = document.createElement('li');
  li.className = 'checkbox-row';
  li.style.cssText = 'justify-content: space-between; margin-top: 6px;';
  const span = document.createElement('span');
  span.textContent = label;
  const btn = document.createElement('button');
  btn.type = 'button';
  btn.className = 'btn-inline secondary weather-widget-city-remove';
  btn.dataset.label = label;
  btn.textContent = 'Remove';
  btn.addEventListener('click', removeWeatherWidgetCity);
  li.appendChild(span);
  li.appendChild(btn);
  list.appendChild(li);
}

async function removeWeatherWidgetCity(e) {
  const label = e.target.dataset.label;
  try {
    const resp = await fetch(`${window.FRAME_API}/weather-widget-cities/remove`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ label }),
    });
    if (!resp.ok) throw new Error(await apiError(resp));
    e.target.closest('li').remove();
    const list = document.getElementById('weather-widget-city-list');
    if (!list.querySelector('li')) {
      list.innerHTML = '<li class="sub" id="weather-widget-city-empty">No cities added yet.</li>';
    }
    showStatus(true, `${label} removed.`);
    loadWeatherPreview(false);
  } catch (e) {
    showStatus(false, e.message);
  }
}

function loadWeatherPreview(force) {
  const suffix = force ? '&force=1' : '';
  document.getElementById('weather-preview').src = `${window.FRAME_API}/preview/weather?_=${Date.now()}${suffix}`;
}

function initWeatherDialog() {
  document.getElementById('weather_mode').addEventListener('change', updateWeatherFieldVisibility);
  updateWeatherFieldVisibility();

  document.getElementById('weather-config-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const body = new URLSearchParams({
      weather_mode: document.getElementById('weather_mode').value,
      weather_provider: document.getElementById('weather_provider').value,
      weather_units: document.getElementById('weather_units').value,
      weather_hourly_interval_hours: document.getElementById('weather_hourly_interval_hours').value,
      weather_daily_days: document.getElementById('weather_daily_days').value,
    });
    try {
      const resp = await fetch(`${window.FRAME_API}/config`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body,
      });
      if (!resp.ok) throw new Error(await apiError(resp));
      showStatus(true, 'Saved.');
      loadWeatherPreview(false);
    } catch (e) {
      showStatus(false, e.message);
    }
  });

  document.getElementById('weather-location-set').addEventListener('click', async () => {
    const input = document.getElementById('weather-location-input');
    const name = input.value.trim();
    if (!name) return;
    try {
      const resp = await fetch(`${window.FRAME_API}/weather-location`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name }),
      });
      if (!resp.ok) throw new Error(await apiError(resp));
      const data = await resp.json();
      document.getElementById('weather-location-current').textContent = `Currently: ${data.city.label}`;
      input.value = '';
      showStatus(true, `Location set to ${data.city.label}.`);
      loadWeatherPreview(false);
    } catch (e) {
      showStatus(false, e.message);
    }
  });

  document.getElementById('weather-location-clear').addEventListener('click', async () => {
    try {
      const resp = await fetch(`${window.FRAME_API}/weather-location`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: null }),
      });
      if (!resp.ok) throw new Error(await apiError(resp));
      document.getElementById('weather-location-current').textContent = 'No location set yet.';
      showStatus(true, 'Location cleared.');
      loadWeatherPreview(false);
    } catch (e) {
      showStatus(false, e.message);
    }
  });

  document.querySelectorAll('.weather-widget-city-remove').forEach((el) => el.addEventListener('click', removeWeatherWidgetCity));

  document.getElementById('weather-widget-city-add').addEventListener('click', async () => {
    const input = document.getElementById('weather-widget-city-input');
    const name = input.value.trim();
    if (!name) return;
    try {
      const resp = await fetch(`${window.FRAME_API}/weather-widget-cities/add`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name }),
      });
      if (!resp.ok) throw new Error(await apiError(resp));
      const data = await resp.json();
      addWeatherWidgetCityRow(data.city.label);
      input.value = '';
      showStatus(true, `Added ${data.city.label}.`);
      loadWeatherPreview(false);
    } catch (e) {
      showStatus(false, e.message);
    }
  });

  document.getElementById('weather-preview-refresh').addEventListener('click', () => loadWeatherPreview(true));
  loadWeatherPreview(false);
}

function closeWeatherDialog() {
  // Nothing to tear down -- no poll interval, unlike the photos dialog.
}
