/* SubMedium — app: homepage feed + story-cluster detail + tweaks */
const { useState: useS, useEffect: useE } = React;

const ACCENTS = [
  { name: "Amber",   c: "#BE530F" },
  { name: "Cobalt",  c: "#1F4FB0" },
  { name: "Oxblood", c: "#8E2A24" },
  { name: "Forest",  c: "#1E6B47" },
  { name: "Ink",     c: "#2A2722" },
];

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "edition": "day",
  "accent": "#BE530F",
  "brief": true
}/*EDITMODE-END*/;

/* ----- source row (cluster detail) ----- */
function SourceRow({ s, lead }) {
  const src = SRC[s.k] || { name: s.k };
  return (
    <article style={{ display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 16, alignItems: "start", padding: "18px 0", borderTop: "1px solid var(--line)" }}>
      <SourceAvatar k={s.k} size={40} />
      <div style={{ minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 4, flexWrap: "wrap" }}>
          <span style={{ fontFamily: "var(--sans)", fontWeight: 600, fontSize: 14, color: "var(--ink)", whiteSpace: "nowrap" }}>{src.name}</span>
          <span style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ink-3)", border: "1px solid var(--line)", padding: "1px 6px", borderRadius: 2 }}>{src.tag}</span>
        </div>
        <h3 className="hl" style={{ fontSize: 19, margin: 0, fontWeight: 540 }}>{s.h}</h3>
      </div>
      <div style={{ textAlign: "right", whiteSpace: "nowrap" }}>
        <div className="meta">{s.time}</div>
        <span style={{ fontFamily: "var(--sans)", fontSize: 12.5, color: "var(--accent-2)", fontWeight: 500 }}>Read →</span>
      </div>
    </article>
  );
}

/* ----- coverage spread (tag distribution) ----- */
function CoverageSpread({ sources }) {
  const tags = {};
  sources.forEach((s) => { const t = (SRC[s.k] || {}).tag || "Other"; tags[t] = (tags[t] || 0) + 1; });
  const entries = Object.entries(tags);
  return (
    <div>
      <div style={{ display: "flex", height: 7, borderRadius: 4, overflow: "hidden", border: "1px solid var(--line)" }}>
        {entries.map(([t, n], i) => (
          <div key={t} style={{ flex: n, background: `color-mix(in oklab, var(--accent) ${88 - i * 16}%, var(--paper-3))` }} />
        ))}
      </div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: "4px 14px", marginTop: 10 }}>
        {entries.map(([t, n]) => (
          <span key={t} className="meta" style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
            <span style={{ width: 7, height: 7, borderRadius: 2, background: "var(--accent)", opacity: 0.8 }} />
            {t} · {n}
          </span>
        ))}
      </div>
    </div>
  );
}

/* ============ CLUSTER DETAIL ============ */
function ClusterView({ s, onBack, openStory }) {
  useE(() => { window.scrollTo(0, 0); }, [s.id]);
  const related = STORIES.filter((x) => x.section === s.section && x.id !== s.id).slice(0, 4);
  return (
    <div className="shell rise" style={{ padding: "30px 28px 90px" }}>
      <button onClick={onBack} style={{ background: "none", border: 0, padding: 0, marginBottom: 22, fontFamily: "var(--mono)", fontSize: 12, letterSpacing: "0.04em", color: "var(--ink-2)" }}>← All stories</button>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 312px", gap: 52, alignItems: "start" }}>
        {/* main */}
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
            <SectionTag>{s.kicker}</SectionTag>
            {s.live && <LiveDot />}
            <span className="meta">Updated {s.time} ago</span>
          </div>
          <h1 className="hl" style={{ fontSize: 46, margin: "0 0 18px", maxWidth: "16ch" }}>{s.headline}</h1>
          <p className="dek" style={{ fontSize: 21, margin: "0 0 26px", maxWidth: "60ch" }}>{s.dek}</p>

          {s.image && <div style={{ marginBottom: 26 }}><ImagePH h={400} /></div>}

          {/* The Brief — expanded */}
          <div style={{ background: "var(--paper-2)", border: "1px solid var(--line)", borderRadius: 5, padding: "22px 24px", marginBottom: 34 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12, flexWrap: "wrap" }}>
              <BriefMark />
              <span className="kicker" style={{ color: "var(--ink)" }}>The Brief</span>
              <span className="meta" style={{ fontSize: 10.5, whiteSpace: "nowrap" }}>· synthesized from {s.sourceCount} sources</span>
            </div>
            <p style={{ margin: "0 0 16px", fontFamily: "var(--serif)", fontSize: 19, lineHeight: 1.5, color: "var(--ink)", fontWeight: 400 }}>{s.brief}</p>
            <CoverageSpread sources={s.sources} />
            <p className="meta" style={{ marginTop: 14, fontSize: 10.5, color: "var(--ink-3)", fontStyle: "normal" }}>
              Generated automatically · verify against original reporting below
            </p>
          </div>

          {/* all coverage */}
          <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 4, gap: 16 }}>
            <h2 style={{ fontFamily: "var(--serif)", fontSize: 22, fontWeight: 600, margin: 0, whiteSpace: "nowrap" }}>All coverage</h2>
            <span className="meta" style={{ whiteSpace: "nowrap" }}>{s.sourceCount} sources · newest first</span>
          </div>
          <div>
            {s.sources.map((src, i) => <SourceRow key={i} s={src} lead={i === 0} />)}
            {s.sourceCount > s.sources.length && (
              <div style={{ borderTop: "1px solid var(--line)", paddingTop: 16, marginTop: 2 }}>
                <button style={{ fontFamily: "var(--sans)", fontSize: 13.5, fontWeight: 500, color: "var(--accent-2)", background: "none", border: 0, padding: 0 }}>
                  Show {s.sourceCount - s.sources.length} more sources →
                </button>
              </div>
            )}
          </div>
        </div>

        {/* rail */}
        <aside style={{ position: "sticky", top: 96 }}>
          <RailCard title="Story facts">
            <FactRow label="First reported" v={`${s.sources[s.sources.length - 1].time} ago`} />
            <FactRow label="Sources tracking" v={`${s.sourceCount}`} />
            <FactRow label="Region" v={s.region} />
            <FactRow label="Desk" v={s.section} />
          </RailCard>
          <div style={{ height: 22 }} />
          <div className="kicker" style={{ marginBottom: 10 }}>More in {s.section}</div>
          {related.map((r, i) => <div key={r.id} style={{ borderTop: i ? "1px solid var(--line)" : "1px solid var(--ink)" }}><CompactRow s={r} onOpen={() => openStory(r)} /></div>)}
        </aside>
      </div>
    </div>
  );
}

function RailCard({ title, children }) {
  return (
    <div style={{ border: "1px solid var(--line)", borderTop: "2px solid var(--ink)", padding: "16px 18px", background: "var(--paper-2)" }}>
      <div className="kicker" style={{ marginBottom: 10, color: "var(--ink)" }}>{title}</div>
      {children}
    </div>
  );
}
function FactRow({ label, v }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", padding: "7px 0", borderTop: "1px solid var(--line-2)" }}>
      <span className="meta" style={{ color: "var(--ink-3)" }}>{label}</span>
      <span style={{ fontFamily: "var(--mono)", fontSize: 13, color: "var(--ink)" }}>{v}</span>
    </div>
  );
}

/* ============ HOMEPAGE ============ */
function Home({ section, forYou, query, openStory, showBrief }) {
  let list = STORIES;
  if (section !== "Top") list = STORIES.filter((s) => s.section === section);
  if (query.trim()) {
    const q = query.toLowerCase();
    list = STORIES.filter((s) => (s.headline + s.dek + s.kicker).toLowerCase().includes(q));
  }
  const [lead, ...rest] = list.length ? list : STORIES;
  const grid = rest.slice(0, 6);
  const more = rest.slice(6);
  const trending = TRENDING.map((t) => STORIES.find((s) => s.headline.toLowerCase().includes(t.t.split(" ")[0].toLowerCase())) || STORIES[0]);

  return (
    <div className="shell" style={{ padding: "26px 28px 90px" }}>
      {forYou && <ForYouBanner />}
      {query.trim() && <div className="meta" style={{ marginBottom: 18 }}>{list.length} results for “{query}”</div>}

      {/* lead */}
      <LeadStory s={lead} onOpen={() => openStory(lead)} showBrief={showBrief} />
      <hr className="rule" style={{ margin: "30px 0 4px" }} />

      {/* body grid */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 318px", gap: 44 }}>
        {/* main column */}
        <div>
          <SectionHeader>{forYou ? "Curated for you" : (section === "Top" ? "Top stories" : section)}</SectionHeader>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 0 }}>
            {grid.map((s, i) => (
              <div key={s.id} style={{
                padding: "22px 22px",
                borderLeft: i % 3 ? "1px solid var(--line)" : "none",
                borderTop: i >= 3 ? "1px solid var(--line)" : "none",
              }}>
                <StoryCard s={s} onOpen={() => openStory(s)} thumb={i === 0} brief={i === 0 && showBrief} />
              </div>
            ))}
          </div>

          {more.length > 0 && (
            <>
              <SectionHeader>More coverage</SectionHeader>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0 44px" }}>
                {more.map((s, i) => (
                  <div key={s.id} style={{ borderTop: "1px solid var(--line)" }}>
                    <CompactRow s={s} onOpen={() => openStory(s)} />
                  </div>
                ))}
              </div>
            </>
          )}
        </div>

        {/* right rail */}
        <aside>
          {forYou ? <FollowingCard /> : <MarketsCard />}
          <div style={{ height: 26 }} />
          <SectionHeader small>Most covered</SectionHeader>
          <div>
            {TRENDING.map((t, i) => {
              const st = STORIES.find((s) => s.id === ["ecb-rate","ai-chips","climate-summit","merger","election-court"][i]) || STORIES[0];
              return (
                <div key={i} style={{ borderTop: i ? "1px solid var(--line)" : "1px solid var(--ink)" }}>
                  <CompactRow s={st} idx={i + 1} onOpen={() => openStory(st)} />
                </div>
              );
            })}
          </div>
          <div style={{ height: 26 }} />
          <DigestCard />
        </aside>
      </div>
    </div>
  );
}

function SectionHeader({ children, small }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 14, margin: small ? "0 0 6px" : "8px 0 4px" }}>
      <h2 style={{ fontFamily: "var(--serif)", fontSize: small ? 16 : 19, fontWeight: 600, margin: 0, whiteSpace: "nowrap", letterSpacing: "-0.01em" }}>{children}</h2>
      <hr className="rule-ink" style={{ flex: 1 }} />
    </div>
  );
}

function MarketsCard() {
  return (
    <RailCard title="Markets">
      {MARKETS.slice(0, 6).map((q, i) => {
        const up = q.pct >= 0;
        return (
          <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr auto auto", gap: 12, alignItems: "baseline", padding: "8px 0", borderTop: i ? "1px solid var(--line-2)" : "none" }}>
            <span style={{ fontFamily: "var(--mono)", fontSize: 12.5, color: "var(--ink-2)" }}>{q.sym}</span>
            <span style={{ fontFamily: "var(--mono)", fontSize: 12.5, color: "var(--ink)" }}>{q.val}</span>
            <span style={{ fontFamily: "var(--mono)", fontSize: 12, color: up ? "var(--up)" : "var(--down)", textAlign: "right", minWidth: 56 }}>{up ? "+" : "−"}{Math.abs(q.pct).toFixed(2)}%</span>
          </div>
        );
      })}
    </RailCard>
  );
}

function ForYouBanner() {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "13px 18px", background: "var(--ink)", color: "var(--paper)", borderRadius: 4, marginBottom: 24 }}>
      <svg width="16" height="16" viewBox="0 0 14 14"><path d="M7 1.5l1.6 3.3 3.6.5-2.6 2.5.6 3.6L7 10.2 3.8 11.9l.6-3.6L1.8 5.8l3.6-.5z" fill="var(--accent-2)" stroke="var(--accent-2)" strokeWidth="0.5"/></svg>
      <div style={{ fontFamily: "var(--sans)", fontSize: 14 }}>
        <strong style={{ fontWeight: 600 }}>Your edition.</strong>
        <span style={{ opacity: 0.8 }}> Ranked across the 8 topics you follow · refreshed 4 min ago</span>
      </div>
      <button style={{ marginLeft: "auto", background: "transparent", border: "1px solid rgba(255,255,255,0.3)", color: "var(--paper)", borderRadius: 3, padding: "5px 12px", fontSize: 12.5, fontWeight: 500 }}>Edit topics</button>
    </div>
  );
}

function FollowingCard() {
  return (
    <RailCard title="Following">
      <div style={{ display: "flex", flexWrap: "wrap", gap: 7, marginTop: 2 }}>
        {TOPICS.map((t) => (
          <span key={t} style={{ fontFamily: "var(--sans)", fontSize: 12.5, padding: "5px 11px", border: "1px solid var(--line)", borderRadius: 20, color: "var(--ink-2)", background: "var(--paper)" }}>{t}</span>
        ))}
        <span style={{ fontFamily: "var(--sans)", fontSize: 12.5, padding: "5px 11px", border: "1px dashed var(--accent)", borderRadius: 20, color: "var(--accent-2)", fontWeight: 500 }}>+ Add</span>
      </div>
    </RailCard>
  );
}

function DigestCard() {
  return (
    <div style={{ border: "1px solid var(--line)", borderTop: "2px solid var(--accent)", padding: "18px", background: "var(--paper-2)" }}>
      <div className="kicker" style={{ marginBottom: 8 }}>The Daily Brief</div>
      <p style={{ fontFamily: "var(--serif)", fontSize: 15.5, lineHeight: 1.45, margin: "0 0 14px", color: "var(--ink-2)" }}>
        One AI-synthesized digest of everything you follow, in your inbox by 6am.
      </p>
      <div style={{ display: "flex", gap: 8 }}>
        <input placeholder="you@email.com" style={{ flex: 1, font: "inherit", fontFamily: "var(--mono)", fontSize: 12.5, padding: "8px 10px", border: "1px solid var(--line)", background: "var(--paper)", color: "var(--ink)", borderRadius: 3, outline: "none" }} />
        <button style={{ background: "var(--ink)", color: "var(--paper)", border: 0, borderRadius: 3, padding: "0 14px", fontSize: 13, fontWeight: 500 }}>Subscribe</button>
      </div>
    </div>
  );
}

/* ============ APP ============ */
function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [section, setSection] = useS("Top");
  const [forYou, setForYou] = useS(false);
  const [query, setQuery] = useS("");
  const [active, setActive] = useS(null); // cluster story or null

  useE(() => {
    document.documentElement.setAttribute("data-edition", t.edition);
    document.documentElement.style.setProperty("--accent", t.accent);
  }, [t.edition, t.accent]);

  const openStory = (s) => setActive(s);
  const goHome = () => { setActive(null); setQuery(""); setSection("Top"); };

  return (
    <div style={{ fontSize: 16 }}>
      <Ticker />
      <Masthead section={section} setSection={(s) => { setSection(s); setActive(null); }} onHome={goHome}
        query={query} setQuery={(q) => { setQuery(q); setActive(null); }} forYou={forYou} setForYou={setForYou} />

      {active
        ? <ClusterView s={active} onBack={() => setActive(null)} openStory={openStory} />
        : <Home section={section} forYou={forYou} query={query} openStory={openStory} showBrief={t.brief} />}

      <Footer />

      <TweaksPanel>
        <TweakSection label="Edition" />
        <TweakRadio label="Theme" value={t.edition} options={["day", "night"]} onChange={(v) => setTweak("edition", v)} />
        <TweakSection label="Brand accent" />
        <TweakColor label="Accent" value={t.accent} options={ACCENTS.map((a) => a.c)} onChange={(v) => setTweak("accent", v)} />
        <TweakSection label="Features" />
        <TweakToggle label="AI Brief in feed" value={t.brief} onChange={(v) => setTweak("brief", v)} />
      </TweaksPanel>
    </div>
  );
}

function Footer() {
  return (
    <footer style={{ borderTop: "2px solid var(--ink)", marginTop: 40 }}>
      <div className="shell" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "26px 28px", flexWrap: "wrap", gap: 16 }}>
        <div style={{ display: "flex", alignItems: "baseline", gap: 14 }}>
          <span style={{ fontFamily: "var(--serif)", fontWeight: 620, fontSize: 19 }}>SubMedium<span style={{ color: "var(--accent)" }}>.</span></span>
          <span className="meta">Every story. Every source. One brief.</span>
        </div>
        <div style={{ display: "flex", gap: 22, alignItems: "center" }}>
          <a className="meta" style={{ color: "var(--accent-2)", fontWeight: 500 }} href="SubMedium Mobile.html">iOS App ↗</a>
          {["About", "Sources", "Methodology", "API", "Privacy"].map((x) => <a key={x} className="meta" style={{ color: "var(--ink-2)" }} href="#">{x}</a>)}
        </div>
      </div>
    </footer>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
