/* ============================================================
   SKI NEW ENGLAND — secondary pages: Resorts, News, Map, Store
   ============================================================ */
function PageHead({ eyebrow, title, sub, edge = "var(--frost-50)" }) {
  return (
    <div style={{ position: "relative", background: "var(--ink-900)", color: "#fff", paddingTop: 44, paddingBottom: edge ? 52 : 36 }}>
      <div className="wrap">
        <div className="eyebrow" style={{ color: "var(--blue-300)", marginBottom: 14 }}>{eyebrow}</div>
        <h1 className="display" style={{ margin: 0, fontSize: "clamp(36px,5.5vw,66px)" }}>{title}</h1>
        {sub && <p className="serif" style={{ fontSize: 18, lineHeight: 1.5, color: "rgba(255,255,255,0.8)", maxWidth: 560, marginTop: 16 }}>{sub}</p>}
      </div>
      {edge && <SnowEdge fill={edge} />}
    </div>
  );
}

/* ---------- Resorts directory ---------- */
function ResortsMapHeader({ data }) {
  return (
    <div style={{ position: "relative", background: "var(--ink-900)", color: "#fff" }}>
      <div className="wrap" style={{ position: "relative", padding: "34px 28px 0" }}>
        <div className="eyebrow" style={{ color: "var(--blue-300)", marginBottom: 12 }}>{data.RESORTS.length} mountains &middot; 6 states</div>
        <h1 className="display" style={{ margin: 0, fontSize: "clamp(34px,5vw,58px)", lineHeight: 1 }}>Every Resort</h1>
        <p className="serif" style={{ fontSize: 17, lineHeight: 1.5, color: "rgba(255,255,255,0.66)", margin: "14px 0 0", maxWidth: 560 }}>From Yawgoo Valley&rsquo;s 245 feet to Sugarloaf&rsquo;s above-treeline snowfields &mdash; the full New England roster.</p>
      </div>
      <div style={{ position: "relative", height: 672, marginTop: 18 }}>
        <iframe src="./resortmap/index.html" title="Every ski resort in New England" loading="lazy"
          referrerPolicy="strict-origin-when-cross-origin"
          style={{ position: "absolute", inset: 0, width: "100%", height: "100%", border: 0, display: "block" }}></iframe>
      </div>
    </div>
  );
}

/* Spinning lifts + trails open = the mountain is running today. Set open: false on a
   resort in data.js (or from the feed) to force it closed regardless of its numbers. */
const isResortOpen = (r) => r.open !== false && !!(r.lifts && r.lifts[0] > 0) && r.trailsOpen > 0;

/* Ranking dropdown — one menu per metric family, single active metric overall */
function RankMenu({ group, sortId, features, onPick }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  const activeItem = group.sections.some((s) => s.items.some((it) => it.id === sortId)) ? SNE_RANK.BY_ID[sortId] : null;
  const activeFeatures = group.sections.reduce((acc, s) => acc.concat(s.items.filter((it) => it.type === "filter" && features.includes(it.id))), []);
  const active = !!activeItem || activeFeatures.length > 0;
  const label = activeItem ? activeItem.label
    : activeFeatures.length ? activeFeatures.map((f) => f.label).join(" · ")
    : group.label;
  const isOn = (it) => (it.type === "filter" ? features.includes(it.id) : sortId === it.id);

  useEffect(() => {
    if (!open) return;
    const away = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    const esc = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("mousedown", away);
    document.addEventListener("keydown", esc);
    return () => { document.removeEventListener("mousedown", away); document.removeEventListener("keydown", esc); };
  }, [open]);

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button onClick={() => setOpen((v) => !v)} style={{
        padding: "8px clamp(9px,1.1vw,14px)", borderRadius: 99, border: "1px solid",
        borderColor: active ? "var(--ink-900)" : "var(--line)",
        background: active ? "var(--ink-900)" : "transparent",
        color: active ? "#fff" : "var(--ink-900)",
        fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 13,
        display: "inline-flex", alignItems: "center", gap: 7, whiteSpace: "nowrap", maxWidth: 230,
      }}>
        <span style={{ overflow: "hidden", textOverflow: "ellipsis" }}>{label}</span>
        <svg width="9" height="6" viewBox="0 0 9 6" fill="none" style={{ flexShrink: 0, opacity: 0.7, transform: open ? "rotate(180deg)" : "" }}>
          <path d="M1 1l3.5 3.5L8 1" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
        </svg>
      </button>
      {open && (
        <div style={{
          position: "absolute", top: "calc(100% + 8px)", left: 0, zIndex: 80, width: 262,
          background: "var(--paper)", border: "1px solid var(--line)", borderRadius: 6,
          boxShadow: "var(--shadow-pop)", padding: "8px 0", maxHeight: 360, overflowY: "auto",
        }}>
          {group.sections.map((s, si) => (
            <div key={si}>
              {s.label && <div className="eyebrow" style={{ fontSize: 8.5, color: "var(--muted-2)", padding: si === 0 ? "4px 14px 6px" : "10px 14px 6px" }}>{s.label}</div>}
              {s.items.map((it) => (
                <button key={it.id} onClick={() => { onPick(it); if (it.type !== "filter") setOpen(false); }} style={{
                  display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, width: "100%",
                  padding: "7px 14px", border: "none", background: isOn(it) ? "var(--frost-50)" : "transparent",
                  fontFamily: "var(--f-display)", fontWeight: isOn(it) ? 700 : 600, fontSize: 13,
                  color: "var(--ink-900)", textAlign: "left", cursor: "pointer",
                }}
                  onMouseEnter={(e) => { e.currentTarget.style.background = "var(--frost-50)"; }}
                  onMouseLeave={(e) => { e.currentTarget.style.background = isOn(it) ? "var(--frost-50)" : "transparent"; }}>
                  {it.label}
                  {isOn(it) && <span className="mono" style={{ fontSize: 11, color: "var(--blue-500)" }}>{it.type === "filter" ? "\u2713" : "\u00d7"}</span>}
                </button>
              ))}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function ResortsPage({ go, data, initialState }) {
  const [stateFilter, setStateFilter] = useState(initialState || "ALL");
  const [surfaceOnly, setSurfaceOnly] = useState(false);
  const [query, setQuery] = useState("");
  const [sortId, setSortId] = useState(null);
  const [features, setFeatures] = useState([]);
  const [openOnly, setOpenOnly] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const searchRef = useRef(null);
  const [, setFeedTick] = useState(0);
  useEffect(() => (window.SNE_API ? SNE_API.subscribe(() => setFeedTick((t) => t + 1)) : undefined), []);
  const pick = (it) => {
    if (it.type === "filter") setFeatures((f) => (f.includes(it.id) ? f.filter((x) => x !== it.id) : f.concat(it.id)));
    else setSortId((cur) => (cur === it.id ? null : it.id));
  };
  const states = [{ code: "ALL", name: "All states", count: data.RESORTS.length }, ...data.STATES];
  const q = query.trim().toLowerCase();
  const metric = sortId ? SNE_RANK.BY_ID[sortId] : null;
  let rows = data.RESORTS.filter((r) => (stateFilter === "ALL" || r.state === stateFilter) &&
    (!surfaceOnly || r.surfaceOnly) &&
    (!openOnly || isResortOpen(r)) &&
    features.every((id) => SNE_RANK.BY_ID[id].test(r)) &&
    (q === "" || `${r.name} ${r.state} ${r.region}`.toLowerCase().includes(q)));
  if (metric) {
    const dir = metric.dir === "asc" ? 1 : -1;
    rows = rows.slice().sort((a, b) => (metric.get(a) - metric.get(b)) * dir || a.name.localeCompare(b.name));
  }

  return (
    <div style={{ background: "var(--frost-50)", minHeight: "100%" }}>
      <ResortsMapHeader data={data} />
      <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", gap: 5, rowGap: 8, padding: "13px 28px", flexWrap: "wrap", alignItems: "center" }}>
          {states.map((s) => (
            <button key={s.code} title={s.name} onClick={() => { setStateFilter(s.code); setSurfaceOnly(false); }} style={{
              padding: "8px clamp(9px,1.1vw,15px)", borderRadius: 99, border: "1px solid", whiteSpace: "nowrap",
              borderColor: stateFilter === s.code && !surfaceOnly ? "var(--ink-900)" : "var(--line)",
              background: stateFilter === s.code && !surfaceOnly ? "var(--ink-900)" : "transparent",
              color: stateFilter === s.code && !surfaceOnly ? "#fff" : "var(--ink-900)",
              fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 13,
              display: "inline-flex", alignItems: "center", gap: 7,
            }}>
              {s.code === "ALL" ? "All" : s.code}
              <span className="mono" style={{ fontSize: 11, opacity: 0.6 }}>{s.count}</span>
            </button>
          ))}
          <button onClick={() => { const next = !surfaceOnly; setSurfaceOnly(next); if (next) setStateFilter("ALL"); }} style={{
            padding: "8px clamp(9px,1.1vw,15px)", borderRadius: 99, border: "1px solid",
            borderColor: surfaceOnly ? "var(--ink-900)" : "var(--line)",
            background: surfaceOnly ? "var(--ink-900)" : "transparent",
            color: surfaceOnly ? "#fff" : "var(--ink-900)",
            fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 13,
            display: "inline-flex", alignItems: "center", gap: 8, whiteSpace: "nowrap",
          }}>
            Surface lift only
            <span className="mono" style={{ fontSize: 11, opacity: 0.6 }}>{data.RESORTS.filter((r) => r.surfaceOnly).length}</span>
          </button>
          <span style={{ width: 1, height: 20, background: "var(--line)", margin: "0 4px", flexShrink: 0 }}></span>
          {SNE_RANK.GROUPS.map((g) => <RankMenu key={g.id} group={g} sortId={sortId} features={features} onPick={pick} />)}
          <button onClick={() => setOpenOnly((v) => !v)} aria-pressed={openOnly} title="Show only resorts currently open" style={{
            padding: "8px clamp(9px,1.1vw,15px)", borderRadius: 99, border: "1px solid",
            borderColor: openOnly ? "var(--ink-900)" : "var(--line)",
            background: openOnly ? "var(--ink-900)" : "transparent",
            color: openOnly ? "#fff" : "var(--ink-900)",
            fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 13,
            display: "inline-flex", alignItems: "center", whiteSpace: "nowrap", flexShrink: 0,
          }}>Open</button>
          <div style={{ marginLeft: "auto", position: "relative", width: 104, height: 34, flexShrink: 0 }}>
            <div onClick={() => { setSearchOpen(true); if (searchRef.current) searchRef.current.focus(); }} style={{
              position: "absolute", top: 0, right: 0, height: 34, width: searchOpen ? 312 : 104, maxWidth: "calc(100vw - 56px)",
              display: "flex", alignItems: "center", gap: 7, padding: "0 11px", borderRadius: 99,
              border: "1px solid", borderColor: searchOpen ? "var(--ink-900)" : "var(--line)",
              background: "var(--paper)", boxShadow: searchOpen ? "var(--shadow-pop)" : "none",
              transition: "width .18s ease, box-shadow .18s ease, border-color .18s ease",
              cursor: "text", zIndex: 3,
            }}>
              <SearchIcon size={14} color="var(--muted-2)" />
              <input ref={searchRef} value={query} type="search" placeholder="Search" aria-label="Search resorts"
                onFocus={() => setSearchOpen(true)}
                onBlur={() => { if (!query) setSearchOpen(false); }}
                onChange={(e) => setQuery(e.target.value)}
                onKeyDown={(e) => { if (e.key === "Escape") { setQuery(""); setSearchOpen(false); e.currentTarget.blur(); } }}
                style={{ width: "100%", minWidth: 0, border: "none", outline: "none", background: "transparent", fontFamily: "var(--f-display)", fontWeight: 600, fontSize: 12.5, color: "var(--ink-900)" }} />
            </div>
          </div>
        </div>
      </div>
      <div className="wrap" style={{ padding: "30px 28px 70px" }}>
        {(metric || features.length > 0 || openOnly || surfaceOnly) && rows.length > 0 && (
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 18 }}>
            <div className="eyebrow" style={{ fontSize: 9.5, color: "var(--muted)" }}>
              {metric ? `Ranked by ${metric.label}` : "Filtered"}
              {openOnly && " \u00b7 Open now"}
              {surfaceOnly && " \u00b7 Surface lift only"}
              {features.length > 0 && ` \u00b7 ${features.map((id) => SNE_RANK.BY_ID[id].label).join(" + ")}`}
              {` \u00b7 ${rows.length} mountains`}
            </div>
            <button onClick={() => { setSortId(null); setFeatures([]); setOpenOnly(false); setSurfaceOnly(false); }} className="mono" style={{ border: "1px solid var(--line)", background: "var(--paper)", borderRadius: 99, padding: "3px 10px", fontSize: 11, color: "var(--muted)", cursor: "pointer" }}>Clear</button>
          </div>
        )}
        {rows.length === 0 ? (
          <div className="mono" style={{ fontSize: 13, color: "var(--muted)", padding: "40px 0" }}>No mountain matches “{query.trim()}”.</div>
        ) : (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 22 }}>
          {rows.map((r, i) => <ResortCard key={r.id} r={r} onOpen={(id) => go("resort", id)}
            rank={metric ? i + 1 : null} statLabel={metric ? metric.unit : null} statValue={metric ? metric.fmt(r) : null} />)}
        </div>
        )}
      </div>
    </div>
  );
}

/* ---------- Store ---------- */
function StorePage({ go, data }) {
  const extended = [
    ...data.STORE,
    { id: "s5", name: "Summit Trucker Cap — Blaze", price: 30, cat: "Headwear", tag: null },
    { id: "s6", name: "New England Trail Map Poster", price: 42, cat: "Prints", tag: "New" },
    { id: "s7", name: "Powder Hound Crewneck", price: 58, cat: "Apparel", tag: null },
    { id: "s8", name: "Six Summits Sticker Pack", price: 12, cat: "Accessories", tag: null },
    { id: "s9", name: "Jay Cloud Hoodie", price: 72, cat: "Apparel", tag: "Best seller" },
    { id: "s10", name: "Base Lodge Enamel Mug", price: 24, cat: "Drinkware", tag: null },
    { id: "s11", name: "Single Chair Tee", price: 34, cat: "Apparel", tag: null },
    { id: "s12", name: "Vermont Ridgeline Beanie", price: 28, cat: "Headwear", tag: null },
    { id: "s13", name: "Corduroy Morning Flannel", price: 86, cat: "Apparel", tag: "New" },
    { id: "s14", name: "Rope Tow Patch Set", price: 16, cat: "Accessories", tag: null },
    { id: "s15", name: "White Mountains Letterpress Print", price: 48, cat: "Prints", tag: null },
    { id: "s16", name: "Après Wool Socks", price: 22, cat: "Accessories", tag: null },
    { id: "s17", name: "Snowfield Insulated Bottle", price: 38, cat: "Drinkware", tag: null },
    { id: "s18", name: "Liftline Canvas Tote", price: 26, cat: "Accessories", tag: null },
    { id: "s19", name: "Northeast Kingdom Quarter-Zip", price: 94, cat: "Apparel", tag: null },
    { id: "s20", name: "Storm Cycle Field Notebook", price: 14, cat: "Accessories", tag: null },
    { id: "s21", name: "Chairlift Keychain", price: 11, cat: "Accessories", tag: null },
    { id: "s22", name: "Summit Marker Pennant", price: 32, cat: "Prints", tag: null },
    { id: "s23", name: "First Tracks Neck Gaiter", price: 19, cat: "Accessories", tag: null },
    { id: "s24", name: "Six States Puffer Vest", price: 128, cat: "Apparel", tag: "New" },
  ];
  return (
    <div style={{ background: "var(--frost-50)", minHeight: "100%", position: "relative" }}>
      <div style={{ position: "absolute", inset: 0, zIndex: 5, background: "rgba(6,19,33,0.74)", backdropFilter: "blur(3px)", display: "flex", alignItems: "flex-start", justifyContent: "center", padding: "140px 28px" }}>
        <div style={{ position: "sticky", top: 140, maxWidth: 470, textAlign: "center", background: "var(--ink-900)", border: "1px solid rgba(255,255,255,0.16)", borderRadius: "var(--radius)", padding: "34px 34px 30px", boxShadow: "var(--shadow-pop)" }}>
          <div className="eyebrow" style={{ fontSize: 9.5, color: "var(--pow)", marginBottom: 12 }}>Under Construction</div>
          <div className="display" style={{ fontSize: 30, fontWeight: 800, color: "#fff", lineHeight: 1.08, margin: 0 }}>The shop is being restocked</div>
          <p className="serif" style={{ fontSize: 15.5, lineHeight: 1.55, color: "rgba(255,255,255,0.68)", margin: "13px 0 20px" }}>We&rsquo;re putting the finishing touches on the store. Check back soon &mdash; in the meantime the mountain reports are all live.</p>
          <button onClick={() => go("conditions")} style={{ fontFamily: "var(--f-mono)", fontSize: 10.5, fontWeight: 600, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink-900)", background: "#fff", border: "none", borderRadius: 4, padding: "11px 20px", cursor: "pointer" }}>See conditions</button>
        </div>
      </div>
      <div aria-hidden="true" style={{ pointerEvents: "none", userSelect: "none" }}>
      <PageHead eyebrow="Our Store" title="The Shop" sub="Layers, hats, and stickers for those who check the snow report before the forecast. Thanks for supporting the ski community." />
      <div className="wrap" style={{ padding: "40px 28px 70px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 22 }}>
          {extended.map((p) => (
            <div key={p.id} style={{ background: "var(--paper)", border: "1px solid var(--line)", borderRadius: 8, overflow: "hidden", boxShadow: "var(--shadow-card)" }}>
              <div style={{ position: "relative", aspectRatio: "1/1", background: "var(--frost-100)" }}>
                {p.img
                  ? <img src={p.img} alt={p.name} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "contain", padding: 10 }} />
                  : <image-slot id={`storepage-${p.id}`} shape="rect" placeholder={p.name} style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}></image-slot>}
                {p.tag && <span style={{ position: "absolute", top: 12, left: 12, fontFamily: "var(--f-mono)", fontSize: 10, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", background: "var(--ink-900)", color: "#fff", padding: "4px 9px", borderRadius: 3 }}>{p.tag}</span>}
              </div>
              <div style={{ padding: "15px 16px 18px" }}>
                <div className="eyebrow" style={{ fontSize: 9, color: "var(--muted)" }}>{p.cat}</div>
                <div style={{ fontWeight: 700, fontSize: 15, margin: "7px 0 10px", lineHeight: 1.2 }}>{p.name}</div>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                  <span className="mono" style={{ fontSize: 15, fontWeight: 600, color: "var(--blue-600)" }}>${p.price}</span>
                  <button className="btn" style={{ padding: "8px 14px", fontSize: 12 }}>Add</button>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
      </div>
    </div>
  );
}

Object.assign(window, { ResortsPage, ResortsMapHeader, StorePage });
