/* ============================================================
   SKI NEW ENGLAND — Weather
   State temperature header · conditions map · regional forecasts
   ============================================================ */
const RANGES = [
  { id: "northern-greens", name: "Northern Greens", states: "VT", ids: ["jay-peak", "stowe", "smugglers-notch", "bolton-valley", "burke", "cochrans", "lyndon-outing-club"], pos: [15, 14] },
  { id: "central-greens", name: "Central Greens", states: "VT", ids: ["sugarbush", "mad-river-glen", "killington", "pico", "middlebury-snow-bowl"], pos: [15, 32] },
  { id: "southern-greens", name: "Southern Greens", states: "VT", ids: ["okemo", "stratton", "mount-snow", "bromley", "magic-mountain"], pos: [13, 50] },
  { id: "white-mountains", name: "White Mountains", states: "NH", ids: ["cannon", "bretton-woods", "loon", "waterville-valley", "attitash", "wildcat", "cranmore", "black-mountain-nh", "tenney-mountain"], pos: [45, 28] },
  { id: "longfellows", name: "Longfellow Mountains", states: "ME", ids: ["sugarloaf", "sunday-river", "saddleback", "black-mountain-me", "mt-abram", "pleasant-mountain", "big-moose", "bigrock", "camden-snow-bowl", "lost-valley", "lonesome-pine", "mt-jefferson", "powderhouse-hill", "spruce-mountain", "titcomb"], pos: [76, 20] },
  { id: "lakes-region", name: "Lakes Region", states: "NH", ids: ["gunstock", "king-pine", "abenaki"], pos: [78, 36] },
  { id: "upper-valley", name: "Upper Valley", states: "VT · NH", ids: ["sunapee", "ragged-mountain", "dartmouth-skiway", "whaleback", "quechee-club", "saskadena-six", "arrowhead", "ascutney-outdoors", "northeast-slopes"], pos: [42, 46] },
  { id: "monadnocks", name: "Monadnocks", states: "NH · RI", ids: ["crotched", "granite-gorge", "pats-peak", "mcintyre", "yawgoo-valley"], pos: [76, 54] },
  { id: "worcester-hills", name: "Worcester Hills", states: "MA", ids: ["wachusett", "ski-ward", "nashoba-valley", "blue-hills"], pos: [45, 68] },
  { id: "berkshires", name: "Berkshires", states: "MA · CT", ids: ["berkshire-east", "jiminy-peak", "mohawk", "ski-sundown", "bousquet", "catamount", "otis-ridge", "mt-southington", "powder-ridge"], pos: [13, 72] },
];

const MAP_PTS = {
  "jay-peak": [30, 8], "stowe": [33, 18], "smugglers-notch": [31, 16], "sugarbush": [34, 24],
  "mad-river-glen": [35, 26], "killington": [38, 34], "okemo": [37, 42], "stratton": [36, 50],
  "mount-snow": [37, 56], "sugarloaf": [62, 12], "saddleback": [60, 16], "sunday-river": [58, 22],
  "cannon": [46, 26], "bretton-woods": [50, 24], "loon": [47, 30], "waterville-valley": [49, 33],
  "berkshire-east": [30, 60], "jiminy-peak": [29, 64], "wachusett": [44, 62],
  "mohawk": [28, 76], "ski-sundown": [33, 78], "yawgoo-valley": [50, 80],
  "bolton-valley": [33, 21], "burke": [40, 12], "middlebury-snow-bowl": [32, 28], "pico": [39, 36],
  "bromley": [34, 48], "magic-mountain": [37, 48], "quechee-club": [42, 38], "saskadena-six": [41, 35],
  "attitash": [50, 28], "wildcat": [53, 25], "cranmore": [52, 30], "black-mountain-nh": [54, 28],
  "tenney-mountain": [46, 36], "gunstock": [49, 41], "king-pine": [53, 33], "sunapee": [45, 46],
  "ragged-mountain": [47, 43], "dartmouth-skiway": [43, 41], "whaleback": [43, 44],
  "crotched": [46, 53], "granite-gorge": [43, 56], "pats-peak": [48, 49], "mcintyre": [50, 53],
  "pleasant-mountain": [56, 31], "mt-abram": [57, 25], "black-mountain-me": [59, 20],
  "big-moose": [60, 7], "bigrock": [67, 5], "camden-snow-bowl": [64, 29], "lost-valley": [58, 34],
  "bousquet": [29, 61], "catamount": [28, 68], "otis-ridge": [31, 64], "ski-ward": [43, 61],
  "nashoba-valley": [46, 58], "blue-hills": [49, 63], "mt-southington": [36, 75], "powder-ridge": [39, 77],
};

const baseElev = (r) => r.summit - r.vertical;
const avg = (xs) => Math.round(xs.reduce((s, x) => s + x, 0) / xs.length);
const DAY_NAMES = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

function tempColor(t) {
  if (t <= 12) return "#5b6fd6";
  if (t <= 20) return "#3b9fe0";
  if (t <= 28) return "#5fb3a1";
  return "#c98a3c";
}
function snowColor(n) {
  if (n >= 9) return "var(--pow)";
  if (n >= 4) return "#3b9fe0";
  if (n >= 1) return "#9fc2dd";
  return "rgba(255,255,255,0.3)";
}

/* ---------- state temperature strip ---------- */
function StateTemps({ data }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(6,minmax(0,1fr))", gap: 10 }}>
      {data.STATES.map((s) => {
        const rs = data.RESORTS.filter((r) => r.state === s.code);
        if (!rs.length) return null;
        const peak = rs.reduce((a, b) => (b.summit > a.summit ? b : a));
        const low = rs.reduce((a, b) => (baseElev(b) < baseElev(a) ? b : a));
        return (
          <div key={s.code} style={{ borderLeft: "1px solid rgba(255,255,255,0.18)", paddingLeft: 9, minWidth: 0 }}>
            <div className="eyebrow" style={{ fontSize: 8.5, color: "rgba(255,255,255,0.62)", marginBottom: 7, whiteSpace: "nowrap" }}>{s.code}</div>
            <div style={{ display: "flex", gap: 7 }}>
              <div style={{ minWidth: 0 }}>
                <div className="display" style={{ fontSize: 17, fontWeight: 800, lineHeight: 1, color: "#fff" }}>{peak.tempF}&deg;</div>
                <div className="mono" style={{ fontSize: 8.5, color: "rgba(255,255,255,0.55)", marginTop: 5, whiteSpace: "nowrap" }}>&#9650;{peak.summit.toLocaleString()}&prime;</div>
              </div>
              <div style={{ minWidth: 0 }}>
                <div className="display" style={{ fontSize: 17, fontWeight: 800, lineHeight: 1, color: "rgba(255,255,255,0.72)" }}>{low.tempF}&deg;</div>
                <div className="mono" style={{ fontSize: 8.5, color: "rgba(255,255,255,0.55)", marginTop: 5, whiteSpace: "nowrap" }}>&#9660;{baseElev(low).toLocaleString()}&prime;</div>
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

/* ---------- conditions map ---------- */
function WeatherMap({ data, go }) {
  const [layer, setLayer] = useState("sky");
  const [hover, setHover] = useState(null);
  const [active, setActive] = useState(null);
  const layers = [["sky", "Conditions"], ["temp", "Temperature"], ["snow", "24h snow"]];
  const activeRange = active ? RANGES.find((g) => g.id === active) : null;
  const hoveredRange = hover ? RANGES.find((g) => g.id === hover) : null;
  const hoveredRs = hoveredRange ? hoveredRange.ids.map((id) => data.RESORTS.find((r) => r.id === id)).filter(Boolean) : [];

  return (
    <div style={{ position: "relative", aspectRatio: "1 / 0.62", background: "var(--ink-850)", borderRadius: 12, border: "1px solid rgba(255,255,255,0.1)", overflow: "hidden" }}>
      <div style={{ position: "absolute", inset: 0, backgroundImage: "radial-gradient(circle at 34% 22%, rgba(59,159,224,0.16), transparent 52%), radial-gradient(circle at 60% 16%, rgba(255,255,255,0.08), transparent 42%), radial-gradient(circle at 42% 74%, rgba(46,158,91,0.07), transparent 48%)" }}></div>
      <svg style={{ position: "absolute", inset: 0, width: "100%", height: "100%", opacity: 0.14 }} preserveAspectRatio="none" viewBox="0 0 100 100">
        <path d="M40 2 L40 60 M28 60 L56 60 M43 28 L62 23 M30 70 L56 72 M56 4 L56 60" stroke="#fff" strokeWidth="0.3" fill="none" />
      </svg>

      <div style={{ position: "absolute", top: 14, right: 16, display: "flex", border: "1px solid rgba(255,255,255,0.18)", borderRadius: 99, overflow: "hidden", zIndex: 6, background: "rgba(0,21,67,0.5)", backdropFilter: "blur(4px)" }}>
        {layers.map(([k, l]) => (
          <button key={k} onClick={() => setLayer(k)} style={{ padding: "7px 14px", border: "none", whiteSpace: "nowrap", background: layer === k ? "#fff" : "transparent", color: layer === k ? "var(--ink-900)" : "rgba(255,255,255,0.8)", fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 12 }}>{l}</button>
        ))}
      </div>

      {RANGES.map((g) => {
        const rs = g.ids.map((id) => data.RESORTS.find((r) => r.id === id)).filter(Boolean);
        if (!rs.length) return null;
        const on = hover === g.id;
        const lead = rs.reduce((a, b) => (b.newSnow > a.newSnow ? b : a));
        const t = avg(rs.map((r) => r.tempF));
        const sel = active === g.id;
        return (
          <button key={g.id} onMouseEnter={() => setHover(g.id)} onMouseLeave={() => setHover(null)} onClick={() => setActive(sel ? null : g.id)}
            style={{ position: "absolute", left: `${g.pos[0]}%`, top: `${g.pos[1]}%`, transform: "translate(-50%,-50%)", display: "flex", alignItems: "center", gap: 9, padding: "7px 13px 7px 9px", borderRadius: 99, whiteSpace: "nowrap", background: sel || on ? "#fff" : "rgba(0,21,67,0.72)", color: sel || on ? "var(--ink-900)" : "#fff", border: "1px solid rgba(255,255,255,0.28)", boxShadow: sel || on ? "var(--shadow-pop)" : "none", zIndex: on || sel ? 7 : 3 }}>
            {layer === "sky" && <SkyIcon sky={lead.sky} size={18} />}
            {layer === "temp" && <span className="display" style={{ display: "grid", placeItems: "center", minWidth: 32, height: 22, padding: "0 7px", borderRadius: 11, background: tempColor(t), color: "#fff", fontWeight: 800, fontSize: 12 }}>{t}&deg;</span>}
            {layer === "snow" && <span className="display" style={{ display: "grid", placeItems: "center", minWidth: 32, height: 22, padding: "0 7px", borderRadius: 11, background: snowColor(lead.newSnow), color: lead.newSnow >= 4 ? "#fff" : "var(--ink-900)", fontWeight: 800, fontSize: 12 }}>{lead.newSnow}&Prime;</span>}
            <span style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 2 }}>
              <span className="display" style={{ fontWeight: 800, fontSize: 13, lineHeight: 1 }}>{g.name}</span>
              <span className="mono" style={{ fontSize: 9.5, opacity: 0.65 }}>{rs.length} mountains</span>
            </span>
          </button>
        );
      })}

      {activeRange && (
        <div style={{ position: "absolute", right: 16, bottom: 46, width: 230, maxHeight: "58%", overflowY: "auto", background: "var(--paper)", borderRadius: 8, boxShadow: "var(--shadow-pop)", zIndex: 8 }} className="thin-scroll">
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, padding: "10px 12px", borderBottom: "1px solid var(--line)" }}>
            <span className="display" style={{ fontWeight: 800, fontSize: 13, color: "var(--ink-900)" }}>{activeRange.name}</span>
            <button onClick={() => setActive(null)} aria-label="Close" style={{ border: "none", background: "none", padding: 0, lineHeight: 1, color: "var(--muted)", fontSize: 15 }}>&times;</button>
          </div>
          {activeRange.ids.map((id) => data.RESORTS.find((r) => r.id === id)).filter(Boolean).map((r) => (
            <button key={r.id} onClick={() => go("resort", r.id)} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, width: "100%", textAlign: "left", padding: "9px 12px", border: "none", borderBottom: "1px solid var(--line-soft)", background: "transparent" }}>
              <span style={{ fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 12.5, color: "var(--ink-900)" }}>{r.name}</span>
              <span className="mono" style={{ fontSize: 10.5, color: r.newSnow >= 6 ? "var(--pow)" : "var(--muted)", whiteSpace: "nowrap" }}>{r.tempF}&deg; · {r.newSnow}&Prime;</span>
            </button>
          ))}
        </div>
      )}

      <div style={{ position: "absolute", left: 16, bottom: 14, display: "flex", gap: 16, alignItems: "center", flexWrap: "wrap" }}>
        {layer === "temp" && [["#5b6fd6", "≤12°"], ["#3b9fe0", "13–20°"], ["#5fb3a1", "21–28°"], ["#c98a3c", "29°+"]].map(([c, l]) => (
          <span key={l} className="eyebrow" style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 9.5, color: "rgba(255,255,255,0.75)" }}><span style={{ width: 11, height: 11, borderRadius: 3, background: c }}></span>{l}</span>
        ))}
        {layer === "snow" && <span className="eyebrow" style={{ fontSize: 9.5, color: "rgba(255,255,255,0.6)" }}>Deepest 24-hour total in each range</span>}
        {layer === "sky" && <span className="eyebrow" style={{ fontSize: 9.5, color: "rgba(255,255,255,0.6)" }}>Current sky by range · click a range for its mountains</span>}
      </div>
      <div className="mono" style={{ position: "absolute", right: 16, bottom: 14, fontSize: 10.5, color: "rgba(255,255,255,0.45)" }}>
        {hoveredRange ? `${hoveredRs.length} mountains · ${avg(hoveredRs.map((r) => r.tempF))}° avg · up to ${Math.max(...hoveredRs.map((r) => r.newSnow))}″ new` : "Click a range to list its mountains"}
      </div>
    </div>
  );
}

/* ---------- one range forecast card ---------- */
function RangeForecast({ range, data, go }) {
  const rs = range.ids.map((id) => data.RESORTS.find((r) => r.id === id)).filter(Boolean);
  if (!rs.length) return null;
  const t = avg(rs.map((r) => r.tempF));
  const snow7 = Array.from({ length: 7 }, (_, d) => Math.max(...rs.map((r) => r.forecast[d] || 0)));
  const total = snow7.reduce((s, x) => s + x, 0);
  const lead = rs.reduce((a, b) => (b.newSnow > a.newSnow ? b : a));
  const today = new Date().getDay();
  const peak = Math.max(4, ...snow7);
  const sway = [0, -2, -5, -3, 1, 3, 2];

  return (
    <div style={{ background: "var(--paper)", border: "1px solid var(--line)", borderRadius: "var(--radius)", boxShadow: "var(--shadow-card)", overflow: "hidden" }}>
      <div style={{ position: "relative", height: 200, background: "var(--ink-850)" }}>
        <image-slot id={`range-${range.id}`} shape="rect" placeholder={`${range.name} header image`} 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.12) 0%, rgba(6,19,33,0.1) 45%, rgba(6,19,33,0.8) 100%)", pointerEvents: "none" }}></div>
        <div style={{ position: "absolute", left: 22, right: 22, bottom: 16, display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 18, flexWrap: "wrap" }}>
          <div>
            <div className="eyebrow" style={{ fontSize: 9.5, color: "rgba(255,255,255,0.75)", marginBottom: 7 }}>{range.states} · {rs.length} mountains</div>
            <h3 className="display" style={{ margin: 0, fontSize: 28, fontWeight: 800, color: "#fff", lineHeight: 1 }}>{range.name}</h3>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 18, color: "#fff" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
              <SkyIcon sky={lead.sky} size={22} />
              <span className="display" style={{ fontSize: 30, fontWeight: 800, lineHeight: 1 }}>{t}&deg;</span>
            </div>
            <div style={{ textAlign: "right" }}>
              <div className="display" style={{ fontSize: 20, fontWeight: 800, color: total >= 8 ? "var(--pow)" : "#fff", lineHeight: 1 }}>{total}&Prime;</div>
              <div className="eyebrow" style={{ fontSize: 9, color: "rgba(255,255,255,0.7)", marginTop: 5 }}>7-day total</div>
            </div>
          </div>
        </div>
      </div>
      <div style={{ padding: "18px 22px 22px" }}>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(7,minmax(0,1fr))", gap: 6 }}>
        {snow7.map((n, d) => {
          const hi = t + sway[d] + 3, lo = t + sway[d] - 9;
          return (
            <div key={d} style={{ textAlign: "center", padding: "10px 4px 11px", borderRadius: 6, background: d === 0 ? "var(--frost-100)" : "var(--frost-50)", border: "1px solid var(--line-soft)" }}>
              <div className="eyebrow" style={{ fontSize: 9, color: d === 0 ? "var(--ink-900)" : "var(--muted-2)" }}>{d === 0 ? "Today" : DAY_NAMES[(today + d) % 7]}</div>
              <div style={{ height: 46, display: "flex", alignItems: "flex-end", justifyContent: "center", marginTop: 8 }}>
                <div style={{ width: 16, height: `${Math.max(3, (n / peak) * 46)}px`, borderRadius: 3, background: n >= 6 ? "var(--pow)" : n >= 1 ? "var(--blue-400)" : "var(--line)" }}></div>
              </div>
              <div className="display" style={{ fontSize: 13, fontWeight: 800, marginTop: 8 }}>{n}&Prime;</div>
              <div className="mono" style={{ fontSize: 10, color: "var(--muted)", marginTop: 4 }}>{hi}&deg;/{lo}&deg;</div>
            </div>
          );
        })}
      </div>

      <div style={{ display: "flex", gap: 7, flexWrap: "wrap", marginTop: 16 }}>
        {rs.map((r) => (
          <button key={r.id} onClick={() => go("resort", r.id)} style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "7px 12px", borderRadius: 99, border: "1px solid var(--line)", background: "transparent", fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 12.5, color: "var(--ink-900)" }}>
            {r.name}
            <span className="mono" style={{ fontSize: 11, color: r.newSnow >= 6 ? "var(--pow)" : "var(--muted)" }}>{r.tempF}&deg; · {r.newSnow}&Prime;</span>
          </button>
        ))}
      </div>
      </div>
    </div>
  );
}

/* ---------- live snow map (iframe) with schematic fallback ----------
   The embedded bundle needs this origin allowlisted on BOTH the token
   Worker and the COG Worker. Until the token endpoint answers, we keep
   the schematic map rather than showing an error box. */
const SNOW_MAP_SRC = "./snowmap/index.html";
const SNOW_TOKEN_PROBE = "https://api.stormchance.io/health";

function LiveSnowMap({ data, go }) {
  return (
    <div style={{ position: "relative", height: "min(78vh,760px)", minHeight: 460, borderRadius: 12, overflow: "hidden", border: "1px solid rgba(255,255,255,0.1)", background: "#0b1119" }}>
      <iframe src={SNOW_MAP_SRC} title="New England snow map — temperature, wind and new snow"
        loading="lazy" referrerPolicy="strict-origin-when-cross-origin"
        style={{ position: "absolute", inset: 0, width: "100%", height: "100%", border: 0, display: "block" }}></iframe>
    </div>
  );
}

function WeatherPage({ go, data }) {
  return (
    <div style={{ background: "var(--frost-50)", minHeight: "100%" }}>
      <div style={{ background: "var(--retro-900)", color: "#fff", paddingTop: 42, paddingBottom: 38 }}>
        <div className="wrap" style={{ display: "grid", gridTemplateColumns: "auto minmax(0,1fr)", gap: 24, alignItems: "center" }}>
          <div>
            <h1 className="display" style={{ margin: 0, fontSize: "clamp(34px,4.6vw,60px)", letterSpacing: "-0.01em", lineHeight: 1, whiteSpace: "nowrap" }}>WEATHER</h1>
          </div>
          <StateTemps data={data} />
        </div>
      </div>

      <div className="wrap" style={{ paddingTop: 26, paddingBottom: 10 }}>
        <LiveSnowMap data={data} go={go} />
      </div>

      <div className="wrap" style={{ padding: "26px 28px 70px" }}>
        <SectionHead eyebrow="By Mountain Range" title="Regional forecasts" />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(430px,1fr))", gap: 18 }}>
          {RANGES.map((g) => <RangeForecast key={g.id} range={g} data={data} go={go} />)}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { WeatherPage, WeatherMap, LiveSnowMap, RangeForecast, StateTemps, MAP_PTS, RANGES });
