/* ============================================================
   IBC Labs — Pages (part 1): Home, About, Research, Paper
   ============================================================ */

/* ---------- Home ---------- */
function HomePage() {
  const { areas, papers } = window.IBC;
  const featured = [window.IBC.paperById("ibc"), window.IBC.paperById("dit")];
  return (
    <div className="page">
      <section className="hero container">
        <div className="eyebrow hero__eyebrow">Independent Research</div>
        <h1 className="display hero__title">
          Toward a Standard of Identity in AI Interaction.
        </h1>
        <p className="hero__mission">
          IBC Labs studies how an interactive system holds a coherent identity across a
          conversation — and what it would take to hold that identity to a measurable standard.
        </p>
        <div className="hero__actions">
          <Link to="research/ibc" className="btn btn--solid">Read the IBC Paper <Arrow /></Link>
          <Link to="research" className="btn">Browse Research <Arrow /></Link>
        </div>
        <hr className="rule hero__rule" />
      </section>

      <section className="section--tight container">
        <div className="sectionhead">
          <h2 className="heading sectionhead__title">Research Areas</h2>
          <Link to="research" className="tlink sectionhead__link">All publications <Arrow /></Link>
        </div>
        <div className="grid-3">
          {areas.map((a) => <AreaCard key={a.id} area={a} />)}
        </div>
      </section>

      <section className="section--tight container">
        <div className="sectionhead">
          <h2 className="heading sectionhead__title">Featured Papers</h2>
        </div>
        <Rule />
        <div className="divider-list">
          {featured.map((p) => (
            <div className="featured__row" key={p.id}>
              <div>
                <Link to={"research/" + p.id} className="paperrow__titlelink">
                  <div className="featured__title">{p.title}</div>
                </Link>
                <div className="featured__meta">
                  <span>{p.authors.join(", ")}</span>
                  <span className="paperrow__dot">·</span>
                  <Badge status={p.status} />
                  <span className="paperrow__dot">·</span>
                  <span className="mono">{p.year}</span>
                </div>
              </div>
              <div className="featured__actions">
                <span className="tlink tlink--muted" onClick={(e) => e.preventDefault()}>PDF <Arrow dir="down" /></span>
                <Link to={"research/" + p.id} className="tlink">Read <Arrow /></Link>
              </div>
            </div>
          ))}
        </div>
      </section>

      <Footer />
    </div>
  );
}

/* ---------- About ---------- */
function AboutPage() {
  const { team } = window.IBC;
  return (
    <div className="page">
      <div className="container">
        <PageHeader
          eyebrow="About"
          title="An independent research lab."
          lead="IBC Labs is a small, self-directed group studying the measurement of identity in AI interaction. We publish openly and answer to the work."
        />
        <section className="section--tight">
          <div className="prose">
            <p>
              We are not a product organization. We do not sell, advise, or advocate. Our output is
              research — papers, methodologies, and the concepts that hold them together — released
              when it is ready and revised when it is wrong.
            </p>
            <p>
              The lab grew out of a single observation: the thing people most rely on from an
              interactive system is the one thing our evaluations do not measure. A standard of
              identity is our attempt to close that gap, and everything we publish is in service of it.
            </p>
          </div>
        </section>
        <section className="section--tight">
          <h2 className="heading">Researchers</h2>
          <Rule />
          <div className="teamgrid">
            {team.map((m) => (
              <div className="teamcard" key={m.name}>
                <div className="teamcard__name">{m.name}</div>
                <div className="teamcard__role">{m.role}</div>
                <div className="teamcard__focus">{m.focus}</div>
              </div>
            ))}
          </div>
        </section>
      </div>
      <Footer />
    </div>
  );
}

/* ---------- Research index ---------- */
function ResearchPage() {
  const [filter, setFilter] = useState("All");
  const { papers } = window.IBC;
  const filters = ["All", "Published", "Active", "Forthcoming"];
  const shown = filter === "All" ? papers : papers.filter((p) => p.status === filter);
  return (
    <div className="page">
      <div className="container">
        <PageHeader
          eyebrow="Publications"
          title="Research Publications"
          lead="Papers and working drafts from IBC Labs. Published work is versioned; active drafts are revised in the open."
        />
        <div className="filterbar">
          {filters.map((f) => (
            <button
              key={f}
              className={"filter" + (filter === f ? " is-active" : "")}
              onClick={() => setFilter(f)}
            >
              {f}
            </button>
          ))}
        </div>
        <section className="section--tight" style={{ paddingTop: "var(--s3)" }}>
          <div className="divider-list">
            {shown.length ? shown.map((p) => <PaperRow key={p.id} paper={p} />) : (
              <p className="muted" style={{ padding: "var(--s4) 0" }}>No papers with this status.</p>
            )}
          </div>
        </section>
      </div>
      <Footer />
    </div>
  );
}

/* ---------- BibTeX builder ---------- */
function bibtex(p) {
  const key = p.authors[0].toLowerCase() + p.year + p.id;
  return `@techreport{${key},
  title   = {${p.title}},
  author  = {${p.authors.join(" and ")}},
  year    = {${p.year}},
  institution = {IBC Labs},
  note    = {${p.status}}
}`;
}

/* ---------- Paper detail ---------- */
function PaperPage({ id }) {
  const p = window.IBC.paperById(id);
  const [copied, setCopied] = useState(false);
  useEffect(() => { setCopied(false); }, [id]);
  if (!p) {
    return (
      <div className="page container">
        <BackLink to="research">Back to Research</BackLink>
        <PageHeader title="Paper not found" lead="This paper does not exist." />
        <Footer />
      </div>
    );
  }
  const copy = () => {
    const text = bibtex(p);
    const done = () => { setCopied(true); setTimeout(() => setCopied(false), 1800); };
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(text).then(done).catch(done);
    } else { done(); }
  };
  const related = (p.related || []).map((rid) => window.IBC.paperById(rid)).filter(Boolean);

  return (
    <div className="page">
      <div className="container">
        <BackLink to="research">Back to Research</BackLink>
        <div className="paperlayout">
          <article>
            <div className="paperdetail__status"><Badge status={p.status} /></div>
            <h1 className="display paperdetail__title">{p.title}</h1>
            <div className="paperdetail__byline">{p.authors.join(", ")} · {p.year}</div>
            <Rule />
            <p className="paperdetail__abstract">{p.abstract}</p>
            <div className="paperbody">
              {p.body.map((sec, i) => (
                <section key={i}>
                  <h2>{sec.h}</h2>
                  {sec.p.map((para, j) => <p key={j}>{para}</p>)}
                </section>
              ))}
            </div>
            {related.length > 0 && (
              <div className="related">
                <h3 className="subheading related__title">Related Papers</h3>
                <div className="related__links">
                  {related.map((r) => (
                    <Link key={r.id} to={"research/" + r.id} className="tlink">{r.title} <Arrow /></Link>
                  ))}
                </div>
              </div>
            )}
          </article>

          <aside className="sidebar">
            <div className="sidebar__block">
              <button className="btn btn--solid" style={{ width: "100%", justifyContent: "center" }} onClick={(e) => e.preventDefault()}>
                Download PDF <Arrow dir="down" />
              </button>
            </div>
            <div className="sidebar__block">
              <div className="label sidebar__label">Authors</div>
              <div className="sidebar__value">{p.authors.join(", ")}</div>
              <div className="label sidebar__label" style={{ marginTop: "var(--s2)" }}>Status</div>
              <div className="sidebar__value"><Badge status={p.status} /></div>
              <div className="label sidebar__label" style={{ marginTop: "var(--s2)" }}>Date</div>
              <div className="sidebar__value mono">{p.date}</div>
            </div>
            <div className="sidebar__block">
              <div className="label sidebar__label">Cite this paper</div>
              <div className="bibtex">{bibtex(p)}</div>
              <button className="copybtn" onClick={copy}>{copied ? "✓ Copied" : "Copy BibTeX"}</button>
            </div>
            <div className="sidebar__block">
              <div className="label sidebar__label">Revision history</div>
              <div className="revlist">
                {p.revisions.map((r, i) => (
                  <div className="revlist__item" key={i}>
                    <span className="revlist__v">{r.v} · {r.date}</span>
                    <span className="revlist__note">{r.note}</span>
                  </div>
                ))}
              </div>
            </div>
          </aside>
        </div>
      </div>
      <Footer />
    </div>
  );
}

Object.assign(window, { HomePage, AboutPage, ResearchPage, PaperPage, bibtex });
