/* WeatherMate — screens */

function uvDesc(uv) {
  if (uv == null) return "—";
  if (uv < 3) return "Low"; if (uv < 6) return "Moderate";
  if (uv < 8) return "High"; if (uv < 11) return "Very High"; return "Extreme";
}
function dewPoint(t, rh) {
  const a = 17.27, b = 237.7;
  const g = (a * t) / (b + t) + Math.log(Math.max(rh, 1) / 100);
  return (b * g) / (a - g);
}
function pressureDesc(p) {
  if (p < 1000) return "Low";
  if (p > 1022) return "High"; return "Normal";
}
function visDesc(km) {
  if (km >= 20) return "Perfectly clear"; if (km >= 10) return "Clear";
  if (km >= 4) return "Hazy"; if (km >= 1) return "Misty"; return "Very poor";
}

function DetailsGrid({ data, unit, animate }) {
  const c = data.current, today = data.daily[0];
  const visKm = WX.conv.vis(c.visibility, unit);
  const dp = dewPoint(c.temp, c.humidity);
  const feels = WX.conv.temp(c.feels, unit);
  const actual = WX.conv.temp(c.temp, unit);
  return (
    <div className="detail-grid">
      <DetailWidget icon="☀︎" title="UV Index">
        <div className="dw-value">{c.uv != null ? Math.round(c.uv) : "—"}</div>
        <div style={{ height: 6, borderRadius: 4, margin: "10px 0 0", background: "linear-gradient(90deg,#4caf50,#ffeb3b,#ff9800,#f44336,#9c27b0)", position: "relative" }}>
          <i style={{ position: "absolute", top: -3, left: `calc(${Math.min(100, (c.uv || 0) / 11 * 100)}% - 6px)`, width: 12, height: 12, borderRadius: "50%", background: "#fff", boxShadow: "0 0 0 2px rgba(0,0,0,0.2)" }} />
        </div>
        <div className="dw-note">{uvDesc(c.uv)}</div>
      </DetailWidget>

      <DetailWidget icon="☼" title="Sunrise">
        <div className="dw-value" style={{ fontSize: 26 }}>{WX.fmtClock(today.sunrise)}</div>
        <SunArc sunrise={today.sunrise} sunset={today.sunset} now={Date.now()} />
        <div className="dw-note">Sunset: {WX.fmtClock(today.sunset)}</div>
      </DetailWidget>

      <DetailWidget icon="≋" title="Wind">
        <Compass dir={c.windDir} speed={WX.conv.wind(c.wind, unit)} unit={WX.conv.windUnit(unit)} />
        <div className="dw-note" style={{ textAlign: "center" }}>{WX.conv.wind(c.wind, unit)} {WX.conv.windUnit(unit)} winds</div>
      </DetailWidget>

      <DetailWidget icon="☂" title="Rainfall">
        <div className="dw-value">{WX.conv.precip(c.precip, unit).toFixed(1)}<span className="dw-unit"> {WX.conv.precipUnit(unit)}</span></div>
        <div className="dw-note">{WX.conv.precip(today.precip, unit).toFixed(1)} {WX.conv.precipUnit(unit)} expected today{today.pop != null ? ` · ${today.pop}% chance` : ""}</div>
      </DetailWidget>

      <DetailWidget icon="❂" title="Feels Like">
        <div className="dw-value">{feels}°</div>
        <div className="dw-note">{feels === actual ? "Same as the actual temp" : feels > actual ? "Humidity makes it warmer" : "Wind makes it feel cooler"}</div>
      </DetailWidget>

      <DetailWidget icon="❍" title="Humidity">
        <div className="dw-value">{Math.round(c.humidity)}<span className="dw-unit">%</span></div>
        <div className="dw-note">Dew point {WX.conv.temp(dp, unit)}° right now</div>
      </DetailWidget>

      <DetailWidget icon="◉" title="Visibility">
        <div className="dw-value">{visKm.toFixed(visKm < 10 ? 1 : 0)}<span className="dw-unit"> {WX.conv.visUnit(unit)}</span></div>
        <div className="dw-note">{visDesc(visKm)}</div>
      </DetailWidget>

      <DetailWidget icon="◷" title="Pressure">
        <div className="dw-value">{Math.round(c.pressure)}<span className="dw-unit"> hPa</span></div>
        <div className="dw-note">{pressureDesc(c.pressure)} pressure</div>
      </DetailWidget>
    </div>
  );
}

function summaryText(data, unit) {
  const c = data.current, d = data.daily;
  const label = WX.labelOf(c.code);
  const hi = WX.conv.temp(d[0].hi, unit), lo = WX.conv.temp(d[0].lo, unit);
  // find next rainy day
  let rainDay = null;
  for (let i = 1; i < d.length; i++) {
    const cond = WX.conditionOf(d[i].code);
    if (cond === "rain" || cond === "drizzle" || cond === "thunder") { rainDay = d[i]; break; }
  }
  let s = `${label} conditions will continue with a high of ${hi}° and a low of ${lo}°.`;
  if (rainDay) {
    const day = WX.fmtDay(rainDay.date, d.indexOf(rainDay));
    s += ` Rain is expected ${day}.`;
  } else {
    s += " Dry conditions are expected all week.";
  }
  return s;
}

function ForecastCard({ data, unit, animate, forecastMode, setForecastMode, selectedHour, setSelectedHour }) {
  const tempVals = data.daily.map(d => [d.lo, d.hi]).flat();
  const range = { min: Math.min(...tempVals), max: Math.max(...tempVals) };
  return (
    <div className="fc-card glass">
      <div className="fc-tabs">
        <button className={"fc-tab" + (forecastMode === "hourly" ? " active" : "")} onClick={() => setForecastMode("hourly")}>Hourly Forecast</button>
        <button className={"fc-tab" + (forecastMode === "weekly" ? " active" : "")} onClick={() => setForecastMode("weekly")}>Weekly Forecast</button>
      </div>
      {forecastMode === "hourly" ? (
        <div className="hours">
          {data.hourly.map((h, i) => (
            <HourSlot key={h.time} h={h} unit={unit} animate={animate} isNow={i === 0}
              active={selectedHour === i}
              onClick={() => setSelectedHour(selectedHour === i ? null : i)} />
          ))}
        </div>
      ) : (
        <div className="week">
          {data.daily.map((d, i) => (
            <WeekRow key={d.date} d={d} idx={i} unit={unit} animate={animate} range={range} />
          ))}
        </div>
      )}
    </div>
  );
}

function HomeScreen({ data, unit, animate, theme, city, style, forecastMode, setForecastMode, ptr }) {
  const [selectedHour, setSelectedHour] = React.useState(null);
  const scrollRef = React.useRef(null);

  // hero reflects selected hour or current
  const sel = selectedHour != null ? data.hourly[selectedHour] : null;
  const heroCode = sel ? sel.code : data.current.code;
  const heroDay = sel ? sel.isDay : data.current.isDay;
  const heroTemp = sel ? sel.temp : data.current.temp;
  const heroCond = WX.labelOf(heroCode);
  const hi = WX.conv.temp(data.daily[0].hi, unit);
  const lo = WX.conv.temp(data.daily[0].lo, unit);
  const novel = style === "novel";

  return (
    <div className="screen">
      <div className="scroll" ref={scrollRef} {...ptr.bind(scrollRef)}>
        <div ref={ptr.zoneRef} className={"ptr" + (ptr.spinning ? " spin" : "")} style={{ height: ptr.height }}>
          <div className="ptr-spinner" style={{ opacity: ptr.height > 6 ? 1 : 0, transform: `rotate(${ptr.height * 4}deg)` }} />
        </div>

        <div className={"hero" + (novel ? " novel" : "")} style={{ "--theme-sub": theme.sub }}>
          {!novel && (
            <div style={{ display: "flex", justifyContent: "center", marginBottom: -6 }}>
              <WeatherIcon condition={WX.conditionOf(heroCode)} isDay={heroDay} size={novel ? 150 : 132} animate={animate} />
            </div>
          )}
          <div className="city">{city.name}</div>
          <div style={{ display: "flex", justifyContent: novel ? "flex-start" : "center", alignItems: "flex-start" }}>
            <span className="temp">{WX.conv.temp(heroTemp, unit)}<span className="deg">°</span></span>
            {novel && (
              <div style={{ marginTop: 18, marginLeft: 8 }}>
                <WeatherIcon condition={WX.conditionOf(heroCode)} isDay={heroDay} size={92} animate={animate} />
              </div>
            )}
          </div>
          <div className="cond">{sel ? `${heroCond} · ${WX.fmtHour(sel.time)}` : heroCond}</div>
          <div className="hilo">H:{hi}°<span></span>L:{lo}°</div>
        </div>

        <div style={{ height: 18 }} />
        <ForecastCard data={data} unit={unit} animate={animate}
          forecastMode={forecastMode} setForecastMode={setForecastMode}
          selectedHour={selectedHour} setSelectedHour={setSelectedHour} />

        <div className="summary glass" style={{ "--theme-sub": theme.sub }}>
          <WeatherIcon condition={WX.conditionOf(data.current.code)} isDay={data.current.isDay} size={48} animate={animate} />
          <div className="s-txt">
            <div className="s-title">Forecast</div>
            <div className="s-body">{summaryText(data, unit)}</div>
          </div>
        </div>

        <DetailsGrid data={data} unit={unit} animate={animate} />
        <div style={{ height: 96 }} />
      </div>
    </div>
  );
}

window.HomeScreen = HomeScreen;
