/* ============================================================
   The Carnation — trust & accountability pages
   Masthead/Staff · Ethics & Standards · Corrections · Funding · Contact
   ============================================================ */

/* ===================== MASTHEAD / STAFF ===================== */
function StaffPage() {
  const D = C();
  useStore();
  return (
    <main className="route">
      <section className="phead">
        <div className="wrap">
          <div className="phead__kick">Masthead</div>
          <h1 className="phead__title">Who makes The Carnation</h1>
          <p className="phead__dek">The Carnation begins in Alliance, but its questions are bigger: what happens when overlooked American places start narrating, modernizing, and building their own future. A small core, a wide circle, and a serious public record.</p>
          <hr className="rule rule--double phead__rule" />
        </div>
      </section>

      <section className="section section--tight">
        <div className="wrap">
          <Reveal>
            <div className="staff-grid rise">
              {D.STAFF.map((p) => (
                <div className="staff" key={p.id}>
                  <Avatar slot={"staff:" + p.id} initials={p.name.split(" ").map(w=>w[0]).join("").slice(0,2)} size={72} className="staff__av" />
                  <div className="staff__role">{p.role}</div>
                  <div className="staff__name">{p.name}</div>
                  <p className="staff__bio">{p.bio}</p>
                  {p.authorKey
                    ? <a className="staff__link" href={"#/author/" + p.authorKey}>Read their stories →</a>
                    : (p.id === "contributors" || p.id === "staff"
                        ? <a className="staff__link" href="#/join">Join the desk →</a>
                        : null)}
                </div>
              ))}
            </div>
          </Reveal>
        </div>
      </section>

      <section className="section section--tint section--tight">
        <div className="wrap wrap--mid">
          <SecRule title="The masthead" meta="Publication of record" />
          <div className="masthead-list">
            <div className="mrow"><span className="mrow__k">Publication</span><span className="mrow__v">The Carnation</span></div>
            <div className="mrow"><span className="mrow__k">Published by</span><span className="mrow__v">Alliance Renaissance</span></div>
            <div className="mrow"><span className="mrow__k">Home base</span><span className="mrow__v">Alliance, Ohio</span></div>
            <div className="mrow"><span className="mrow__k">Editorial scope</span><span className="mrow__v">The Carnation City region, Ohio's new economy, and the future of overlooked American places.</span></div>
            <div className="mrow"><span className="mrow__k">Purpose</span><span className="mrow__v">A civic journal for Alliance, Ohio, and the future of American places.</span></div>
            <div className="mrow"><span className="mrow__k">Focus</span><span className="mrow__v">Stories, ideas, business, spaces, culture, public life, civic futures, and local intelligence.</span></div>
            <div className="mrow"><span className="mrow__k">Founded</span><span className="mrow__v">2026</span></div>
            <div className="mrow"><span className="mrow__k">Publishing rhythm</span><span className="mrow__v">Biweekly features, periodic notes, and The Dispatch.</span></div>
            <div className="mrow"><span className="mrow__k">Standards</span><span className="mrow__v"><a href="#/ethics" style={{color:"var(--red)"}}>Ethics &amp; Standards</a> · <a href="#/corrections" style={{color:"var(--red)"}}>Corrections</a> · <a href="#/funding" style={{color:"var(--red)"}}>Funding</a></span></div>
          </div>
          <p className="note" style={{marginTop:"20px"}}>The Carnation grows through contributors, partners, readers, photographers, business owners, and residents who believe Alliance deserves a serious public record. <a href="#/join" style={{color:"var(--red)"}}>Share a lead, nominate a business, contribute a piece, or partner with the publication →</a></p>
        </div>
      </section>
    </main>
  );
}

/* ===================== AUTHOR (stories by one writer) ===================== */
function AuthorPage({ authorKey }) {
  const D = C();
  const a = D.authorOf(authorKey);
  const list = D.byAuthorKey(authorKey);
  useStore();
  useEffect(() => { window.scrollTo(0, 0); }, [authorKey]);
  const totalViews = list.reduce((s, x) => s + (D.views(x.slug) || 0), 0);
  const fmtNum = (n) => n >= 1e6 ? (n/1e6).toFixed(1).replace(/\.0$/,"") + "M" : n >= 1e3 ? (n/1e3).toFixed(1).replace(/\.0$/,"") + "K" : String(n);
  const avg = list.length ? Math.round(totalViews / list.length) : 0;
  return (
    <main className="route">
      <section className="phead">
        <div className="wrap wrap--mid">
          <a className="backlink" href="#/staff">← Masthead</a>
          <div className="author-head">
            <Avatar slot={"author:" + authorKey} initials={a.initials} size={84} />
            <div>
              <div className="phead__kick">{a.role}</div>
              <h1 className="phead__title" style={{margin:"6px 0 10px"}}>{a.name}</h1>
              <p className="phead__dek" style={{maxWidth:"56ch"}}>{a.bio}</p>
              <AuthorContact a={a} fineprint />
              <SocialRow label="Follow The Carnation" />
            </div>
          </div>
          {list.length > 0 && (
            <div className="author-metrics">
              <div className="ametric"><span className="ametric__n">{fmtNum(totalViews)}</span><span className="ametric__l">Total reads</span></div>
              <div className="ametric"><span className="ametric__n">{list.length}</span><span className="ametric__l">{list.length === 1 ? "Story filed" : "Stories filed"}</span></div>
              <div className="ametric"><span className="ametric__n">{fmtNum(avg)}</span><span className="ametric__l">Avg. per story</span></div>
            </div>
          )}
          <hr className="rule rule--double phead__rule" />
        </div>
      </section>
      <section className="section section--tight">
        <div className="wrap">
          <Reveal>
            {list.length ? (
              <div className="listgrid rise">{list.map((x) => <ArticleCard a={x} size="md" key={x.slug} />)}</div>
            ) : <p className="note">No stories filed yet.</p>}
          </Reveal>
        </div>
      </section>
    </main>
  );
}

/* ===================== ETHICS & STANDARDS ===================== */
function EthicsPage() {
  const D = C();
  return (
    <main className="route">
      <section className="phead">
        <div className="wrap">
          <div className="phead__kick">Accountability</div>
          <h1 className="phead__title">Ethics &amp; Standards</h1>
          <p className="phead__dek">We ask the city to be transparent. These are the rules we hold ourselves to in return.</p>
          <hr className="rule rule--double phead__rule" />
        </div>
      </section>

      <section className="section section--tight">
        <div className="wrap wrap--mid">
          <Reveal>
            <div className="standards rise">
              {D.ETHICS.map((e, i) => (
                <div className="standard" key={e.h}>
                  <span className="standard__n">{String(i+1).padStart(2,"0")}</span>
                  <div>
                    <h3 className="standard__h">{e.h}</h3>
                    <p className="standard__p">{e.p}</p>
                  </div>
                </div>
              ))}
            </div>
          </Reveal>
          <div style={{marginTop:"34px", display:"flex", gap:"14px", flexWrap:"wrap"}}>
            <a className="btn btn--line" href="#/corrections">See our corrections log <span className="arw">→</span></a>
            <a className="btn btn--line" href="#/funding">How we're funded</a>
          </div>
        </div>
      </section>
    </main>
  );
}

/* ===================== CORRECTIONS (log + report form) ===================== */
function CorrectionsPage() {
  const D = C();
  useStore();
  const [form, setForm] = useState({ article: "", text: "", email: "" });
  const [sent, setSent] = useState(false);
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));
  const submit = async (e) => {
    e.preventDefault();
    const ok = await window.captureOrAlert("submissions", { type: "Correction Report", title: form.article, body: form.text, email: form.email });
    if (!ok) return;
    setSent(true);
    setForm({ article: "", text: "", email: "" });
    setTimeout(() => setSent(false), 5000);
  };
  return (
    <main className="route">
      <section className="phead">
        <div className="wrap">
          <div className="phead__kick">Accountability</div>
          <h1 className="phead__title">Corrections</h1>
          <p className="phead__dek">We fix our mistakes in public and keep the record. Every correction we've made is logged here, newest first.</p>
          <hr className="rule rule--double phead__rule" />
        </div>
      </section>

      <section className="section section--tight">
        <div className="wrap wrap--mid">
          <SecRule title="Corrections log" meta={D.CORRECTIONS.length + " on record"} />
          <div className="corr-log">
            {D.CORRECTIONS.map((c, i) => (
              <div className="corr" key={i}>
                <span className="corr__date">{c.date}</span>
                <div className="corr__body">
                  <a className="corr__art" href={"#/article/" + c.slug}>{c.article}</a>
                  <p className="corr__text">{c.text}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="section section--tint section--tight">
        <div className="wrap wrap--narrow">
          <SecRule title="Spot a mistake?" meta="Tell us" />
          {sent ? (
            <div className="sent">Thank you — your correction request is in. We review every one and post a public correction when warranted.</div>
          ) : (
            <form className="form" onSubmit={submit}>
              <div className="frow"><label>Which story?</label><input className="input" required value={form.article} onChange={set("article")} placeholder="Headline or link" /></div>
              <div className="frow"><label>What's wrong?</label><textarea className="textarea" required value={form.text} onChange={set("text")} placeholder="Describe the error and, if you can, the correct information and your source." /></div>
              <div className="frow"><label>Email</label><input className="input" type="email" value={form.email} onChange={set("email")} placeholder="So we can follow up (optional)" /></div>
              <button className="btn btn--red" type="submit">Send correction request <span className="arw">→</span></button>
            </form>
          )}
        </div>
      </section>
    </main>
  );
}

/* ===================== FUNDING & OWNERSHIP ===================== */

/* Live supporter data comes from CLOUD.listSupporters(). Until real,
   permission-granted supporters exist, the roll shows a recognition placeholder
   rather than any placeholder names. */

function SupportersRoll() {
  const cloud = window.CLOUD && window.CLOUD.enabled;
  const [rows, setRows] = useState(cloud ? null : []);
  useEffect(() => {
    if (!cloud) return;
    let alive = true;
    window.CLOUD.listSupporters().then((r) => { if (alive) setRows(r || []); });
    return () => { alive = false; };
  }, [cloud]);

  if (rows === null) return null; // still loading from the database

  const named = rows.filter((r) => r.name && r.name.trim());
  const anon = rows.length - named.length;
  const patrons = named.filter((r) => r.tier === "patron");
  const members = named.filter((r) => r.tier === "member");
  const friends = named.filter((r) => r.tier === "coffee");

  if (rows.length === 0) {
    return (
      <section className="section section--tight supgroup">
        <div className="wrap wrap--mid">
          <div className="sup__head">
            <span className="kicker">Community-supported</span>
            <h2 className="sup__h">The Founding Supporters</h2>
            <p className="sup__intro" style={{textWrap:"balance"}}>Founding Supporter recognition will appear here as early individuals, families, alumni, and community members join The Carnation.</p>
          </div>
          <div style={{textAlign:"center"}}><a className="btn btn--navy btn--lg" href="#/membership">Become a Founding Supporter <span className="arw">→</span></a></div>
        </div>
      </section>
    );
  }

  const Tier = ({ label, count, people, lead }) => people.length ? (
    <div className={"sup__tier" + (lead ? " sup__tier--lead" : "")}>
      <div className="sup__label"><span className="sup__bar" />{label}<span className="sup__count">{count}</span></div>
      <ul className={"sup__roll" + (lead ? " sup__roll--lead" : "")}>
        {people.map((p, i) => <li className="sup__name" key={p.name + i}>{p.name}</li>)}
      </ul>
    </div>
  ) : null;

  return (
    <section className="section section--tight supgroup">
      <div className="wrap wrap--mid">
        <div className="sup__head">
          <span className="kicker">Community-supported</span>
          <h2 className="sup__h">The Founding Supporters</h2>
          <p className="sup__intro">The Carnation stays free to read because these neighbors pay for it — by choice, with no paywall in return. Our thanks to every one of them.</p>
        </div>
        <Reveal>
          <div className="sup rise">
            <Tier label="Patrons" count={patrons.length} people={patrons} lead />
            <Tier label="Members" count={members.length} people={members} />
            <Tier label="Friends of The Carnation" count={friends.length} people={friends} />
            {anon > 0 && <p className="sup__anon">…and {anon} {anon === 1 ? "neighbor who gives" : "neighbors who give"} anonymously.</p>}
          </div>
        </Reveal>
        <p className="sup__foot">Listed with permission. Prefer not to appear here?<br />Tell us at checkout or email <a href="#/contact">the editors</a> and we'll remove your name.</p>
      </div>
    </section>
  );
}

function FundingPage() {
  const D = C();
  const f = D.FUNDING;
  return (
    <main className="route">
      <section className="phead">
        <div className="wrap">
          <div className="phead__kick">Transparency</div>
          <h1 className="phead__title">How We&rsquo;re Funded</h1>
          <p className="phead__dek">The Carnation is published by Alliance Renaissance.<br />We believe readers should know who supports the work, how the publication is funded, and how editorial independence is protected.</p>
          <hr className="rule rule--double phead__rule" />
        </div>
      </section>

      <section className="section section--tight">
        <div className="wrap wrap--mid">
          <SecRule title="How the publication is designed to be funded" meta="Our intended funding mix" />
          <Reveal>
            <div className="fund rise">
              {f.sources.map((s) => (
                <div className="fundrow" key={s.label}>
                  <div className="fundrow__top">
                    <span className="fundrow__label">{s.label}</span>
                    <span className="fundrow__share">{s.share}</span>
                  </div>
                  <div className="fundbar"><span className="fundbar__fill" style={{width: s.share.replace(/[^\d]/g,"") + "%"}} /></div>
                  <p className="fundrow__desc">{s.desc}</p>
                </div>
              ))}
            </div>
          </Reveal>
        </div>
      </section>

      <SupportersRoll />

      <section className="section section--tint section--tight">
        <div className="wrap wrap--mid">
          <SecRule title="Editorial independence" />
          <div style={{background:"var(--paper)", border:"1px solid var(--line)", borderLeft:"4px solid var(--red)", padding:"clamp(26px,3.6vw,46px)", boxShadow:"0 26px 60px -38px rgba(21,17,12,.5)"}}>
            <p className="art__body" style={{maxWidth:"720px", fontSize:"1.12rem", margin:0}}>{f.governance}</p>
            <div style={{marginTop:"28px", display:"flex", gap:"14px", flexWrap:"wrap"}}>
              <a className="btn btn--red" href="#/membership">Support the work <span className="arw">→</span></a>
              <a className="btn btn--line" href="#/ethics">Read our standards</a>
            </div>
          </div>
        </div>
      </section>

      <section className="section section--tight">
        <div className="wrap wrap--mid">
          <div style={{position:"relative", background:"var(--ink)", color:"var(--paper)", border:"1px solid rgba(244,239,227,.18)", borderLeft:"4px solid var(--red)", padding:"clamp(30px,4vw,52px)", boxShadow:"0 30px 70px -40px rgba(21,17,12,.7)"}}>
            <div style={{display:"flex", justifyContent:"space-between", alignItems:"baseline", gap:"16px", flexWrap:"wrap", marginBottom:"clamp(14px,2vw,20px)"}}>
              <h2 style={{fontFamily:"var(--serif)", fontWeight:600, letterSpacing:"-.01em", fontSize:"clamp(1.6rem,3.4vw,2.4rem)", lineHeight:1.05, margin:0, color:"var(--paper)", maxWidth:"20ch"}}>Interested in supporting The Carnation?</h2>
              <span style={{fontFamily:"var(--mono)", fontSize:".66rem", letterSpacing:".18em", textTransform:"uppercase", color:"rgba(244,239,227,.6)", whiteSpace:"nowrap"}}>For partners</span>
            </div>
            <p style={{fontFamily:"var(--serif)", fontSize:"1.12rem", lineHeight:1.6, color:"rgba(244,239,227,.82)", maxWidth:"560px", textWrap:"balance", margin:0}}>Businesses, institutions, and civic supporters can learn about partner recognition, section support, spotlights, and the Local Index.</p>
            <div style={{marginTop:"clamp(22px,3vw,30px)"}}>
              <a className="btn btn--red" href="#/advertise">Partner With The Carnation <span className="arw">→</span></a>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

/* ===================== CONTACT ===================== */
function ContactPage() {
  const D = C();
  const c = D.CONTACT;
  const rows = [
    { k: "General", v: c.general, d: "Questions, feedback, anything else." },
    { k: "News tips", v: c.tips, d: "The fastest way to reach the newsroom." },
    { k: "Corrections", v: c.corrections, d: "Or use the form on our corrections page." },
    { k: "Advertise & sponsor", v: c.advertise, d: "Partnerships, Spotlights, and sponsorship." },
  ];
  return (
    <main className="route">
      <section className="phead">
        <div className="wrap">
          <div className="phead__kick">Contact</div>
          <h1 className="phead__title">Reach The Carnation</h1>
          <p className="phead__dek">{c.note}</p>
          <hr className="rule rule--double phead__rule" />
        </div>
      </section>

      <section className="section section--tight">
        <div className="wrap wrap--mid">
          <div className="contact-grid">
            {rows.map((r) => (
              <div className="contactcard" key={r.k}>
                <span className="contactcard__k">{r.k}</span>
                <a className="contactcard__v" href={"mailto:" + r.v}>{r.v}</a>
                <span className="contactcard__d">{r.d}</span>
              </div>
            ))}
          </div>
          <div className="contact-addr">
            <span className="meta">Mailing</span>
            <p>{c.address}</p>
          </div>
          <div className="dual" style={{marginTop:"clamp(30px,4vw,52px)"}}>
            <div className="dual__cell">
              <span className="dual__kick">Have something to say?</span>
              <h3 className="dual__h">Weigh in on an Open Question.</h3>
              <p className="dual__p">For a public response the whole city can read, our Open Questions are the place — submit an answer and read what Alliance is saying.</p>
              <a className="btn btn--line" href="#/ideas">See Open Questions <span className="arw">→</span></a>
            </div>
            <div className="dual__cell dual__cell--ink">
              <span className="dual__kick">Got a lead?</span>
              <h3 className="dual__h">Send it to the desk.</h3>
              <p className="dual__p">Nominate a business, flag a space, pitch a story, or send a correction. Good leads become coverage.</p>
              <a className="btn btn--red" href="#/submit" style={{marginTop:"auto", alignSelf:"flex-start"}}>Submit to The Carnation</a>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

window.StaffPage = StaffPage;
window.AuthorPage = AuthorPage;
window.EthicsPage = EthicsPage;
window.CorrectionsPage = CorrectionsPage;
window.FundingPage = FundingPage;
window.ContactPage = ContactPage;
