/* ============================================================
   SKI NEW ENGLAND — Home
   ============================================================ */
/* Forecast snow for the next 24h at the resort's own NWS grid square. */
const wxSnow = (r) => {
  const w = window.SNE_WX ? SNE_WX.forResort(r) : null;
  return w && w.snow24 != null ? w.snow24 : r.newSnow;
};

function SnowTile({ r, i, go, metric }) {
  const trails = metric === "trails";
  const inches = !trails;
  const snow = wxSnow(r);
  const val = metric === "snow" ? snow : metric === "base" ? (r.base == null ? "—" : r.base) : r.trailsOpen;
  const cap = metric === "snow" ? "next 24h" : metric === "base" ? "base depth" : "of " + r.trailsTotal;
  const hot = metric === "snow" ? snow >= 6 : metric === "base" ? r.base >= 50 : r.trailsOpen === r.trailsTotal;
  const pct = Math.round((r.trailsOpen / (r.trailsTotal || 1)) * 100);
  return (
    <button onClick={() => go("resort", r.id)} style={{
      position: "relative", textAlign: "left", background: "var(--paper)",
      border: "1px solid var(--line)", borderRadius: 6, padding: "9px 10px 11px", overflow: "hidden",
      boxShadow: "var(--shadow-card)", display: "flex", flexDirection: "column",
      minWidth: 0, transition: "transform .15s ease, box-shadow .15s ease, border-color .15s ease",
    }}
      onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.boxShadow = "0 10px 28px rgba(6,19,33,0.13)"; e.currentTarget.style.borderColor = "var(--blue-300)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.transform = "none"; e.currentTarget.style.boxShadow = "var(--shadow-card)"; e.currentTarget.style.borderColor = "var(--line)"; }}
    >
      <span style={{ fontWeight: 800, fontSize: 13.5, lineHeight: 1.18, letterSpacing: "-0.01em", textWrap: "pretty", minHeight: "2.36em" }}>{r.name}</span>
      <span style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 5, marginTop: "auto", paddingTop: 6, minWidth: 0 }}>
        <span className="mono tnum" style={{ fontSize: 26, fontWeight: 600, lineHeight: 0.8, color: hot ? "var(--sky-cta)" : "var(--blue-600)" }}>{val}{inches ? <>&Prime;</> : null}</span>
        <span className="eyebrow" style={{ fontSize: 8.5, color: "var(--muted-2)", whiteSpace: "nowrap" }}>{cap}</span>
      </span>
      <span style={{ position: "absolute", left: 0, right: 0, bottom: 0, height: 2, background: "var(--line-soft)" }}>
        <span style={{ display: "block", height: "100%", width: pct + "%", background: i === 0 ? "var(--sky-cta)" : "var(--blue-300)" }} />
      </span>
    </button>
  );
}

function SnowList({ label, note, rows, go, metric, style, labelStyle }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12, minWidth: 0, ...style }}>
      <div style={{ display: "flex", flexDirection: "column", justifyContent: "flex-end", gap: 4, minHeight: 49, paddingBottom: 8, borderBottom: "1px solid rgba(255,255,255,0.18)" }}>
        <span className="eyebrow" style={{ color: "#fff", fontSize: 10, ...labelStyle }}>{label}</span>
        <span className="mono" style={{ fontSize: 10, color: "rgba(255,255,255,0.55)" }}>{note}</span>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr)", gap: 9 }}>
        {rows.map((r, i) => <SnowTile key={r.id} r={r} i={i} go={go} metric={metric} />)}
      </div>
    </div>
  );
}

/* ---------- live conditions + the map ---------- */
function ConditionsSection({ go, resorts }) {
  const [, wxTick] = useState(0);
  useEffect(() => (window.SNE_WX ? SNE_WX.subscribe(() => wxTick((n) => n + 1)) : undefined), []);
  useEffect(() => { if (window.SNE_WX) SNE_WX.prefetchResorts(); }, []);
  const bySnow = [...resorts].sort((a, b) => wxSnow(b) - wxSnow(a)).slice(0, 4);
  const byTrails = [...resorts].sort((a, b) => b.trailsOpen - a.trailsOpen).slice(0, 4);
  const byBase = [...resorts].sort((a, b) => b.base - a.base).slice(0, 4);
  const sum = (f) => resorts.reduce((n, r) => n + f(r), 0);
  const fmt = (n) => n.toLocaleString("en-US");
  const deepest = resorts.reduce((n, r) => Math.max(n, wxSnow(r)), 0);
  const avgBase = Math.round(sum((r) => r.base) / (resorts.length || 1));
  const stats = [
    [deepest + "\u2033", null, "deepest next 24h"],
    [avgBase + "\u2033", null, "average base"],
    [fmt(sum((r) => r.trailsOpen)), "of " + fmt(sum((r) => r.trailsTotal)), "trails open"],
    [fmt(sum((r) => r.lifts[0])), "of " + fmt(sum((r) => r.lifts[1])), "lifts spinning"],
    [resorts.length, null, "areas tracked"],
  ];
  return (
    <section style={{ position: "relative", padding: "58px 0 92px", background: "var(--retro-900)", color: "#fff" }}>
      <div className="wrap">
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 28, flexWrap: "wrap", marginBottom: 26 }}>
          <div style={{ minWidth: 280, flex: "1 1 380px" }}>
            <div className="eyebrow" style={{ color: "var(--blue-300)", marginBottom: 10, display: "flex", alignItems: "center", gap: 9 }}>
              LAST UPDATED &middot; <FeedTime />
            </div>
            <h2 className="display" style={{ margin: 0, fontSize: "clamp(26px,3.4vw,40px)" }}>LATEST CONDITIONS</h2>
            <p className="serif" style={{ fontSize: 16.5, lineHeight: 1.45, color: "rgba(255,255,255,0.78)", margin: "11px 0 0", maxWidth: 440 }}>
              Where the snow fell overnight and where the most terrain is turning. Full numbers for 40+ areas on the conditions board.
            </p>
          </div>
          <div style={{ display: "flex", alignItems: "flex-end", gap: 20, flexWrap: "wrap", paddingBottom: 4 }}>
            {stats.map((s, i) => (
              <div key={s[2]} style={{ paddingLeft: i === 0 ? 0 : 20, borderLeft: i === 0 ? "none" : "1px solid rgba(255,255,255,0.2)" }}>
                <div style={{ display: "flex", alignItems: "baseline", gap: 5 }}>
                  <span className="mono tnum" style={{ fontSize: 22, fontWeight: 600, color: "#fff", lineHeight: 1 }}>{s[0]}</span>
                  {s[1] && <span className="mono tnum" style={{ fontSize: 11.5, color: "rgba(255,255,255,0.6)" }}>{s[1]}</span>}
                </div>
                <div className="eyebrow" style={{ fontSize: 9, color: "rgba(255,255,255,0.62)", marginTop: 7 }}>{s[2]}</div>
              </div>
            ))}
          </div>
        </div>
        <div className="cond-body">
          <div style={{ display: "flex", flexDirection: "column", gap: 20, minWidth: 0 }}>
            <div className="cond-lists">
              <SnowList label="Most recent snow" note="past 24 hours" rows={bySnow} go={go} metric="snow" />
              <SnowList label="Most snow depth" note="settled base" rows={byBase} go={go} metric="base" />
              <SnowList label="Most trails open" note="of total terrain" rows={byTrails} go={go} metric="trails" />
            </div>
            <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
              <button className="btn btn--sky" onClick={() => go("conditions")}>
                Full conditions board
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M5 12h14M13 6l6 6-6 6" /></svg>
              </button>
              <button className="btn btn--light" onClick={() => go("weather")}>Snow forecast</button>
            </div>
          </div>
          <MapModule go={go} resorts={resorts} style={{ height: "100%", minHeight: 460 }} />
        </div>
      </div>
    </section>
  );
}

/* ---------- hero background slideshow ---------- */
/* resort hero shots pulled from the same photo manifest the resort pages use */
const resortShot = (id, file) => (window.SNE_PHOTOS ? SNE_PHOTOS.BASE + file : file);
const HERO_SLIDES = [
  { id: "hero-jay", src: "uploads/jay%20header.png", label: "Jay Peak, VT" },
  { id: "hero-killington", src: resortShot("killington", "killington/Killington6.png"), label: "Killington, VT" },
  { id: "hero-sugarloaf", src: resortShot("sugarloaf", "sugarloaf/sugarloaf2.png"), label: "Sugarloaf, ME" },
  { id: "hero-burke", src: "uploads/Burke%20Header.jpg", label: "Burke Mountain, VT" },
  { id: "hero-loon", src: resortShot("loon", "loon/loon3.png"), label: "Loon Mountain, NH" },
  { id: "hero-cannon", src: "uploads/Cannon%20Header.png", label: "Cannon Mountain, NH" },
  { id: "hero-stratton", src: resortShot("stratton", "stratton/stratton1.png"), label: "Stratton, VT" },
  { id: "hero-mtsnow", src: "uploads/mt%20snow%20header1.png", label: "Mount Snow, VT" },
  { id: "hero-jiminy", src: resortShot("jiminy-peak", "jiminy-peak/jiminypeak2.png"), label: "Jiminy Peak, MA" },
];

function HeroSlideshow({ idx, onPause }) {
  return (
    <div style={{ position: "absolute", inset: 0 }}
      onMouseEnter={() => onPause(true)} onMouseLeave={() => onPause(false)}
    >
      {HERO_SLIDES.map((s, i) => (
        <div key={s.id} aria-hidden={i !== idx} style={{
          position: "absolute", inset: 0, opacity: i === idx ? 1 : 0,
          transition: "opacity 1.1s ease",
        }}>
          <img src={s.src} alt={s.label} loading={i === 0 ? "eager" : "lazy"}
            style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", objectPosition: "center 42%" }} />
        </div>
      ))}
    </div>
  );
}

/* carousel controls — live in the hero's content flow, never over other hero content */
function HeroCarouselControls({ idx, go }) {
  const arrow = {
    width: 38, height: 38, borderRadius: "50%", display: "grid", placeItems: "center", flex: "0 0 auto",
    background: "rgba(6,19,33,0.34)", backdropFilter: "blur(6px)",
    border: "1px solid rgba(255,255,255,0.28)", color: "#fff", cursor: "pointer",
    transition: "background .15s ease, border-color .15s ease",
  };
  const onEnter = (e) => { e.currentTarget.style.background = "rgba(6,19,33,0.62)"; e.currentTarget.style.borderColor = "rgba(255,255,255,0.55)"; };
  const onLeave = (e) => { e.currentTarget.style.background = "rgba(6,19,33,0.34)"; e.currentTarget.style.borderColor = "rgba(255,255,255,0.28)"; };
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 9 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, fontFamily: "var(--f-mono)", fontSize: 10.5, fontWeight: 600, letterSpacing: "0.12em", textTransform: "uppercase", color: "#fff", textAlign: "center", marginLeft: 15 }}>
        <span style={{ width: 5, height: 5, borderRadius: "50%", background: "var(--blue-300)" }} />
        {HERO_SLIDES[idx].label}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
        <button aria-label="Previous photo" style={arrow} onMouseEnter={onEnter} onMouseLeave={onLeave} onClick={() => go(idx - 1)}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6" /></svg>
        </button>
        <div style={{ display: "flex", gap: 9 }}>
          {HERO_SLIDES.map((s, i) => (
            <button key={s.id} aria-label={`Go to photo ${i + 1}`} onClick={() => go(i)} style={{
              width: i === idx ? 26 : 9, height: 9, borderRadius: 99, padding: 0, border: "none", cursor: "pointer",
              background: i === idx ? "var(--blue-300)" : "rgba(255,255,255,0.45)",
              transition: "width .3s ease, background .2s ease",
            }} />
          ))}
        </div>
        <button aria-label="Next photo" style={arrow} onMouseEnter={onEnter} onMouseLeave={onLeave} onClick={() => go(idx + 1)}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 18l6-6-6-6" /></svg>
        </button>
      </div>
    </div>
  );
}

function Hero({ go, resorts, heroText = "THE SLOPES ARE CALLING." }) {
  const openNow = (resorts || []).filter((r) => r.open !== false).length;
  const [slide, setSlide] = useState(0);
  const [paused, setPaused] = useState(false);
  const nSlides = HERO_SLIDES.length;
  const goSlide = (next) => setSlide(((next % nSlides) + nSlides) % nSlides);
  useEffect(() => {
    if (paused) return;
    const t = setTimeout(() => setSlide((i) => (i + 1) % nSlides), 6000);
    return () => clearTimeout(t);
  }, [slide, paused, nSlides]);
  // color the last word with the accent
  const words = heroText.trim().split(" ");
  const lastWord = words.length > 1 ? words.pop() : "";
  const head = words.join(" ");
  return (
    <section style={{ position: "relative", background: "var(--ink-900)", color: "#fff", overflow: "hidden" }}>
      <HeroSlideshow idx={slide} onPause={setPaused} />
      <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, rgba(6,19,33,0.55) 0%, rgba(6,19,33,0.35) 35%, rgba(6,19,33,0.88) 100%)", pointerEvents: "none" }} />
      <div style={{ position: "absolute", inset: 0, background: "linear-gradient(90deg, rgba(6,19,33,0.75) 0%, rgba(6,19,33,0) 55%)", pointerEvents: "none" }} />

      <div className="wrap" style={{ position: "relative", paddingTop: 92, paddingBottom: 36 }}>
        <div className="eyebrow" style={{ color: "var(--blue-300)", marginBottom: 22 }}>{new Date().toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric" })} &middot; {openNow} {openNow === 1 ? "resort" : "resorts"} open</div>
        <h1 className="display" style={{ margin: 0, fontSize: "clamp(46px,7vw,104px)", maxWidth: 14 + "ch" }}>
          {head}<br />{lastWord && <span style={{ color: "var(--blue-300)" }}>{lastWord}</span>}
        </h1>
        <p className="serif" style={{ fontSize: "clamp(17px,2vw,21px)", lineHeight: 1.5, maxWidth: 520, marginTop: 22, color: "rgba(255,255,255,0.82)" }}>
          20 Years Providing the Best Guide to every New England Ski Area. Real-time conditions, honest forecasts, and the terrain reports that decide where you point the car at 5 AM.
        </p>
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 28, marginTop: 28, flexWrap: "wrap" }}>
          <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
            <button className="btn btn--sky" onClick={() => go("conditions")}>
              See all conditions
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M5 12h14M13 6l6 6-6 6" /></svg>
            </button>
            <button className="btn btn--light" onClick={() => go("resorts")}>Browse {(resorts || []).length} resorts</button>
          </div>
          <HeroCarouselControls idx={slide} go={goSlide} />
        </div>
      </div>

    </section>
  );
}

function StateBand({ go, states }) {
  return (
    <section style={{ background: "var(--retro-900)", color: "#fff", padding: "30px 0", height: 100 }}>
      <div className="wrap" style={{ display: "grid", gridTemplateColumns: "repeat(6,1fr)", gap: 0 }}>
        {states.map((s, i) => (
          <button key={s.code} onClick={() => go("resorts", null, s.code)} style={{
            background: "none", border: "none", borderLeft: i === 0 ? "none" : "1px solid rgba(255,255,255,0.12)",
            padding: "8px 16px", textAlign: "center", color: "#fff",
          }}
            onMouseEnter={(e) => e.currentTarget.querySelector("b").style.color = "var(--blue-300)"}
            onMouseLeave={(e) => e.currentTarget.querySelector("b").style.color = "#fff"}
          >
            <b style={{ display: "block", fontSize: 19, fontWeight: 800, letterSpacing: "-0.01em", transition: "color .15s ease" }}>{s.name}</b>
            <span className="mono" style={{ fontSize: 11, color: "rgba(255,255,255,0.55)" }}>{s.count} {s.count === 1 ? "area" : "areas"}</span>
          </button>
        ))}
      </div>
    </section>
  );
}

/* pseudo-geographic scatter — shared by the front-page map module */
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],
};

/* ---------- social platform glyphs ---------- */
function PlatformIcon({ p, size = 16, color = "currentColor" }) {
  /* optical sizing: each glyph fills its 24-unit box differently */
  const k = { youtube: 1.3, twitter: 0.92, tiktok: 1.04, instagram: 1, facebook: 1 }[p] || 1;
  const st = { width: size * k, height: size * k, display: "block" };
  if (p === "instagram") return (
    <svg style={st} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8"><rect x="3" y="3" width="18" height="18" rx="5" /><circle cx="12" cy="12" r="4" /><circle cx="17.3" cy="6.7" r="1.1" fill={color} stroke="none" /></svg>
  );
  if (p === "facebook") return (
    <svg style={st} viewBox="0 0 24 24" fill={color}><path d="M22 12a10 10 0 1 0-11.6 9.9v-7H7.9V12h2.5V9.8c0-2.5 1.5-3.9 3.8-3.9 1.1 0 2.2.2 2.2.2v2.5h-1.3c-1.2 0-1.6.8-1.6 1.6V12h2.8l-.5 2.9h-2.3v7A10 10 0 0 0 22 12Z" /></svg>
  );
  if (p === "tiktok") return (
    <svg style={st} viewBox="0 0 24 24" fill={color}><path d="M16.5 3c.3 2.1 1.5 3.4 3.5 3.6v2.4c-1.2.1-2.4-.3-3.5-1v6.6c0 3.4-2.8 5.9-6 5.4-2.8-.4-4.6-3-4.2-5.8.4-2.5 2.7-4.3 5.2-4v2.6c-.4-.1-.8-.1-1.2 0-1.1.3-1.8 1.3-1.6 2.4.2 1.1 1.3 1.9 2.4 1.6 1-.2 1.6-1.1 1.6-2.2V3h3.3Z" /></svg>
  );
  if (p === "youtube") return (
    <svg style={st} viewBox="0 0 24 24" fill={color}><path d="M23 12s0-3.3-.4-4.8a2.5 2.5 0 0 0-1.8-1.8C19.3 5 12 5 12 5s-7.3 0-8.8.4A2.5 2.5 0 0 0 1.4 7.2C1 8.7 1 12 1 12s0 3.3.4 4.8a2.5 2.5 0 0 0 1.8 1.8c1.5.4 8.8.4 8.8.4s7.3 0 8.8-.4a2.5 2.5 0 0 0 1.8-1.8C23 15.3 23 12 23 12Zm-13 3V9l5.2 3-5.2 3Z" /></svg>
  );
  if (p === "twitter" || p === "x") return (
    <svg style={st} viewBox="0 0 24 24" fill={color}><path d="M17.6 3h3.2l-7 8 8.2 10h-6.4l-5-6.1-5.7 6.1H1.7l7.5-8.5L1.3 3h6.6l4.5 5.6L17.6 3Zm-1.1 16h1.8L7.6 4.8H5.7L16.5 19Z" /></svg>
  );
  return null;
}

/* ---------- compact live conditions module ---------- */
function ConditionsModule({ go, resorts, style }) {
  const [, wxTick] = useState(0);
  useEffect(() => (window.SNE_WX ? SNE_WX.subscribe(() => wxTick((n) => n + 1)) : undefined), []);
  useEffect(() => { if (window.SNE_WX) SNE_WX.prefetchResorts(); }, []);
  const fresh = [...resorts].sort((a, b) => wxSnow(b) - wxSnow(a)).slice(0, 5);
  return (
    <div style={{ background: "var(--paper)", border: "1px solid var(--line)", borderRadius: 8, boxShadow: "var(--shadow-card)", display: "flex", flexDirection: "column", overflow: "hidden", ...style }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "15px 18px 13px", borderBottom: "1px solid var(--line)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
          <span className="pow-badge" style={{ width: 7, height: 7, borderRadius: "50%", background: "var(--pow)" }} />
          <span className="eyebrow" style={{ color: "var(--ink-900)" }}>Live Board</span>
        </div>
        <span className="mono" style={{ fontSize: 10.5, color: "var(--muted)" }}>6:42 AM</span>
      </div>
      <div style={{ flex: 1 }}>
        {fresh.map((r, i) => (
          <button key={r.id} onClick={() => go("resort", r.id)} style={{
            width: "100%", display: "flex", alignItems: "center", gap: 12, padding: "12px 18px",
            background: "none", border: "none", borderBottom: i < fresh.length - 1 ? "1px solid var(--line-soft)" : "none", textAlign: "left",
          }}
            onMouseEnter={(e) => e.currentTarget.style.background = "var(--frost-50)"}
            onMouseLeave={(e) => e.currentTarget.style.background = "none"}
          >
            <span className="mono tnum" style={{ fontSize: 11, color: "var(--muted-2)", width: 16 }}>{String(i + 1).padStart(2, "0")}</span>
            <span style={{ flex: 1, minWidth: 0 }}>
              <span style={{ display: "block", fontWeight: 700, fontSize: 14.5, lineHeight: 1.1 }}>{r.name}</span>
              <span className="mono" style={{ fontSize: 10.5, color: "var(--muted)" }}>{r.state} · {r.base == null ? "—" : <>{r.base}&Prime;</>} base</span>
            </span>
            <SkyIcon sky={(window.SNE_WX && SNE_WX.forResort(r) || {}).sky || r.sky} size={15} color="var(--muted-2)" />
            <span className="mono tnum" style={{ fontSize: 18, fontWeight: 600, width: 42, textAlign: "right", color: wxSnow(r) >= 6 ? "var(--pow)" : "var(--blue-500)" }}>{wxSnow(r)}&Prime;</span>
          </button>
        ))}
      </div>
      <button onClick={() => go("conditions")} style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 7, padding: "13px", background: "var(--frost-50)", border: "none", borderTop: "1px solid var(--line)", fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 13, color: "var(--blue-600)" }}>
        Full conditions board
        <svg width="13" height="13" 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>
  );
}

/* ---------- compact map module ---------- */
function MapModule({ go, resorts, style }) {
  return (
    <div style={{ position: "relative", border: "1px solid rgba(255,255,255,0.12)", borderRadius: 8, overflow: "hidden", background: "var(--ink-900)", minHeight: 260, ...style }}>
      <iframe src="./resortmap/index.html?chrome=none" 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 style={{ position: "absolute", left: 16, top: 15, pointerEvents: "none", textShadow: "0 1px 10px rgba(6,19,33,0.85)" }}>
        <div className="eyebrow" style={{ color: "var(--blue-300)", marginBottom: 5 }}>The Map</div>
        <div style={{ color: "#fff", fontWeight: 800, fontSize: 17, letterSpacing: "-0.01em" }}>Every mountain, one screen</div>
      </div>
      <button onClick={() => go("resorts")} style={{ position: "absolute", right: 16, bottom: 14, display: "inline-flex", alignItems: "center", gap: 7, color: "#fff", background: "rgba(11,31,51,0.78)", backdropFilter: "blur(6px)", border: "1px solid rgba(255,255,255,0.18)", padding: "8px 13px", borderRadius: 4, fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 12.5, whiteSpace: "nowrap" }}>
        Open full map
        <svg width="13" height="13" 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>
  );
}

/* ---------- THE FRONT PAGE: lead story + the feed ---------- */
function FeedRow({ n, go }) {
  return (
    <button onClick={() => go("article", null, null, n.slug)} style={{
      display: "grid", gridTemplateColumns: "104px minmax(0,1fr)", gap: 15, alignItems: "start",
      textAlign: "left", background: "none", border: "none", padding: "16px 0", borderTop: "1px solid var(--line)", width: "100%", color: "var(--ink-900)",
    }}>
      <div style={{ position: "relative", aspectRatio: "4/3", borderRadius: 6, overflow: "hidden", background: "var(--frost-100)" }}>
        {n.hero
          ? <img src={n.hero} alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} />
          : <image-slot id={`home-news-${n.id}`} shape="rect" placeholder="Story photo" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}></image-slot>}
      </div>
      <div style={{ minWidth: 0 }}>
        <div className="eyebrow" style={{ color: "var(--blue-500)", fontSize: 9, marginBottom: 7 }}>{kindOf(n)}</div>
        <h3 className="serif" style={{ fontSize: 18, lineHeight: 1.2, margin: "0 0 7px", fontWeight: 600, letterSpacing: "-0.01em", color: "var(--ink-900)" }}>{n.title}</h3>
        <div className="mono" style={{ fontSize: 10.5, color: "var(--muted-2)" }}>{fmtDate(n.date)} · {n.read} read</div>
      </div>
    </button>
  );
}

function FrontPage({ go }) {
  const posts = useNews();
  const feat = posts && posts[0];
  const rest = (posts || []).slice(1, 5);
  return (
    <section style={{ position: "relative", padding: "62px 0 86px", background: "var(--frost-50)", color: "var(--ink-900)" }}>
      <div className="wrap">
        <SectionHead eyebrow="The Front Page" title="Recent news" action="All stories" onAction={() => go("news")} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(320px,1fr))", gap: 34, alignItems: "start" }}>
          <button onClick={() => feat && go("article", null, null, feat.slug)} style={{ display: "flex", flexDirection: "column", textAlign: "left", background: "none", border: "none", padding: 0 }}>
            <div style={{ position: "relative", aspectRatio: "16/10", width: "100%", borderRadius: 8, overflow: "hidden", background: "var(--frost-100)" }}>
              {feat && feat.hero
                ? <img src={feat.hero} alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} />
                : <image-slot id="news-feat" shape="rect" placeholder="Featured story photo" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}></image-slot>}
              {feat && <span style={{ position: "absolute", top: 14, left: 14, fontFamily: "var(--f-mono)", fontSize: 10.5, fontWeight: 600, letterSpacing: "0.12em", background: "var(--pow)", color: "#fff", padding: "5px 10px", borderRadius: 3 }}>{kindOf(feat)}</span>}
            </div>
            <div className="eyebrow" style={{ color: "var(--blue-500)", margin: "20px 0 11px" }}>Lead story</div>
            <h3 className="serif" style={{ fontSize: "clamp(24px,2.6vw,34px)", lineHeight: 1.1, margin: "0 0 12px", fontWeight: 600, letterSpacing: "-0.015em", color: "var(--ink-900)" }}>{feat ? feat.title : "Loading…"}</h3>
            <p className="serif" style={{ fontSize: 16.5, lineHeight: 1.5, color: "var(--muted)", margin: 0 }}>{feat ? feat.dek : ""}</p>
            {feat && <div className="mono" style={{ fontSize: 11.5, color: "var(--muted-2)", marginTop: 16 }}>{byline(feat.author)} · {fmtDate(feat.date)} · {feat.read} read</div>}
          </button>
          <div>
            <div className="eyebrow" style={{ color: "var(--muted)", marginBottom: 4 }}>The feed</div>
            {rest.map((n) => <FeedRow key={n.id} n={n} go={go} />)}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- social wall ---------- */
function AccountRow({ platform, handle, href, note }) {
  return (
    <a href={href} target="_blank" rel="noopener" style={{ display: "flex", alignItems: "center", gap: 13, padding: "12px 20px 12px 13px", borderRadius: 99, border: "1px solid var(--line)", background: "var(--paper)", color: "var(--ink-900)", textDecoration: "none" }}
      onMouseEnter={(e) => { e.currentTarget.style.background = "var(--frost-50)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.background = "var(--paper)"; }}>
      <span style={{ display: "grid", placeItems: "center", width: 38, height: 38, borderRadius: "50%", background: "var(--ink-900)", color: "#fff", flexShrink: 0 }}><PlatformIcon p={platform} size={19} /></span>
      <span style={{ display: "flex", flexDirection: "column", lineHeight: 1.15 }}>
        <span style={{ fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 16 }}>{handle}</span>
        <span className="mono" style={{ fontSize: 11, color: "var(--muted)", marginTop: 4 }}>{note}</span>
      </span>
      <span className="mono" style={{ fontSize: 11.5, fontWeight: 600, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--blue-500)", marginLeft: 6 }}>Follow</span>
    </a>
  );
}

function SocialWall({ social }) {
  return (
    <section style={{ position: "relative", padding: "116px 0 60px", background: "var(--frost-100)", color: "var(--ink-900)", overflow: "hidden" }}>
      <Chairlift color="rgba(11,31,51,0.32)" chairTone="rgba(11,31,51,0.5)" car="gondola" />
      <div className="wrap" style={{ position: "relative", zIndex: 1 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 26, gap: 28, flexWrap: "wrap" }}>
          <div style={{ flex: "1 1 320px", minWidth: 0 }}>
            <div className="eyebrow" style={{ color: "var(--blue-500)", marginBottom: 10 }}>Get featured</div>
            <h2 className="display" style={{ margin: 0, fontSize: "clamp(26px,3.4vw,40px)" }}>TAG US FROM THE LIFT</h2>
            <p className="serif" style={{ fontSize: 16.5, lineHeight: 1.45, color: "var(--muted)", margin: "12px 0 0", maxWidth: 420 }}>
              Tag <strong style={{ color: "var(--ink-900)", fontWeight: 600 }}>@skinewengland</strong> or <strong style={{ color: "var(--ink-900)", fontWeight: 600 }}>#SkiNewEngland</strong> on Instagram or Facebook. We pull the best shots from the six states onto this wall every week.
            </p>
          </div>
          <div style={{ display: "flex", gap: 10, alignItems: "center", flexShrink: 0 }}>
            <AccountRow platform="instagram" handle="@skinewengland" note="Tag your photos" href="https://instagram.com/skinewengland" />
            <AccountRow platform="facebook" handle="/skinewengland" note="Tag the page" href="https://facebook.com/skinewengland" />
            <div style={{ display: "flex", gap: 8 }}>
              {[["youtube", "https://youtube.com/@skinewengland"], ["twitter", "https://twitter.com/skinewengland"], ["tiktok", "https://tiktok.com/@skinewengland"]].map(([p, url]) => (
                <a key={p} href={url} target="_blank" rel="noopener" aria-label={p} title={p} style={{ display: "grid", placeItems: "center", width: 38, height: 38, borderRadius: "50%", background: "var(--ink-900)", color: "#fff" }}
                  onMouseEnter={(e) => { e.currentTarget.style.background = "var(--blue-500)"; }}
                  onMouseLeave={(e) => { e.currentTarget.style.background = "var(--ink-900)"; }}>
                  <PlatformIcon p={p} size={19} />
                </a>
              ))}
            </div>
          </div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(6,1fr)", gap: 14 }}>
          {social.map((s) => (
            <a key={s.id} href="#" onClick={(e) => e.preventDefault()} style={{ position: "relative", aspectRatio: "1/1", borderRadius: 6, overflow: "hidden", background: "var(--ink-850)", display: "block" }} className="social-tile">
              <image-slot id={`social-${s.id}`} shape="rect" placeholder={s.loc} style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}></image-slot>
              <span style={{ position: "absolute", top: 9, right: 9, color: "#fff", filter: "drop-shadow(0 1px 2px rgba(0,0,0,0.5))" }}><PlatformIcon p={s.platform} size={16} /></span>
              <span className="social-overlay" style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, rgba(6,19,33,0) 40%, rgba(6,19,33,0.88) 100%)", opacity: 0, transition: "opacity .18s ease", display: "flex", flexDirection: "column", justifyContent: "flex-end", padding: 12 }}>
                <span style={{ fontSize: 11.5, fontWeight: 600, lineHeight: 1.25, color: "#fff" }}>{s.loc}</span>
                <span className="mono" style={{ fontSize: 10, color: "rgba(255,255,255,0.8)", marginTop: 5, display: "flex", gap: 10 }}>
                  <span>{s.by}</span><span>♥ {s.likes}</span>
                </span>
              </span>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

function StoreTeaser({ go, store }) {
  return (
    <section style={{ position: "relative", padding: "92px 0 64px", background: "var(--retro-900)", color: "#fff" }}>
      <SnowEdge fill="var(--frost-100)" height={34} flip side="top" />
      <div className="wrap">
        <SectionHead eyebrow="OUR SHOP" title="OWN THE MOUNTAINS" action="Visit store" onAction={() => go("store")} light />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 20 }}>
          {store.map((p) => (
            <button key={p.id} onClick={() => go("store")} style={{ textAlign: "left", background: "var(--paper)", border: "1px solid var(--line)", borderRadius: 6, overflow: "hidden", padding: 0 }}>
              <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", objectPosition: "center", padding: 8 }} />
                  : <image-slot id={`prod-${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: 10, left: 10, fontFamily: "var(--f-mono)", fontSize: 10, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", background: "var(--ink-900)", color: "#fff", padding: "4px 8px", borderRadius: 3 }}>{p.tag}</span>}
              </div>
              <div style={{ padding: "13px 14px 16px" }}>
                <div className="eyebrow" style={{ fontSize: 9, color: "var(--muted)" }}>{p.cat}</div>
                <div style={{ fontWeight: 700, fontSize: 14.5, margin: "6px 0 8px", lineHeight: 1.2 }}>{p.name}</div>
                <div className="mono" style={{ fontSize: 14, fontWeight: 600, color: "var(--blue-600)" }}>${p.price}</div>
              </div>
            </button>
          ))}
        </div>
      </div>
    </section>
  );
}

function HomePage({ go, data, heroText }) {
  return (
    <div>
      <Hero go={go} resorts={data.RESORTS} heroText={heroText} />
      <StateBand go={go} states={data.STATES} />
      <SnowDivider above="var(--retro-900)" below="var(--frost-50)" pokeDown={false} />
      <FrontPage go={go} />
      <SnowDivider above="var(--frost-50)" below="var(--retro-900)" pokeDown={true} />
      <ConditionsSection go={go} resorts={data.RESORTS} />
      <SocialWall social={data.SOCIAL} />
      <StoreTeaser go={go} store={data.STORE} />
    </div>
  );
}

Object.assign(window, { HomePage });
