/* ============================================================
   SKI NEW ENGLAND — Webcams gallery
   One live cam per mountain. Slot ids match the resort page's
   cam slot, so a photo dropped on either shows on both.
   ============================================================ */
const CAM_STILLS = { "jay-peak": "./jay-cam-mwbef3uh-o6al.png" };

function camVantage(r) {
  if (r.summit >= 4000) return "Summit";
  if (r.vertical >= 2000) return "Mid-mountain";
  return "Base area";
}

function CamClock() {
  const fmt = () => new Date().toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
  const [now, setNow] = useState(fmt);
  useEffect(() => {
    const id = setInterval(() => setNow(fmt()), 30000);
    return () => clearInterval(id);
  }, []);
  return <span className="mono">{now}</span>;
}

function CamCard({ r, go, big }) {
  const [hover, setHover] = useState(false);
  return (
    <button onClick={() => go("resort", r.id)} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ gridColumn: big ? "span 2" : "span 1", display: "block", width: "100%", textAlign: "left", padding: 0, border: "1px solid var(--line)", borderRadius: "var(--radius)", background: "var(--paper)", overflow: "hidden", boxShadow: hover ? "var(--shadow-pop)" : "var(--shadow-card)", transform: hover ? "translateY(-2px)" : "none", transition: "transform .14s ease, box-shadow .16s ease" }}>
      <div style={{ position: "relative", aspectRatio: big ? "21 / 9" : "16 / 9", background: "var(--ink-850)" }}>
        <image-slot id={`webcam-${r.id}`} shape="rect" placeholder={`${r.name} — ${camVantage(r).toLowerCase()} cam`} src={CAM_STILLS[r.id]} style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}></image-slot>
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(rgba(6,19,33,0) 55%, rgba(6,19,33,0.72) 100%)", pointerEvents: "none" }}></div>
        <div style={{ position: "absolute", top: 11, left: 11, display: "flex", alignItems: "center", gap: 7, background: "rgba(0,21,67,0.66)", backdropFilter: "blur(4px)", padding: "5px 10px", borderRadius: 4 }}>
          <span className="pow-badge" style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--pow)" }}></span>
          <span className="eyebrow" style={{ fontSize: 9, color: "#fff" }}>Live</span>
        </div>
        {r.newSnow >= 6 && (
          <div className="eyebrow" style={{ position: "absolute", top: 11, right: 11, fontSize: 9, color: "#fff", background: "var(--pow)", padding: "5px 9px", borderRadius: 4 }}>{r.newSnow}&Prime; new</div>
        )}
        <div style={{ position: "absolute", left: 13, right: 13, bottom: 11, display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 12 }}>
          <div>
            <div className="eyebrow" style={{ fontSize: 9, color: "rgba(255,255,255,0.72)", marginBottom: 4 }}>{camVantage(r)} · {r.state}</div>
            <div className="display" style={{ fontSize: big ? 30 : 20, fontWeight: 800, color: "#fff", lineHeight: 1.05 }}>{r.name}</div>
          </div>
          <div className="mono" style={{ fontSize: 10.5, color: "rgba(255,255,255,0.75)", whiteSpace: "nowrap" }}>{r.summit.toLocaleString()} ft</div>
        </div>
      </div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, padding: "11px 14px" }}>
        <span className="mono" style={{ fontSize: 11.5, color: "var(--muted)" }}>{r.tempF}&deg; · {r.sky} · {r.wind}</span>
        <span className="eyebrow" style={{ fontSize: 9, color: "var(--muted-2)" }}>Updated <CamClock /></span>
      </div>
    </button>
  );
}

function WebcamsPage({ go, data }) {
  const [stateFilter, setStateFilter] = useState("ALL");
  const [sort, setSort] = useState("snow");
  const states = [{ code: "ALL", name: "All states", count: data.RESORTS.length }, ...data.STATES];

  let rows = data.RESORTS.filter((r) => stateFilter === "ALL" || r.state === stateFilter);
  rows = [...rows].sort((a, b) => sort === "snow" ? b.newSnow - a.newSnow : sort === "elev" ? b.summit - a.summit : a.name.localeCompare(b.name));
  const [featured, ...restCams] = rows;
  const snowing = data.RESORTS.filter((r) => /snow/i.test(r.sky)).length;

  return (
    <div style={{ background: "var(--frost-50)", minHeight: "100%" }}>
      <PageHead eyebrow={`${data.RESORTS.length} cams live · refreshed every 5 minutes`} title="Mountain Webcams"
        sub="Look before you load the car. Every mountain in the network, pointed at the snow right now." />

      <div style={{ background: "var(--retro-900)", color: "#fff" }}>
        <div className="wrap" style={{ display: "flex", flexWrap: "wrap", gap: 0, padding: "0 28px" }}>
          {[[data.RESORTS.length, "cams online"], [snowing, "reporting snow"], [data.RESORTS.filter((r) => r.newSnow >= 6).length, "with 6\u2033+ fresh"]].map(([v, l], i) => (
            <div key={l} style={{ flex: "1 1 0", minWidth: 150, padding: "18px 0 18px 22px", marginLeft: i ? 22 : 0, borderLeft: i ? "1px solid rgba(255,255,255,0.16)" : "none" }}>
              <div className="display" style={{ fontSize: 30, fontWeight: 800, lineHeight: 1 }}>{v}</div>
              <div className="eyebrow" style={{ fontSize: 9.5, color: "rgba(255,255,255,0.66)", marginTop: 6 }}>{l}</div>
            </div>
          ))}
        </div>
      </div>

      <div style={{ position: "sticky", top: 96, zIndex: 20, background: "rgba(244,248,253,0.93)", backdropFilter: "blur(8px)", borderBottom: "1px solid var(--line)" }}>
        <div className="wrap" style={{ display: "flex", alignItems: "center", gap: 6, padding: "13px 28px", flexWrap: "wrap" }}>
          {states.map((s) => (
            <button key={s.code} onClick={() => setStateFilter(s.code)} style={{
              padding: "8px 15px", borderRadius: 99, border: "1px solid",
              borderColor: stateFilter === s.code ? "var(--ink-900)" : "var(--line)",
              background: stateFilter === s.code ? "var(--ink-900)" : "transparent",
              color: stateFilter === s.code ? "#fff" : "var(--ink-900)",
              fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 13,
              display: "inline-flex", alignItems: "center", gap: 8,
            }}>
              {s.code === "ALL" ? "All" : s.name}
              <span className="mono" style={{ fontSize: 11, opacity: 0.6 }}>{s.count}</span>
            </button>
          ))}
          <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 8 }}>
            <span className="eyebrow" style={{ fontSize: 9.5, color: "var(--muted-2)" }}>Sort</span>
            <div style={{ display: "flex", border: "1px solid var(--line)", borderRadius: 99, overflow: "hidden" }}>
              {[["snow", "New snow"], ["elev", "Summit"], ["name", "A–Z"]].map(([k, l]) => (
                <button key={k} onClick={() => setSort(k)} style={{ padding: "7px 14px", border: "none", background: sort === k ? "var(--ink-900)" : "transparent", color: sort === k ? "#fff" : "var(--ink-900)", fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 12.5 }}>{l}</button>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div className="wrap" style={{ padding: "30px 28px 70px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,minmax(0,1fr))", gap: 20 }}>
          {featured && <CamCard r={featured} go={go} big />}
          {restCams.map((r) => <CamCard key={r.id} r={r} go={go} />)}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { WebcamsPage, CamCard, CamClock });
