/* WeatherMate — search / city manager */

function MiniWeather({ city, unit, active, onSelect, onRemove, removable }) {
  const [info, setInfo] = React.useState(null);
  React.useEffect(() => {
    let alive = true;
    WX.fetchWeather(city.lat, city.lon)
      .then(d => { if (alive) setInfo(d); })
      .catch(() => { if (alive) setInfo(null); });
    return () => { alive = false; };
  }, [city.lat, city.lon]);

  const cond = info ? WX.conditionOf(info.current.code) : "cloudy";
  const isDay = info ? info.current.isDay : true;
  const theme = WX.themeFor(cond, isDay);
  return (
    <button className="result-card" style={{
      background: `linear-gradient(135deg, ${theme.bg[0]}, ${theme.bg[2]})`,
      border: active ? "1.5px solid rgba(255,255,255,0.6)" : "1px solid rgba(255,255,255,0.12)",
    }} onClick={() => onSelect(city)}>
      <WeatherIcon condition={cond} isDay={isDay} size={44} animate={false} />
      <div>
        <div className="r-name">{city.name}{active ? "  ●" : ""}</div>
        <div className="r-sub">{[city.admin, city.country].filter(Boolean).join(", ") || (info ? WX.labelOf(info.current.code) : "…")}</div>
      </div>
      <div className="r-meta">
        <div className="r-temp">{info ? WX.conv.temp(info.current.temp, unit) + "°" : "··"}</div>
        {removable && (
          <span onClick={(e) => { e.stopPropagation(); onRemove(city); }}
            style={{ fontSize: 12, color: "rgba(255,255,255,0.6)" }}>Remove</span>
        )}
      </div>
    </button>
  );
}

function SearchScreen({ saved, activeId, unit, onSelect, onAdd, onRemove, onClose }) {
  const [q, setQ] = React.useState("");
  const [results, setResults] = React.useState([]);
  const [busy, setBusy] = React.useState(false);
  const tRef = React.useRef(null);

  React.useEffect(() => {
    if (tRef.current) clearTimeout(tRef.current);
    if (q.trim().length < 2) { setResults([]); setBusy(false); return; }
    setBusy(true);
    tRef.current = setTimeout(() => {
      WX.geocode(q.trim())
        .then(r => setResults(r))
        .catch(() => setResults([]))
        .finally(() => setBusy(false));
    }, 350);
    return () => tRef.current && clearTimeout(tRef.current);
  }, [q]);

  return (
    <div className="screen search-screen fade-enter">
      <div className="search-head">
        <h1>Weather</h1>
        <button className="done-btn" onClick={onClose}>Done</button>
      </div>
      <div className="search-box">
        <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="rgba(235,235,245,0.6)" strokeWidth="2.2" strokeLinecap="round">
          <circle cx="11" cy="11" r="7"/><path d="m20 20-3.2-3.2"/>
        </svg>
        <input autoFocus placeholder="Search for a city or airport" value={q} onChange={e => setQ(e.target.value)} />
        {q && <button onClick={() => setQ("")} style={{ color: "rgba(235,235,245,0.6)", fontSize: 18 }}>×</button>}
      </div>

      <div className="scroll">
        {q.trim().length >= 2 ? (
          <div className="search-list">
            {busy && <div className="hint">Searching…</div>}
            {!busy && results.length === 0 && <div className="hint">No matches for “{q}”.</div>}
            {results.map(r => (
              <button key={r.id} className="result-card glass" onClick={() => onAdd(r)}>
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.7)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M12 21s-7-6.2-7-11a7 7 0 0 1 14 0c0 4.8-7 11-7 11Z"/><circle cx="12" cy="10" r="2.6"/>
                </svg>
                <div>
                  <div className="r-name">{r.name}</div>
                  <div className="r-sub">{[r.admin, r.country].filter(Boolean).join(", ")}</div>
                </div>
                <span className="r-meta" style={{ fontSize: 24, color: "rgba(255,255,255,0.7)" }}>+</span>
              </button>
            ))}
          </div>
        ) : (
          <div className="search-list">
            {saved.map(c => (
              <MiniWeather key={c.id} city={c} unit={unit} active={c.id === activeId}
                onSelect={onSelect} onRemove={onRemove} removable={saved.length > 1} />
            ))}
            <div className="hint">Search to add more cities. Tap a city to view its full forecast.</div>
          </div>
        )}
      </div>
    </div>
  );
}

window.SearchScreen = SearchScreen;
