/* ============================================================
   SKI NEW ENGLAND — News index + article reader
   Posts load from news.json (migrated from the WordPress export).
   Adding an article = add an object to news.json.
   ============================================================ */
const AUTHORS = { ajh2oman: "A.J. Howe", briandix: "Brian Dix" };
const byline = (a) => AUTHORS[a] || a;

function useNews() {
  const [posts, setPosts] = useState(window.__SNE_NEWS || null);
  useEffect(() => {
    if (posts) return;
    fetch("./news.json").then((r) => r.json()).then((d) => { window.__SNE_NEWS = d; setPosts(d); }).catch(() => setPosts([]));
  }, []);
  return posts;
}

const fmtDate = (iso) => {
  const d = new Date(iso + "T12:00:00");
  return d.toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" });
};

const kindOf = (p) => {
  const t = p.title.toUpperCase();
  if (/FORECAST|STORM|SNOW|CLIPPER|REFILL/.test(t)) return "FORECAST";
  if (/CHAIRLIFT|LIFT/.test(t)) return "LIFT NEWS";
  if (/TOP \d|BEST/.test(t)) return "GUIDE";
  return "REPORT";
};

/* ---------- index ---------- */
function NewsPage({ go }) {
  const posts = useNews();
  const [page, setPage] = useState(0);
  const PER = 8;
  if (!posts) return <div className="wrap" style={{ padding: "90px 28px" }}><span className="mono" style={{ color: "var(--muted)" }}>Loading stories…</span></div>;
  if (!posts.length) return <div className="wrap" style={{ padding: "90px 28px" }}><span className="mono" style={{ color: "var(--muted)" }}>No stories yet.</span></div>;

  const [feat, ...rest] = posts;
  const pages = Math.max(1, Math.ceil(rest.length / PER));
  const p0 = Math.min(page, pages - 1);
  const shown = rest.slice(p0 * PER, p0 * PER + PER);
  const arrow = (dir, disabled) => (
    <button onClick={() => { setPage(p0 + dir); window.scrollTo({ top: 0, behavior: "smooth" }); }} disabled={disabled}
      aria-label={dir > 0 ? "More stories" : "Previous stories"}
      style={{ width: 40, height: 40, borderRadius: "50%", display: "grid", placeItems: "center", border: "1px solid var(--line)", background: disabled ? "transparent" : "var(--ink-900)", color: disabled ? "var(--muted-2)" : "#fff", opacity: disabled ? 0.45 : 1 }}>
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d={dir > 0 ? "M9 5l7 7-7 7" : "M15 5l-7 7 7 7"} /></svg>
    </button>
  );
  return (
    <div style={{ background: "var(--paper)", minHeight: "100%" }}>
      <PageHead eyebrow={`The Feed · ${posts.length} stories`} title="Snow Forecast & Reports"
        sub="Honest forecasting and on-the-ground field reports from across the six states." edge="var(--paper)" />
      <div className="wrap" style={{ padding: "44px 28px 70px" }}>
        <button onClick={() => go("article", null, null, feat.slug)} style={{ textAlign: "left", background: "none", border: "none", padding: 0, width: "100%", marginBottom: 50 }}>
          <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 36, alignItems: "center" }}>
            <div style={{ position: "relative", aspectRatio: "16/10", borderRadius: 10, overflow: "hidden", background: "var(--ink-850)" }}>
              {feat.hero && <img src={feat.hero} alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} />}
              <span style={{ position: "absolute", top: 16, left: 16, fontFamily: "var(--f-mono)", fontSize: 11, fontWeight: 600, letterSpacing: "0.12em", background: "var(--pow)", color: "#fff", padding: "5px 11px", borderRadius: 3 }}>{kindOf(feat)}</span>
            </div>
            <div>
              <div className="eyebrow" style={{ color: "var(--blue-500)", marginBottom: 14 }}>Lead story</div>
              <h2 className="serif" style={{ fontSize: "clamp(28px,3.2vw,40px)", lineHeight: 1.08, margin: "0 0 16px", fontWeight: 600, letterSpacing: "-0.015em" }}>{feat.title}</h2>
              <p className="serif" style={{ fontSize: 18, lineHeight: 1.5, color: "var(--muted)", margin: 0 }}>{feat.dek}</p>
              <div className="mono" style={{ fontSize: 12, color: "var(--muted)", marginTop: 20 }}>{byline(feat.author)} · {fmtDate(feat.date)} · {feat.read} read</div>
            </div>
          </div>
        </button>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(2,1fr)", gap: 36, borderTop: "1.5px solid var(--line)", paddingTop: 40 }}>
          {shown.map((n) => (
            <button key={n.id} onClick={() => go("article", null, null, n.slug)} style={{ textAlign: "left", background: "none", border: "none", padding: 0, display: "grid", gridTemplateColumns: "150px 1fr", gap: 20 }}>
              <div style={{ position: "relative", aspectRatio: "1/1", borderRadius: 8, overflow: "hidden", background: "var(--ink-850)" }}>
                {n.hero && <img src={n.hero} alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} />}
              </div>
              <div>
                <div className="eyebrow" style={{ color: "var(--blue-500)", marginBottom: 9, fontSize: 9.5 }}>{kindOf(n)}</div>
                <h3 className="serif" style={{ fontSize: 21, lineHeight: 1.18, margin: "0 0 8px", fontWeight: 600, letterSpacing: "-0.01em" }}>{n.title}</h3>
                <p className="serif" style={{ fontSize: 15, lineHeight: 1.45, color: "var(--muted)", margin: 0 }}>{n.dek}</p>
                <div className="mono" style={{ fontSize: 11, color: "var(--muted)", marginTop: 12 }}>{fmtDate(n.date)} · {n.read} read</div>
              </div>
            </button>
          ))}
        </div>
        {pages > 1 && (
          <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 18, marginTop: 44 }}>
            {arrow(-1, p0 === 0)}
            <span className="mono" style={{ fontSize: 12, color: "var(--muted)" }}>{p0 * PER + 1}&ndash;{p0 * PER + shown.length} of {rest.length}</span>
            {arrow(1, p0 >= pages - 1)}
          </div>
        )}
      </div>
    </div>
  );
}

/* ---------- article ---------- */
function ArticlePage({ go, slug }) {
  const posts = useNews();
  useEffect(() => { window.scrollTo(0, 0); }, [slug]);
  if (!posts) return <div className="wrap" style={{ padding: "90px 28px" }}><span className="mono" style={{ color: "var(--muted)" }}>Loading…</span></div>;
  const p = posts.find((x) => x.slug === slug) || posts[0];
  const more = posts.filter((x) => x.slug !== p.slug).slice(0, 3);

  return (
    <div style={{ background: "var(--paper)", minHeight: "100%" }}>
      <div style={{ position: "relative", background: "var(--ink-900)", color: "#fff" }}>
        {p.hero && <img src={p.hero} alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", opacity: 0.42 }} />}
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, rgba(6,19,33,0.55) 0%, rgba(6,19,33,0.35) 40%, rgba(6,19,33,0.92) 100%)" }}></div>
        <div className="wrap" style={{ position: "relative", padding: "38px 28px 46px", maxWidth: 860 }}>
          <button className="eyebrow" onClick={() => go("news")} style={{ background: "none", border: "none", color: "rgba(255,255,255,0.7)", display: "flex", alignItems: "center", gap: 7, marginBottom: 26, padding: 0 }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M15 5l-7 7 7 7" /></svg>
            All stories
          </button>
          <div className="eyebrow" style={{ color: "var(--blue-300)", marginBottom: 14 }}>{kindOf(p)}</div>
          <h1 className="serif" style={{ fontSize: "clamp(30px,4vw,50px)", lineHeight: 1.06, margin: "0 0 18px", fontWeight: 600, letterSpacing: "-0.015em" }}>{p.title}</h1>
          <div className="mono" style={{ fontSize: 12.5, color: "rgba(255,255,255,0.72)" }}>{byline(p.author)} · {fmtDate(p.date)} · {p.read} read</div>
        </div>
        <SnowEdge fill="var(--paper)" />
      </div>

      <div className="wrap" style={{ padding: "46px 28px 20px", maxWidth: 760 }}>
        <div className="article-body" dangerouslySetInnerHTML={{ __html: p.html }}></div>
        {p.legacyUrl && <div className="mono" style={{ fontSize: 11, color: "var(--muted-2)", marginTop: 40, paddingTop: 18, borderTop: "1px solid var(--line)" }}>Originally published at {p.legacyUrl.replace(/^https?:\/\//, "")}</div>}
      </div>

      <div className="wrap" style={{ padding: "40px 28px 70px" }}>
        <SectionHead eyebrow="Keep Reading" title="More from the feed" />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,minmax(0,1fr))", gap: 22 }}>
          {more.map((n) => (
            <button key={n.id} onClick={() => go("article", null, null, n.slug)} style={{ textAlign: "left", background: "none", border: "none", padding: 0 }}>
              <div style={{ position: "relative", aspectRatio: "16/10", borderRadius: 8, overflow: "hidden", background: "var(--ink-850)", marginBottom: 14 }}>
                {n.hero && <img src={n.hero} alt="" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} />}
              </div>
              <h3 className="serif" style={{ fontSize: 18, lineHeight: 1.2, margin: "0 0 7px", fontWeight: 600 }}>{n.title}</h3>
              <div className="mono" style={{ fontSize: 11, color: "var(--muted)" }}>{fmtDate(n.date)} · {n.read} read</div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { NewsPage, ArticlePage, useNews, kindOf, fmtDate, byline });
