// 天气 / 位置面板 · 温柔琥珀 + 深夜双主题
// 设计 by Claude Design · 集成 by 小鲨鱼

const WeatherModal = ({ state, setState, onClose }) => {
  const toast = window.useToast();
  const { useState, useRef, useEffect } = React;

  // 从 state 读取配置
  const [tab, setTab] = useState('current');
  const [locations, setLocations] = useState(state.settings.weatherLocations || []);
  const [currentId, setCurrentId] = useState(state.settings.weatherCurrentLocation || '');
  const [wxByCity, setWxByCity] = useState({});
  const [loading, setLoading] = useState(false);
  const [ddOpen, setDdOpen] = useState(false);
  const [apiKey, setApiKey] = useState(state.settings.weatherApiKey || '');
  const [autoUpdate, setAutoUpdate] = useState(state.settings.weatherAutoUpdate !== false);
  const [lastUpdated, setLastUpdated] = useState(null);
  const [newName, setNewName] = useState('');
  const [newCity, setNewCity] = useState('');
  const ddRef = useRef(null);

  const current = locations.find((l) => l.id === currentId) || locations[0];
  const wx = current ? wxByCity[current.city] : null;

  // 关闭下拉框
  useEffect(() => {
    const fn = (e) => { if (ddRef.current && !ddRef.current.contains(e.target)) setDdOpen(false); };
    if (ddOpen) { window.addEventListener('click', fn); return () => window.removeEventListener('click', fn); }
  }, [ddOpen]);

  // 天气图标判断
  const condIcon = (cond) => (!cond ? 'cloud' : (/晴|sun|clear/i.test(cond) ? 'sun' : 'cloud'));

  // 刷新天气
  const refresh = async () => {
    if (!current || loading) return;
    if (!apiKey) {
      toast('请先在「设置」里填写 API Key');
      return;
    }

    setLoading(true);
    try {
      const res = await fetch(`/api/weather/current?city=${encodeURIComponent(current.city)}`);
      const data = await res.json();

      if (!res.ok) {
        console.error('Weather API error:', data);
        toast(`获取天气失败：${data.details || data.error || '未知错误'}`);
        return;
      }

      // 转换字段名：后端返回的 → 前端需要的
      const wxData = {
        temp: Math.round(data.temp),
        cond: data.weather,
        feels: Math.round(data.feels_like),
        humidity: data.humidity,
        wind: Math.round(data.wind_speed || 0)
      };

      setWxByCity((m) => ({ ...m, [current.city]: wxData }));
      setLastUpdated(new Date());

      // 更新主页显示
      setState(s => ({
        ...s,
        settings: {
          ...s.settings,
          weatherCity: current.name,
          weatherTemp: wxData.temp,
          weatherCond: wxData.cond,
          weatherLastUpdate: Date.now()
        }
      }));

      // 保存到服务器
      await fetch('/api/settings', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          weatherCity: current.name,
          weatherTemp: wxData.temp,
          weatherCond: wxData.cond,
          weatherLastUpdate: Date.now()
        })
      });

      toast('天气已更新 ✓');
    } catch (e) {
      console.error('Weather fetch error:', e);
      toast('获取天气失败：' + e.message);
    } finally {
      setLoading(false);
    }
  };

  // 添加位置
  const addLocation = async () => {
    const nm = newName.trim(), ct = newCity.trim();
    if (!nm || !ct) {
      toast('请填写位置名称和城市');
      return;
    }

    const id = 'loc_' + Date.now();
    const newLoc = { id, name: nm, city: ct };
    const newLocations = [...locations, newLoc];

    setLocations(newLocations);
    setNewName('');
    setNewCity('');

    // 如果是第一个位置，自动设为当前
    if (newLocations.length === 1) {
      setCurrentId(id);
    }

    // 保存到服务器
    setState(s => ({
      ...s,
      settings: {
        ...s.settings,
        weatherLocations: newLocations,
        weatherCurrentLocation: newLocations.length === 1 ? id : s.settings.weatherCurrentLocation
      }
    }));

    await fetch('/api/settings', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        weatherLocations: newLocations,
        weatherCurrentLocation: newLocations.length === 1 ? id : state.settings.weatherCurrentLocation
      })
    });

    toast('位置已添加 ✓');
  };

  // 删除位置
  const removeLocation = async (id) => {
    if (locations.length <= 1) {
      toast('至少要保留一个位置');
      return;
    }

    const newLocations = locations.filter((l) => l.id !== id);
    const newCurrentId = id === currentId ? newLocations[0].id : currentId;

    setLocations(newLocations);
    if (id === currentId) setCurrentId(newCurrentId);

    // 保存到服务器
    setState(s => ({
      ...s,
      settings: {
        ...s.settings,
        weatherLocations: newLocations,
        weatherCurrentLocation: newCurrentId
      }
    }));

    await fetch('/api/settings', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        weatherLocations: newLocations,
        weatherCurrentLocation: newCurrentId
      })
    });

    toast('位置已删除');
  };

  // 切换位置
  const switchLocation = async (newId) => {
    setCurrentId(newId);
    setDdOpen(false);

    setState(s => ({
      ...s,
      settings: {
        ...s.settings,
        weatherCurrentLocation: newId
      }
    }));

    await fetch('/api/settings', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ weatherCurrentLocation: newId })
    });
  };

  // 保存 API Key
  const saveApiKey = async (key) => {
    setApiKey(key);

    setState(s => ({
      ...s,
      settings: {
        ...s.settings,
        weatherApiKey: key
      }
    }));

    await fetch('/api/settings', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ weatherApiKey: key })
    });
  };

  // 切换自动更新
  const toggleAutoUpdate = async () => {
    const newValue = !autoUpdate;
    setAutoUpdate(newValue);

    setState(s => ({
      ...s,
      settings: {
        ...s.settings,
        weatherAutoUpdate: newValue
      }
    }));

    await fetch('/api/settings', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ weatherAutoUpdate: newValue })
    });
  };

  // 格式化更新时间
  const fmtUpdated = (d) => {
    if (!d) return null;
    const hh = String(d.getHours()).padStart(2, '0');
    const mm = String(d.getMinutes()).padStart(2, '0');
    return `${hh}:${mm}`;
  };

  const TABS = [
    { id: 'current', label: '当前天气' },
    { id: 'locations', label: '位置管理' },
    { id: 'settings', label: '设置' },
  ];

  return (
    <div className="wx-backdrop" onClick={onClose}>
      <div className="wx-modal" onClick={(e) => e.stopPropagation()}>
        <div className="wx-head">
          <div className="wx-title">
            <span className="wx-title-ic"><window.Icon name={condIcon(wx?.cond)} size={24} /></span>
            天气与位置
          </div>
          <div className="wx-sub">看看猫猫所在的地方，今天是什么样子的天</div>
          <button className="wx-close" onClick={onClose} title="关闭">
            <window.Icon name="close" size={16} />
          </button>
        </div>

        <div className="wx-tabs">
          {TABS.map((t) => (
            <button
              key={t.id}
              className={"wx-tab" + (tab === t.id ? " active" : "")}
              onClick={() => setTab(t.id)}
            >{t.label}</button>
          ))}
        </div>

        <div className="wx-body">
          {/* ===== 当前天气 ===== */}
          {tab === 'current' && (
            <div>
              <div className="wx-label">当前位置</div>
              <div className={"wx-dd" + (ddOpen ? " open" : "")} ref={ddRef}>
                <button className="wx-dd-btn" onClick={() => setDdOpen((v) => !v)}>
                  <window.Icon name="pin" size={15} color="var(--amber-600)" />
                  <span>{current?.name || '未设置'}</span>
                  <span className="wx-dd-city">{current?.city || ''}</span>
                  <span className="chev"><window.Icon name="chev-down" size={16} /></span>
                </button>
                {ddOpen && locations.length > 0 && (
                  <div className="wx-dd-menu">
                    {locations.map((l) => (
                      <div
                        key={l.id}
                        className={"wx-dd-item" + (l.id === currentId ? " sel" : "")}
                        onClick={() => switchLocation(l.id)}
                      >
                        <div>
                          <div className="nm">{l.name}</div>
                          <div className="ct">{l.city}</div>
                        </div>
                        {l.id === currentId && <span className="ck"><window.Icon name="check" size={16} /></span>}
                      </div>
                    ))}
                  </div>
                )}
              </div>

              {wx ? (
                <div className="wx-hero">
                  <div className="wx-hero-ic"><window.Icon name={condIcon(wx.cond)} size={44} /></div>
                  <div className="wx-temp">{wx.temp}°</div>
                  <div className="wx-cond">{wx.cond} · {current?.name}</div>
                  <div className="wx-detail-row">
                    <div className="wx-detail"><div className="dv">{wx.feels}°</div><div className="dl">体感</div></div>
                    <div className="wx-detail"><div className="dv">{wx.humidity}%</div><div className="dl">湿度</div></div>
                    <div className="wx-detail"><div className="dv">{wx.wind}</div><div className="dl">风速 km/h</div></div>
                  </div>
                  {lastUpdated && <div className="wx-updated">最近更新于 {fmtUpdated(lastUpdated)}</div>}
                </div>
              ) : (
                <div className="wx-empty">
                  <div className="e-ic"><window.Icon name="cloud" size={48} color="var(--ink-300)" /></div>
                  <div className="e-tx">
                    {locations.length === 0
                      ? '还没有添加位置呢\n去「位置管理」添加第一个位置吧'
                      : `还没有天气数据呢\n点击下方按钮，看看${current?.name}此刻的天气`}
                  </div>
                </div>
              )}
            </div>
          )}

          {/* ===== 位置管理 ===== */}
          {tab === 'locations' && (
            <div>
              {locations.length > 0 && (
                <div className="wx-loc-list">
                  {locations.map((l) => (
                    <div
                      key={l.id}
                      className={"wx-loc" + (l.id === currentId ? " cur" : "")}
                      onClick={() => switchLocation(l.id)}
                    >
                      <div style={{ flex: 1 }}>
                        <div className="nm">{l.name}</div>
                        <div className="ct">{l.city}</div>
                      </div>
                      {l.id === currentId && <span className="cur-badge">当前</span>}
                      <button
                        className="wx-loc-x"
                        title="删除"
                        onClick={(e) => { e.stopPropagation(); removeLocation(l.id); }}
                      ><window.Icon name="close" size={15} /></button>
                    </div>
                  ))}
                </div>
              )}

              <div className="wx-add">
                <h4>添加新位置</h4>
                <div className="wx-field">
                  <label>位置名称</label>
                  <input value={newName} onChange={(e) => setNewName(e.target.value)} placeholder="比如：猫猫的家" />
                </div>
                <div className="wx-field">
                  <label>城市名</label>
                  <input
                    value={newCity}
                    onChange={(e) => setNewCity(e.target.value)}
                    placeholder="比如：Shanghai 或 Beijing"
                    onKeyDown={(e) => { if (e.key === 'Enter') addLocation(); }}
                  />
                  <div className="hint">使用英文城市名或拼音，OpenWeather 会自动识别</div>
                </div>
                <button className="wx-refresh" style={{ marginTop: 4 }} onClick={addLocation} disabled={!newName.trim() || !newCity.trim()}>
                  <window.Icon name="plus" size={16} color="#fff" /> 添加
                </button>
              </div>
            </div>
          )}

          {/* ===== 设置 ===== */}
          {tab === 'settings' && (
            <div>
              <div className="wx-field">
                <label>OpenWeather API Key</label>
                <input
                  type="password"
                  value={apiKey}
                  onChange={(e) => saveApiKey(e.target.value)}
                  placeholder="把你的 API Key 粘在这里"
                />
                <div className="wx-set-hint">
                  <window.Icon name="sparkle" size={13} color="var(--amber-500)" style={{ marginTop: 1, flexShrink: 0 }} />
                  <span>从 <a className="wx-link" href="https://openweathermap.org/api" target="_blank" rel="noreferrer">OpenWeatherMap</a> 免费申请。新 Key 需要等 10–20 分钟激活。</span>
                </div>
              </div>

              <div className="wx-row">
                <div>
                  <div className="rt">自动更新天气</div>
                  <div className="rs">每 10 分钟自动刷新一次（约 150 次/天，完全免费）</div>
                </div>
                <div className={"switch " + (autoUpdate ? "on" : "")} onClick={toggleAutoUpdate}></div>
              </div>
              <div className="wx-set-hint" style={{ marginTop: 12 }}>
                <window.Icon name="sparkle" size={13} color="var(--amber-500)" style={{ marginTop: 1, flexShrink: 0 }} />
                <span>OpenWeather 免费版每天有 1000 次额度，我们的用量完全在范围内。</span>
              </div>
            </div>
          )}
        </div>

        {tab === 'current' && (
          <div className="wx-foot">
            <button className="wx-refresh" onClick={refresh} disabled={loading}>
              {loading
                ? <><span className="spin"><window.Icon name="refresh" size={16} color="#fff" /></span> 正在查询…</>
                : <><window.Icon name="refresh" size={16} color="#fff" /> 刷新天气</>}
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

window.WeatherModal = WeatherModal;
