/* ============================================================
   SKI NEW ENGLAND — shared components
   Exported to window at the end.
   ============================================================ */
const { useState, useEffect, useRef } = React;
const STATE_NAMES = { VT: "Vermont", NH: "New Hampshire", ME: "Maine", MA: "Massachusetts", CT: "Connecticut", RI: "Rhode Island" };

/* ---------- Map pin icon ---------- */
function MapPinIcon({ size = 20 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M12 21.2 C 12 21.2 18.4 14.6 18.4 9.8 A 6.4 6.4 0 0 0 5.6 9.8 C 5.6 14.6 12 21.2 12 21.2 Z" />
      <circle cx="12" cy="9.7" r="2.3" fill="currentColor" stroke="none" />
    </svg>
  );
}

/* ---------- Store icon ---------- */
function StoreIcon({ size = 20 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M4.6 8.6 L19.4 8.6 L18.4 20.4 L5.6 20.4 Z" />
      <path d="M8.9 10.6 L8.9 6.9 A 3.1 3.1 0 0 1 15.1 6.9 L15.1 10.6" />
    </svg>
  );
}

/* ---------- Snowflake icon ---------- */
function SnowflakeIcon({ size = 20 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" aria-hidden="true">
      <g>
        <path d="M12 2.6 L12 21.4" />
        <path d="M3.86 7.3 L20.14 16.7" />
        <path d="M3.86 16.7 L20.14 7.3" />
      </g>
      <g strokeWidth="1.7">
        <path d="M9.3 4.9 L12 7.1 L14.7 4.9" />
        <path d="M9.3 19.1 L12 16.9 L14.7 19.1" />
        <path d="M4.3 10.6 L5.1 7.4 L8.3 6.9" />
        <path d="M19.7 13.4 L18.9 16.6 L15.7 17.1" />
        <path d="M4.3 13.4 L5.1 16.6 L8.3 17.1" />
        <path d="M19.7 10.6 L18.9 7.4 L15.7 6.9" />
      </g>
    </svg>
  );
}

/* ---------- Webcam icon ---------- */
function WebcamIcon({ size = 20 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <circle cx="10" cy="9" r="6.2" />
      <circle cx="10" cy="9" r="2.1" fill="currentColor" stroke="none" />
      <path d="M16.2 9 L21 6.2 L21 11.8 Z" />
      <path d="M10 15.2 L10 19" />
      <path d="M5.6 21 Q 10 18.4 14.4 21" />
    </svg>
  );
}

/* ---------- Brand mark ---------- */
function Logo({ light = false, size = 158 }) {
  /* the PNG carries ~25% transparent padding top and bottom — crop it with the frame
     instead of offsetting the header, so the header keeps a normal flow box */
  return (
    <span style={{ display: "block", height: size * 0.62, width: size * 2.025, overflow: "hidden" }}>
      <img src="uploads/SNE%20Transparent%20logo.png" alt="Ski New England"
        style={{ height: size, width: size * 2.025, display: "block", marginTop: -size * 0.19,
          filter: light ? "brightness(0) invert(1)" : "none" }} />
    </span>
  );
}

/* Live NWS conditions for one mountain range (null until the fetch lands). */
function useWx(rangeId) {
  const [, bump] = useState(0);
  useEffect(() => (window.SNE_WX ? SNE_WX.subscribe(() => bump((n) => n + 1)) : undefined), []);
  return window.SNE_WX && rangeId ? SNE_WX.get(rangeId) : null;
}

/* ---------- Sky / weather glyphs ---------- */
function SkyIcon({ sky, size = 18, color = "currentColor", night }) {
  const s = (sky || "").toLowerCase();
  const st = { width: size, height: size, display: "block" };
  const hr = new Date().getHours();
  const isNight = night != null ? !!night : (hr < 6 || hr >= 18);
  if (s.includes("heavy") || s.includes("snow")) {
    return (
      <svg style={st} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round">
        <path d="M7 15a4 4 0 0 1 .5-7.9A5 5 0 0 1 17 7a3.5 3.5 0 0 1 .5 7" fill="none" />
        <circle cx="8" cy="19.5" r="0.6" fill={color} stroke="none" />
        <circle cx="12" cy="20.5" r="0.6" fill={color} stroke="none" />
        <circle cx="16" cy="19.5" r="0.6" fill={color} stroke="none" />
      </svg>
    );
  }
  if (s.includes("wind")) {
    return (
      <svg style={st} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round">
        <path d="M3 9h11a2.5 2.5 0 1 0-2.5-2.5M3 14h15a2.5 2.5 0 1 1-2.5 2.5" />
      </svg>
    );
  }
  if (s.includes("clear") || s.includes("sunny")) {
    return isNight ? (
      <svg style={st} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
        <path d="M20 14.2A8.2 8.2 0 0 1 9.8 4 8.4 8.4 0 1 0 20 14.2Z" />
      </svg>
    ) : (
      <svg style={st} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round">
        <circle cx="12" cy="12" r="4" />
        <path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M18.4 5.6 17 7M7 17l-1.4 1.4" />
      </svg>
    );
  }
  // cloudy / partly — the disc behind the cloud is the sun by day, the moon at night
  const partly = s.includes("partly") || s.includes("mostly sunny") || s.includes("mostly clear");
  return (
    <svg style={st} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      {partly && (isNight
        ? <path d="M11.6 9.2A4.2 4.2 0 0 1 6.3 3.9a4.3 4.3 0 1 0 5.3 5.3Z" />
        : <circle cx="8" cy="8" r="3" />)}
      <path d="M7 18a4 4 0 0 1 .5-7.9A5 5 0 0 1 17 10a3.5 3.5 0 0 1 .5 7H7Z" />
    </svg>
  );
}

/* ---------- Trail difficulty bar ---------- */
function TrailBar({ d, height = 8 }) {
  const total = d.green + d.blue + d.black + d.dd || 1;
  const seg = (v, c) => v > 0 ? <div style={{ width: `${(v / total) * 100}%`, background: c }} /> : null;
  return (
    <div style={{ display: "flex", height, borderRadius: 99, overflow: "hidden", gap: 0 }}>
      {seg(d.green, "var(--trail-green)")}
      {seg(d.blue, "var(--trail-blue)")}
      {seg(d.black, "var(--trail-black)")}
      {seg(d.dd, "#000")}
    </div>
  );
}

/* ---------- Live open/closed feed ---------- */
function useOps() {
  const [tick, setTick] = useState(0);
  useEffect(() => {
    if (!window.SNE_OPS) return;
    const off = window.SNE_OPS.subscribe(() => setTick((t) => t + 1));
    window.SNE_OPS.load();
    return off;
  }, []);
  return tick;
}

/* Timestamp of the last successful feed pull, or the current time before it lands. */
function FeedTime() {
  useOps();
  const d = (window.SNE_OPS && window.SNE_OPS.updatedAt()) || new Date();
  const t = d.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });
  const sameDay = d.toDateString() === new Date().toDateString();
  return <React.Fragment>{sameDay ? t : `${d.toLocaleDateString("en-US", { month: "short", day: "numeric" })}, ${t}`}</React.Fragment>;
}

/* ---------- Fresh-snow / pass tag ---------- */
function Tag({ label, kind }) {
  if (!label) return null;
  const isPow = kind === "POW DAY" || label === "POW DAY";
  const isSnow = isPow || label === "FRESH" || kind === "FRESH";
  const bg = isPow ? "var(--pow)" : "rgba(255,255,255,0.16)";
  return (
    <span className={isPow ? "pow-badge" : ""} style={{
      fontFamily: "var(--f-mono)", fontSize: 10.5, fontWeight: 600, letterSpacing: "0.12em",
      textTransform: "uppercase", padding: "4px 9px", borderRadius: 3,
      background: bg, color: "#fff",
      border: isPow ? "none" : "1px solid rgba(255,255,255,0.3)",
      display: "inline-flex", alignItems: "center", gap: 5,
    }}>{isSnow && <SnowflakeIcon size={10} />}{label}</span>
  );
}

/* ---------- Stat readout ---------- */
function Stat({ value, unit, label, big, accent }) {
  return (
    <div>
      <div className="mono tnum" style={{
        fontWeight: 600, lineHeight: 1,
        fontSize: big ? 40 : 24,
        color: accent ? "var(--blue-400)" : "inherit",
        display: "flex", alignItems: "baseline", gap: 3,
      }}>
        {value}
        {unit && <span style={{ fontSize: big ? 15 : 11, fontWeight: 500, opacity: 0.6 }}>{unit}</span>}
      </div>
      <div className="eyebrow" style={{ marginTop: 6, fontSize: 10, color: "var(--muted)" }}>{label}</div>
    </div>
  );
}

/* ---------- Resort card ---------- */
function ResortCard({ r, onOpen, rank, statLabel, statValue }) {
  const ranked = statValue != null;
  const closed = r.open === false || !(r.lifts && r.lifts[0] > 0) || !r.trailsOpen;
  return (
    <button onClick={() => onOpen(r.id)} style={{
      textAlign: "left", border: "1px solid var(--line)", background: "var(--paper)",
      borderRadius: 6, overflow: "hidden", padding: 0, width: "100%",
      boxShadow: "var(--shadow-card)", transition: "transform .14s ease, box-shadow .14s ease",
      display: "flex", flexDirection: "column",
    }}
      onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-3px)"; e.currentTarget.style.boxShadow = "var(--shadow-pop)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.transform = ""; e.currentTarget.style.boxShadow = "var(--shadow-card)"; }}
    >
      <div style={{ position: "relative", aspectRatio: "16/10", background: "var(--ink-850)" }}>
        {(window.SNE_PHOTOS && window.SNE_PHOTOS.card(r.id)) ? (
          <img src={window.SNE_PHOTOS.sized(window.SNE_PHOTOS.card(r.id), 640)} alt={`${r.name}`} loading="lazy" decoding="async"
            style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", filter: closed ? "grayscale(0.75)" : "none", opacity: closed ? 0.62 : 1 }} />
        ) : (
          <image-slot id={`card-${r.id}`} shape="rect" placeholder={`${r.name} photo`}
            style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}></image-slot>
        )}
        <div style={{ position: "absolute", top: 10, left: 10, display: "flex", gap: 6, alignItems: "center" }}>
          {rank != null && (
            <span className="mono tnum" style={{ fontSize: 11, fontWeight: 600, color: "var(--ink-900)", background: "#fff", padding: "4px 8px", borderRadius: 3 }}>#{rank}</span>
          )}
          {closed ? (
            <span className="mono" style={{ fontSize: 10, fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase", color: "#fff", background: "rgba(11,31,51,0.88)", padding: "4px 8px", borderRadius: 3 }}>Closed</span>
          ) : <Tag label={r.tag} kind={r.tag} />}
        </div>
        <div style={{ position: "absolute", top: 10, right: 10,
          fontFamily: "var(--f-mono)", fontSize: 11, fontWeight: 600, color: "#fff",
          background: "rgba(6,19,33,0.6)", backdropFilter: "blur(4px)", padding: "4px 8px", borderRadius: 3 }}>
          {r.state}
        </div>
      </div>
      <div style={{ padding: "15px 16px 17px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 10 }}>
          <div>
            <div style={{ fontWeight: 800, fontSize: 19, letterSpacing: "-0.01em", lineHeight: 1 }}>{r.name}</div>
            <div className="eyebrow" style={{ fontSize: 9.5, color: "var(--muted)", marginTop: 5 }}>{r.surfaceOnly ? STATE_NAMES[r.state] || r.state : r.region}</div>
          </div>
          <div className="mono tnum" style={{ textAlign: "right", flexShrink: 0 }}>
            <div style={{ fontSize: ranked ? 20 : 22, fontWeight: 600, color: ranked ? "var(--ink-900)" : (r.newSnow >= 6 ? "var(--pow)" : "var(--blue-500)"), lineHeight: 1 }}>
              {ranked ? statValue : <>{r.newSnow}&Prime;</>}
            </div>
            <div className="eyebrow" style={{ fontSize: 8.5, color: "var(--muted)", marginTop: 3 }}>{ranked ? statLabel : "new (24h)"}</div>
          </div>
        </div>
        <div style={{ margin: "14px 0 10px" }}><TrailBar d={r.difficulty} /></div>
        <div style={{ display: "flex", gap: 16, alignItems: "center",
          fontFamily: "var(--f-mono)", fontSize: 11.5, color: "var(--muted)" }}>
          <span><strong style={{ color: "var(--ink-900)" }}>{r.base == null ? "—" : r.base + '"'}</strong> base</span>
          <span><strong style={{ color: "var(--ink-900)" }}>{r.stats ? `${r.stats.liftsOpen}/${r.stats.lifts}` : `${r.lifts[0]}/${r.lifts[1]}`}</strong> lifts</span>
          <span><strong style={{ color: "var(--ink-900)" }}>{r.stats ? r.stats.trailsOpen : r.trailsOpen}</strong> trails</span>
        </div>
      </div>
    </button>
  );
}

/* ---------- Section header ---------- */
function SectionHead({ eyebrow, title, action, onAction, light }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end",
      marginBottom: 26, gap: 20, flexWrap: "wrap" }}>
      <div>
        {eyebrow && <div className="eyebrow" style={{ color: light ? "var(--blue-300)" : "var(--blue-500)", marginBottom: 10 }}>{eyebrow}</div>}
        <h2 className="display" style={{ margin: 0, fontSize: "clamp(26px,3.4vw,40px)", color: light ? "#fff" : "var(--ink-900)" }}>{title}</h2>
      </div>
      {action && (
        <button className="btn btn--ghost" onClick={onAction}
          style={light ? { color: "#fff", borderColor: "rgba(255,255,255,0.3)" } : {}}>
          {action}
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M5 12h14M13 6l6 6-6 6" /></svg>
        </button>
      )}
    </div>
  );
}

/* ---------- Resort search ---------- */
function SearchIcon({ size = 20, color = "currentColor" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2.1" strokeLinecap="round" aria-hidden="true" style={{ flex: "0 0 auto" }}>
      <circle cx="10.6" cy="10.6" r="6.6" />
      <path d="M15.4 15.4 L20.6 20.6" />
    </svg>
  );
}

function ResortSearch({ resorts, go }) {
  const [q, setQ] = useState("");
  const [open, setOpen] = useState(false);
  const [box, setBox] = useState(null);
  const wrapRef = useRef(null);
  const inputRef = useRef(null);

  const hits = q.trim()
    ? resorts.filter((r) => `${r.name} ${r.state} ${r.region}`.toLowerCase().includes(q.trim().toLowerCase())).slice(0, 7)
    : [];

  const measure = () => {
    const el = wrapRef.current;
    if (el) { const b = el.getBoundingClientRect(); setBox({ top: b.bottom + 9, right: Math.max(12, window.innerWidth - b.right) }); }
  };
  useEffect(() => { if (open) measure(); }, [open, q]);
  useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false); };
    const onMove = () => measure();
    document.addEventListener("mousedown", onDoc);
    window.addEventListener("resize", onMove);
    window.addEventListener("scroll", onMove, true);
    return () => { document.removeEventListener("mousedown", onDoc); window.removeEventListener("resize", onMove); window.removeEventListener("scroll", onMove, true); };
  }, [open]);

  const pick = (id) => { setQ(""); setOpen(false); go("resort", id); };

  useEffect(() => { if (open && inputRef.current) inputRef.current.focus(); }, [open]);

  return (
    <div ref={wrapRef} style={{ display: "flex", flex: "0 0 auto" }}>
      <button className="icon-btn btn btn--retro" onClick={() => setOpen((v) => !v)}
        aria-label="Search resorts" data-tip="Search Resorts"
        style={{ padding: "10px 12px", display: "inline-flex", alignItems: "center", justifyContent: "center", background: open ? "var(--retro-950)" : undefined }}>
        <SearchIcon />
      </button>
      {open && box && ReactDOM.createPortal(
        <div style={{ position: "fixed", top: box.top, right: box.right, width: 320, maxWidth: "calc(100vw - 24px)", background: "var(--paper)", border: "1px solid var(--line)", borderRadius: 8, boxShadow: "var(--shadow-pop)", overflow: "hidden", zIndex: 80 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "12px 14px", borderBottom: "1px solid var(--line)" }}>
            <SearchIcon size={15} color="var(--muted-2)" />
            <input ref={inputRef} value={q} type="search" placeholder="Search resorts" aria-label="Search resorts"
              onChange={(e) => setQ(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Escape") { setQ(""); setOpen(false); } if (e.key === "Enter" && hits[0]) pick(hits[0].id); }}
              style={{ width: "100%", minWidth: 0, border: "none", outline: "none", background: "transparent", fontFamily: "var(--f-display)", fontWeight: 600, fontSize: 14, color: "var(--ink-900)" }} />
          </div>
          {q.trim() === "" ? (
            <div className="mono" style={{ padding: "14px", fontSize: 11.5, color: "var(--muted-2)" }}>Type a mountain, state, or region</div>
          ) : hits.length === 0 ? (
            <div className="mono" style={{ padding: "14px", fontSize: 12, color: "var(--muted)" }}>No mountain matches &ldquo;{q.trim()}&rdquo;</div>
          ) : hits.map((r) => (
            <button key={r.id} onClick={() => pick(r.id)}
              style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, width: "100%", textAlign: "left", padding: "11px 14px", border: "none", borderBottom: "1px solid var(--line-soft)", background: "transparent" }}>
              <span>
                <span style={{ display: "block", fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 14, color: "var(--ink-900)" }}>{r.name}</span>
                <span className="mono" style={{ fontSize: 10.5, color: "var(--muted)" }}>{r.state} · {r.region}</span>
              </span>
              <span className="mono" style={{ fontSize: 11, color: r.newSnow >= 6 ? "var(--pow)" : "var(--muted-2)", whiteSpace: "nowrap" }}>{r.newSnow}&Prime;</span>
            </button>
          ))}
        </div>, document.body)}
    </div>
  );
}

/* ---------- Top nav ---------- */
function Header({ route, go, resorts, showTicker = true }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const el = document.querySelector("#app-scroll");
    const onScroll = () => setScrolled((el ? el.scrollTop : window.scrollY) > 12);
    const t = el || window;
    t.addEventListener("scroll", onScroll);
    return () => t.removeEventListener("scroll", onScroll);
  }, []);

  const links = [
    { id: "resorts", label: "Resorts" },
    { id: "weather", label: "Weather" },
    { id: "news", label: "News" },
    { id: "store", label: "Store" },
  ];
  const iconLinks = [
    { id: "conditions", label: "Live Conditions", Icon: SnowflakeIcon },
    { id: "webcams", label: "Mountain Webcams", Icon: WebcamIcon },
  ];
  /* only areas the conditions feed tracks count toward the totals */
  const tracked = window.SNE_OPS ? SNE_OPS.tracked(resorts) : resorts;
  const powCount = tracked.filter((r) => r.newSnow >= 6).length;
  /* counts come from the feed itself — it tracks areas the site doesn't list */
  const feed = window.SNE_OPS && SNE_OPS.feedTotals().total ? SNE_OPS.feedTotals() : null;
  const openCount = feed ? feed.open : tracked.filter((r) => r.open !== false).length;
  const trackedTotal = feed ? feed.total : tracked.length;

  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 50,
      background: scrolled ? "rgba(255,255,255,0.92)" : "var(--paper)",
      backdropFilter: scrolled ? "blur(10px)" : "none",
      borderBottom: "1px solid var(--line)",
      transition: "background .2s ease",
      height: 147, overflow: "hidden",
    }}>
      {/* fresh-snow ticker strip */}
      {showTicker && (
      <div style={{ background: "var(--retro-900)", color: "#fff", overflow: "hidden", height: 30,
        display: "flex", alignItems: "center" }}>
        <div className="wrap" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", width: "100%" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
            <span style={{ width: 7, height: 7, borderRadius: "50%", background: powCount ? "var(--pow)" : "var(--trail-green)", boxShadow: powCount ? "0 0 8px var(--pow)" : "0 0 8px var(--trail-green)" }} className={powCount ? "pow-badge" : undefined} />
            <span className="eyebrow" style={{ fontSize: 10.5 }}>{powCount
              ? `${powCount} mountains reporting 6″+ fresh`
              : `${openCount} of ${trackedTotal} mountains open`}</span>
          </div>
          <div className="mono" style={{ fontSize: 10.5, color: "rgba(255,255,255,0.6)", letterSpacing: "0.04em" }}>
            Conditions Updated <FeedTime />
          </div>
        </div>
      </div>
      )}

      <div className="wrap" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, height: 98, marginTop: 19 }}>
        <button onClick={() => go("home")} style={{ background: "none", border: "none", padding: 0, flex: "0 1 auto", minWidth: 0 }}>
          <Logo />
        </button>
        <nav style={{ display: "flex", alignItems: "center", gap: 2, flexWrap: "nowrap", minWidth: 0 }}>
          {links.map((l) => (
            <button key={l.id} onClick={() => go(l.id)} style={{
              background: "none", border: "none", padding: "9px clamp(6px,1vw,13px)",
              fontFamily: "var(--f-display)", fontWeight: 700, fontSize: "clamp(13px,1.45vw,20px)",
              color: route === l.id ? "var(--blue-500)" : "var(--ink-900)",
              position: "relative", whiteSpace: "nowrap",
            }}>
              {l.label}
              {route === l.id && <span style={{ position: "absolute", left: 13, right: 13, bottom: 2, height: 2, background: "var(--blue-500)", borderRadius: 2 }} />}
            </button>
          ))}
          {iconLinks.map((l, i) => (
            <button key={l.id} className="icon-btn btn btn--retro" onClick={() => go(l.id)}
              aria-label={l.label} data-tip={l.label}
              style={{ marginLeft: i === 0 ? "clamp(4px,0.8vw,10px)" : 8, padding: "10px 12px", flex: "0 0 auto", display: "inline-flex", alignItems: "center", justifyContent: "center", background: route === l.id ? "var(--retro-950)" : undefined }}>
              <l.Icon />
            </button>
          ))}
        </nav>
      </div>
    </header>
  );
}

/* ---------- Footer ---------- */
function Footer({ go, states }) {
  return (
    <footer style={{ background: "var(--retro-900)", color: "rgba(255,255,255,0.7)" }}>
      <LiftScene />
      <div style={{ paddingTop: 50 }}>
      <div className="wrap" style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1fr", gap: 40, paddingBottom: 46 }}>
        <div>
          <Logo light size={104} />
          <p className="serif" style={{ fontSize: 15, lineHeight: 1.55, marginTop: 18, maxWidth: 280, color: "rgba(255,255,255,0.6)" }}>
            The independent guide to skiing and riding all six New England states — conditions, forecasts, and the mountains we love.
          </p>
        </div>
        {[
          { h: "Explore", items: ["Conditions", "Resorts", "Interactive Map", "Webcams"] },
          { h: "Read", items: ["Snow Forecast", "Field Reports", "Trip Guides", "Best Resorts"] },
          { h: "Shop", items: ["New Arrivals", "Headwear", "Apparel", "Gift Cards"] },
        ].map((col) => (
          <div key={col.h} style={{ paddingTop: 35 }}>
            <div className="eyebrow" style={{ color: "#fff", marginBottom: 16 }}>{col.h}</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
              {col.items.map((i) => <a key={i} href="#" onClick={(e) => e.preventDefault()} style={{ fontSize: 14, color: "rgba(255,255,255,0.62)" }}>{i}</a>)}
            </div>
          </div>
        ))}
      </div>
      <div style={{ borderTop: "1px solid rgba(255,255,255,0.14)", background: "var(--retro-950)" }}>
        <div className="wrap" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "20px 28px", flexWrap: "wrap", gap: 12 }}>
          <div className="mono" style={{ fontSize: 11.5, color: "rgba(255,255,255,0.45)" }}>© 2026 Ski New England · Not affiliated with any resort</div>
          <div style={{ display: "flex", gap: 18 }} className="mono">
            {["Privacy", "Terms", "Advertise", "Contact"].map((i) => <a key={i} href="#" onClick={(e) => e.preventDefault()} style={{ fontSize: 11.5, color: "rgba(255,255,255,0.45)" }}>{i}</a>)}
          </div>
        </div>
      </div>
      </div>
    </footer>
  );
}

/* ---------- Live webcam surface ----------
   Renders a real feed when one is mapped in camfeeds.js, otherwise
   falls back to the drop-in image slot so editors can still place a still. */
function LiveCam({ r, slotId, placeholder, still, interactive = false }) {
  const cam = window.SNE_CAMS ? window.SNE_CAMS.getCam(r.id) : null;
  const [tick, setTick] = useState(() => Math.floor(Date.now() / 1000));
  const [failed, setFailed] = useState(false);
  // YouTube refuses to play when it cannot verify the embedding origin
  // (error 153 — happens inside sandboxed preview frames). Fall back to the
  // stream's poster frame rather than showing YouTube's error card.
  const [ytBlocked, setYtBlocked] = useState(false);
  const frameRef = useRef(null);

  useEffect(() => {
    if (!cam || cam.kind !== "img") return;
    const ms = (cam.every || 60) * 1000;
    const t = setInterval(() => setTick(Math.floor(Date.now() / 1000)), ms);
    return () => clearInterval(t);
  }, [cam && cam.src]);

  useEffect(() => {
    if (!cam || cam.kind !== "yt") return;
    setYtBlocked(false);
    const f = frameRef.current;
    if (!f) return;
    let pingT = null, stopT = null;
    const ping = () => { try { f.contentWindow.postMessage(JSON.stringify({ event: "listening", id: 1 }), "*"); } catch (e) {} };
    const onMsg = (e) => {
      if (e.source !== f.contentWindow) return;
      if (typeof e.origin !== "string" || !/^https:\/\/(www\.)?youtube(-nocookie)?\.com$/.test(e.origin)) return;
      let d = e.data;
      if (typeof d === "string") { try { d = JSON.parse(d); } catch (x) { return; } }
      if (!d) return;
      if (d.event === "onReady") ping();
      if (d.event === "onError") setYtBlocked(true);
    };
    // The iframe is lazy, so the handshake has to start when it actually
    // loads — a mount-time timer expires long before an off-screen cam exists.
    const begin = () => {
      clearInterval(pingT); clearTimeout(stopT);
      ping();
      pingT = setInterval(ping, 1200);
      stopT = setTimeout(() => clearInterval(pingT), 12000);
    };
    window.addEventListener("message", onMsg);
    f.addEventListener("load", begin);
    begin();
    return () => { window.removeEventListener("message", onMsg); f.removeEventListener("load", begin); clearInterval(pingT); clearTimeout(stopT); };
  }, [cam && cam.id]);

  const fill = { position: "absolute", inset: 0, width: "100%", height: "100%" };
  if (cam && !failed) {
    if (cam.kind === "frame") {
      return (
        <iframe src={cam.src} title={`${r.name} live webcam`} loading="lazy" allow="autoplay; encrypted-media; fullscreen" allowFullScreen scrolling="no"
          style={{ ...fill, border: 0, pointerEvents: interactive ? "auto" : "none" }}></iframe>
      );
    }
    if (cam.kind === "yt") {
      if (ytBlocked) {
        return (
          <React.Fragment>
            <img src={`https://i.ytimg.com/vi/${cam.id}/maxresdefault.jpg`} alt={`${r.name} webcam`}
              onError={(e) => { e.target.src = `https://i.ytimg.com/vi/${cam.id}/hqdefault.jpg`; }}
              style={{ ...fill, objectFit: "cover" }} />
            {interactive && (
              <a href={`https://www.youtube.com/watch?v=${cam.id}`} target="_blank" rel="noopener noreferrer"
                style={{ position: "absolute", left: "50%", top: "50%", transform: "translate(-50%,-50%)", display: "inline-flex", alignItems: "center", gap: 9, padding: "10px 18px", borderRadius: 99, background: "rgba(6,19,33,0.74)", backdropFilter: "blur(6px)", color: "#fff", textDecoration: "none", fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 13.5, border: "1px solid rgba(255,255,255,0.28)" }}>
                <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M7 4.5v15l13-7.5z" /></svg>
                Watch live
              </a>
            )}
          </React.Fragment>
        );
      }
      return (
        <iframe ref={frameRef} src={window.SNE_CAMS.camEmbed(cam)} title={`${r.name} live webcam`} loading="lazy" allow="autoplay; encrypted-media; picture-in-picture" allowFullScreen
          style={{ ...fill, border: 0, pointerEvents: interactive ? "auto" : "none" }}></iframe>
      );
    }
    return (
      <img src={window.SNE_CAMS.camStill(cam, tick)} alt={`${r.name} live webcam`} onError={() => setFailed(true)}
        style={{ ...fill, objectFit: "cover" }} />
    );
  }
  return <image-slot id={slotId} shape="rect" placeholder={placeholder} src={still} style={fill}></image-slot>;
}

Object.assign(window, { useOps, FeedTime, LiveCam, useWx, Logo, SkyIcon, TrailBar, Tag, Stat, ResortCard, SectionHead, Header, Footer, WebcamIcon, SnowflakeIcon, MapPinIcon, StoreIcon, ResortSearch, SearchIcon, STATE_NAMES });
