/* global React, Nav, Footer, Hero, BriefingCard, CtaRail, CtaBar, SummaryBox, Takeaways, SignupGate, SignupForm, AuthorBio, AudioPlayer, ListenRow, ChipRow, Wordmark, MedallionReversed, renderInline, BriefingBody */
const { useState, useMemo } = React;

/* All editable content now lives in content.json (loaded in app.jsx and
   passed down as the `content` prop). To add or change a Briefing, a
   Logbook issue or a Soundings episode, edit that file — not this one. */

/* ============================================================== */

function HomePage({ content, onNav, signedIn, onSignup }) {
  return (
    <>
      <Hero
        onPrimary={() => onNav("briefings")}
        onSecondary={() => onNav("signup")}
      />
      <section className="container" style={{ paddingTop: "var(--sp-8)", paddingBottom: "var(--sp-7)" }}>
        <div className="row-between" style={{ alignItems: "flex-end" }}>
          <div>
            <h1 style={{ fontSize: 32 }}>Briefings</h1>
            <p className="muted" style={{ marginTop: 6 }}>Short, useful explainers on shipping and trade law. Sign in to read in full.</p>
          </div>
          <button className="btn btn-secondary" onClick={() => onNav("briefings")}>All Briefings →</button>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 20, marginTop: 24 }}>
          {content.briefings.slice(0, 3).map(b => (
            <BriefingCard key={b.slug} b={b} signedIn={signedIn} onOpen={() => onNav("briefing", b.slug)} />
          ))}
        </div>
      </section>

    </>
  );
}

/* ============================================================== */

function BriefingsIndex({ content, onNav, signedIn }) {
  const [topic, setTopic] = useState("All");
  const [q, setQ] = useState("");
  const filtered = useMemo(() => content.briefings.filter(b => (topic === "All" || b.topic === topic) && (q === "" || b.title.toLowerCase().includes(q.toLowerCase()))), [content, topic, q]);
  return (
    <section className="container" style={{ paddingTop: "var(--sp-7)", paddingBottom: "var(--sp-8)" }}>
      <h1>Briefings</h1>
      <p className="muted" style={{ marginTop: 6 }}>All Briefings to date — sorted by recency. Sign in to read in full.</p>
      <div style={{ display: "flex", gap: 16, marginTop: 24, alignItems: "center", flexWrap: "wrap" }}>
        <ChipRow items={content.topics} active={topic} onPick={setTopic} />
        <div style={{ marginLeft: "auto", minWidth: 240 }}>
          <input className="input" placeholder="🔍  Search Briefings…" value={q} onChange={e => setQ(e.target.value)} />
        </div>
      </div>

      <div className="stack" style={{ marginTop: 24 }}>
        {filtered.map(b => (
          <article key={b.slug} className="card row-between" onClick={() => onNav("briefing", b.slug)} style={{ cursor: "pointer" }}>
            <div>
              <h3 style={{ fontSize: 18 }}>{b.title}{b.status === "draft" && <span style={{ marginLeft: 10, fontSize: 11, fontWeight: 600, letterSpacing: ".06em", color: "var(--brass)", verticalAlign: "middle" }}>DRAFT</span>}</h3>
              <div className="editorial" style={{ marginTop: 4, fontSize: 13 }}>{b.topic} · {b.minutes} min · {b.date}</div>
            </div>
            <button className="btn btn-secondary" onClick={(e) => { e.stopPropagation(); onNav("briefing", b.slug); }}>{signedIn ? "Open" : "Sign in to read"}</button>
          </article>
        ))}
        {filtered.length === 0 && (
          <div className="card" style={{ textAlign: "center", padding: "var(--sp-7)" }}>
            <h3>No Briefings yet on this topic</h3>
            <p className="editorial" style={{ marginTop: 6 }}>Back soon. In the meantime, sign up and we'll let you know when one lands.</p>
          </div>
        )}
      </div>

      <div style={{ display: "flex", justifyContent: "center", gap: 14, marginTop: 32, color: "var(--slate)", fontSize: 13 }}>
        <span>← 1 2 3 →</span>
      </div>
    </section>
  );
}

/* ============================================================== */

function BriefingDetail({ content, slug, onNav, signedIn, onSignup }) {
  if (!content.briefings.length) {
    return (
      <section className="container" style={{ paddingTop: "var(--sp-7)", paddingBottom: "var(--sp-8)" }}>
        <a className="crumb" onClick={(e) => { e.preventDefault(); onNav("briefings"); }} href="#">← Briefings</a>
        <h1 style={{ marginTop: 14 }}>No Briefings yet</h1>
        <p className="muted" style={{ marginTop: 6 }}>Add your first Briefing in content.json.</p>
      </section>
    );
  }
  const b = content.briefings.find(x => x.slug === slug) || content.briefings[0];
  const bodyMd = b.body || "";
  const author = (content.site && content.site.author) || "Jonathan Cooke";
  return (
    <>
      <section className="container" style={{ paddingTop: "var(--sp-6)", paddingBottom: "var(--sp-8)" }}>
        <a className="crumb" onClick={(e) => { e.preventDefault(); onNav("briefings"); }} href="#">← Briefings</a>
        <div style={{ marginTop: 14, maxWidth: 820 }}>
          <article>
            <div className="eyebrow" style={{ color: "var(--brass)" }}>BRIEFING · {b.topic}</div>
            <h1 style={{ fontSize: 32, marginTop: 8 }}>{b.title}</h1>
            <p className="editorial" style={{ marginTop: 8, fontSize: 14 }}>{b.minutes} min read · Updated {b.updated || b.date} · By {author}</p>

            <div className="stack-lg" style={{ marginTop: 24 }}>
              <SummaryBox>{renderInline(b.summary || "", "sum")}</SummaryBox>
              <Takeaways items={(b.takeaways || []).map((t, i) => renderInline(t, "tk" + i))} />
            </div>

            {!signedIn && (
              <div style={{ marginTop: "var(--sp-7)" }}>
                <SignupGate onSubmit={() => onSignup()} />
              </div>
            )}

            {signedIn && (
              <>
                <MarkdownBody markdown={bodyMd} style={{ marginTop: "var(--sp-7)" }} />

                <div style={{ marginTop: "var(--sp-7)", display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
                  <button className="btn btn-secondary">↓ Download as PDF</button>
                  <span className="editorial" style={{ fontSize: 13 }}>Branded PDF, watermarked with your email.</span>
                </div>

                <div style={{ marginTop: "var(--sp-6)" }}>
                  <AuthorBio />
                </div>

                <div style={{ marginTop: "var(--sp-7)" }}>
                  <h3 style={{ fontSize: 19 }}>Related Briefings</h3>
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 16, marginTop: 12 }}>
                    {content.briefings.filter(x => x.slug !== b.slug).slice(0, 3).map(rb => (
                      <BriefingCard key={rb.slug} b={rb} signedIn={signedIn} onOpen={() => onNav("briefing", rb.slug)} />
                    ))}
                  </div>
                </div>
              </>
            )}
          </article>

        </div>
      </section>
    </>
  );
}

/* ============================================================== */

function SoundingsRemoved() { return null; }

/* ============================================================== */

function BridgeRemoved() { return null; }

/* ============================================================== */

function Dashboard({ onNav }) {
  return (
    <section className="container" style={{ paddingTop: "var(--sp-7)", paddingBottom: "var(--sp-8)" }}>
      <h1>Welcome back, Jonathan</h1>
      <p className="muted" style={{ marginTop: 6 }}>Your Anchorage and recent Briefings.</p>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 20, marginTop: 28 }}>
        {[
          { title: "My Anchorage", sub: "Saved Briefings", items: [{ t: "Hague-Visby package limit", m: 7 }, { t: "Demurrage time bars", m: 7 }] },
          { title: "Recently viewed", sub: "Last 30 days", items: [{ t: "Notice of Readiness", m: 5 }, { t: "Off-hire", m: 6 }, { t: "FOB stop-loading", m: 8 }] },
          { title: "Recommended for you", sub: "Based on your area", items: [{ t: "Cargo claims defences", m: 6 }, { t: "Bills of lading", m: 6 }, { t: "Hague Rules", m: 5 }] },
        ].map((col, i) => (
          <div key={i} className="card">
            <h3 style={{ fontSize: 18 }}>{col.title}</h3>
            <p className="editorial" style={{ fontSize: 13, marginTop: 2 }}>{col.sub}</p>
            <div className="stack" style={{ marginTop: 14 }}>
              {col.items.map((it, j) => (
                <div key={j} style={{ borderTop: j > 0 ? "1px solid var(--soft-border)" : 0, paddingTop: j > 0 ? 12 : 0 }}>
                  <div style={{ fontWeight: 600, fontSize: 14 }}>{it.t}</div>
                  <div style={{ marginTop: 4, fontSize: 12 }}><span className="editorial" style={{ fontSize: 12 }}>{it.m} min · </span><a href="#" style={{ color: "var(--brass)" }}>Open →</a></div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

    </section>
  );
}

/* ============================================================== */

/* The Logbook digest. Member topics, the editorial note, this month's
   Soundings and the archive all come from content.json (content.logbook
   + content.member). In production member topics come from the signed-in
   user's saved preferences. */
function LogbookPage({ content, onNav, signedIn }) {
  const lb = content.logbook || {};
  const member = content.member || { name: "there", topics: [] };
  const monthName = (lb.currentIssue || "").split(" ")[0] || "latest";
  /* ---- anonymous: public marketing + gate --------------------- */
  if (!signedIn) {
    return (
      <section className="container" style={{ paddingTop: "var(--sp-7)", paddingBottom: "var(--sp-8)" }}>
        <div className="eyebrow">THE LOGBOOK</div>
        <h1 style={{ marginTop: 4 }}>The monthly digest</h1>
        <p className="editorial" style={{ marginTop: 8, maxWidth: 620, fontSize: 16 }}>
          One email a month: the new Briefings and a short note on what's moving in shipping and trade law — chosen around the topics you follow. Read it in your inbox or here.
        </p>

        <div className="card" style={{ marginTop: 28, maxWidth: 620, borderColor: "var(--ink-navy)", borderWidth: 1.5 }}>
          <h3 style={{ fontSize: 20 }}>The Logbook is for members</h3>
          <p className="editorial" style={{ marginTop: 6, fontSize: 14 }}>
            Sign up free to get the digest each month and read the full archive of past issues here, personalised to your topics.
          </p>
          <div style={{ display: "flex", gap: 12, marginTop: 18, flexWrap: "wrap" }}>
            <button className="btn btn-primary" onClick={() => onNav("signup")}>Sign up — free</button>
            <button className="btn btn-secondary" onClick={() => onNav("signin")}>Sign in</button>
          </div>
        </div>
      </section>
    );
  }

  /* ---- signed in: personalised current issue ------------------ */
  const picked = content.briefings.filter((b) => member.topics.includes(b.topic));
  const pickedSlugs = new Set(picked.map((b) => b.slug));
  const alsoNew = content.briefings.filter((b) => !pickedSlugs.has(b.slug));

  const Item = ({ b }) => (
    <div style={{ paddingTop: 14, marginTop: 14, borderTop: "1px solid var(--soft-border)" }}>
      <div style={{ fontWeight: 600, fontSize: 15 }}>{b.title}</div>
      <div style={{ marginTop: 4, fontSize: 12 }}>
        <span className="editorial" style={{ fontSize: 12 }}>{b.topic} · {b.minutes} min · {b.date} · </span>
        <a href="#" style={{ color: "var(--brass)" }} onClick={(e) => { e.preventDefault(); onNav("briefing", b.slug); }}>Open →</a>
      </div>
    </div>
  );

  return (
    <section className="container" style={{ paddingTop: "var(--sp-7)", paddingBottom: "var(--sp-8)" }}>
      <div className="eyebrow">THE LOGBOOK{lb.currentIssue ? " · " + lb.currentIssue.toUpperCase() : ""}</div>
      <h1 style={{ marginTop: 4 }}>Your {monthName} issue</h1>
      <p className="muted" style={{ marginTop: 6 }}>
        {member.topics.length ? <>Personalised around the topics you follow: {member.topics.join(" · ")}. </> : <>Your monthly digest. </>}
        <a href="#" style={{ color: "var(--brass)" }} onClick={(e) => { e.preventDefault(); onNav("dashboard"); }}>Change topics</a>
      </p>

      {/* editorial note */}
      {lb.note && (
        <div className="card" style={{ marginTop: 24, background: "var(--paper-warm)" }}>
          <p className="editorial" style={{ fontStyle: "italic", fontSize: 16, lineHeight: 1.55, margin: 0 }}>
            "{lb.note}" — {member.name === "Jonathan" ? "JC" : member.name}
          </p>
        </div>
      )}

      <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 24, marginTop: 24, alignItems: "start" }}>
        {/* main column */}
        <div>
          <div className="card">
            <h3 style={{ fontSize: 18 }}>Picked for you</h3>
            <p className="editorial" style={{ fontSize: 13, marginTop: 2 }}>From {member.topics.join(" & ")}</p>
            {picked.length
              ? picked.map((b) => <Item key={b.slug} b={b} />)
              : <p className="editorial" style={{ fontSize: 14, marginTop: 12 }}>Nothing new in your topics this month — see below.</p>}
          </div>

          <div className="card" style={{ marginTop: 20 }}>
            <h3 style={{ fontSize: 18 }}>Also new this month</h3>
            <p className="editorial" style={{ fontSize: 13, marginTop: 2 }}>Across all topics</p>
            {alsoNew.map((b) => <Item key={b.slug} b={b} />)}
          </div>
        </div>

        {/* side rail */}
        <div className="stack" style={{ gap: 20 }}>
          <div className="card" style={{ background: "var(--paper-warm)" }}>
            <h3 style={{ fontSize: 16 }}>Manage your digest</h3>
            <p className="editorial" style={{ fontSize: 13, marginTop: 4 }}>Change topics or how often the Logbook lands in your inbox.</p>
            <a href="#" style={{ color: "var(--brass)", fontSize: 13, display: "inline-block", marginTop: 10 }} onClick={(e) => { e.preventDefault(); onNav("dashboard"); }}>Email preferences →</a>
          </div>
        </div>
      </div>

      {/* archive */}
      <h2 style={{ marginTop: "var(--sp-7)", fontSize: 24 }}>Past issues</h2>
      <p className="muted" style={{ marginTop: 4 }}>The full archive — members only.</p>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: 16, marginTop: 18 }}>
        {(lb.archive || []).map((issue) => (
          <a
            key={issue.month}
            href="#"
            className="card"
            style={{ display: "block", textDecoration: "none", color: "inherit" }}
            onClick={(e) => e.preventDefault()}
          >
            <div style={{ fontWeight: 600, fontSize: 16 }}>{issue.month}</div>
            <div className="editorial" style={{ fontSize: 13, marginTop: 4 }}>{issue.count} Briefings · Open →</div>
          </a>
        ))}
      </div>
    </section>
  );
}

/* ============================================================== */

function SignupPage({ onDone }) {
  return (
    <section className="container" style={{ paddingTop: "var(--sp-8)", paddingBottom: "var(--sp-8)" }}>
      <SignupForm onDone={onDone} />
    </section>
  );
}

function SigninPage({ onDone }) {
  const [mode, setMode] = useState("link"); // "link" | "password"
  const [sent, setSent] = useState(false);
  return (
    <section className="container" style={{ paddingTop: "var(--sp-8)", paddingBottom: "var(--sp-8)" }}>
      <form className="card" style={{ maxWidth: 420, margin: "0 auto" }} onSubmit={(e) => { e.preventDefault(); if (mode === "link") { setSent(true); } else { onDone(); } }}>
        <div className="eyebrow">SIGN IN</div>
        <h2 style={{ marginTop: 4 }}>Welcome back</h2>

        {sent ? (
          <p style={{ marginTop: 18, fontFamily: "var(--font-serif)", color: "var(--slate)", lineHeight: 1.5 }}>
            Check your inbox — we've sent a sign-in link to your email. It's valid for 15 minutes.
          </p>
        ) : (
          <>
            <div style={{ marginTop: 18 }}>
              <label className="label">Email</label>
              <input className="input" placeholder="you@firm.com" />
            </div>

            {mode === "password" && (
              <div style={{ marginTop: 12 }}>
                <label className="label">Password</label>
                <input className="input" type="password" placeholder="••••••••" />
              </div>
            )}

            {mode === "link" ? (
              <button type="submit" className="btn btn-primary btn-block" style={{ marginTop: 16 }}>Email me a sign-in link</button>
            ) : (
              <button type="submit" className="btn btn-primary btn-block" style={{ marginTop: 16 }}>Sign in</button>
            )}

            <button
              type="button"
              className="btn btn-link btn-block"
              style={{ marginTop: 8 }}
              onClick={() => setMode(mode === "link" ? "password" : "link")}
            >
              {mode === "link" ? "Use a password instead" : "Email me a sign-in link instead"}
            </button>
          </>
        )}
      </form>
    </section>
  );
}

Object.assign(window, {
  HomePage, BriefingsIndex, BriefingDetail,
  Dashboard, LogbookPage, SignupPage, SigninPage,
});
