// ─────────────────────────────────────────────────────────────────────────
// pages.jsx — section components for non-landing public pages.
//
// All copy comes from window.{ABOUT,WAITLIST,ERROR404,DISCLOSE,CASES,LEGAL}
// (content-pages.jsx) and window.PRODUCTS (content.jsx). These components
// are designed to compose with the existing BSHeader / BSFooter / BSContact.
// ─────────────────────────────────────────────────────────────────────────

// ───────────────────────────────────────────────────── Product deep-dive

function BSProductDeepDive({ productId }) {
  // Resolve which product to render. URL ?id=foo overrides the prop.
  const params = typeof window !== "undefined"
    ? new URLSearchParams(window.location.search)
    : new URLSearchParams();
  const id = params.get("id") || productId || (PRODUCTS[0] && PRODUCTS[0].id);
  const product = PRODUCTS.find((p) => p.id === id) || PRODUCTS[0];
  const idx = PRODUCTS.findIndex((p) => p.id === product.id);
  const dd = product.deepDive || {};
  const labels = DEEPDIVE_DEFAULTS.sectionLabels;
  const Figure = FIGURES[product.figureKey];
  const related = PRODUCTS.filter((p) => p.id !== product.id);

  return (
    <React.Fragment>
      {/* Hero */}
      <section className="bs-dd-hero" id="top">
        <div className="bs-dd-crumbs" data-reveal>
          <a href="/#products">Products</a>
          <span>›</span>
          <span>§ {String(idx + 1).padStart(2, "0")} — {product.short}</span>
        </div>
        <p className="bs-eyebrow" data-reveal style={{ "--reveal-delay": "60ms" }}>{product.eyebrow}</p>
        <h1 className="bs-h1" data-reveal style={{ "--reveal-delay": "120ms" }}>
          {product.short}
        </h1>
        {dd.tagline && (
          <p className="bs-dd-tagline" data-reveal style={{ "--reveal-delay": "200ms" }}>{dd.tagline}</p>
        )}
        <div className="bs-dd-hero-fig" data-reveal style={{ "--reveal-delay": "280ms" }}>
          {product.featureNumber ? (
            <div className="bs-feature">
              <div className="bs-feature-num">{product.featureNumber}</div>
              <div className="bs-feature-label">
                {(product.featureLabel || "").split("\n").map((l, i, arr) => (
                  <React.Fragment key={i}>{l}{i < arr.length - 1 && <br />}</React.Fragment>
                ))}
              </div>
            </div>
          ) : (
            <div className="bs-fig-art bs-dd-hero-art">
              {Figure ? <Figure /> : null}
            </div>
          )}
        </div>
      </section>

      {/* Overview */}
      {dd.overview && (
        <BSDDSection label={labels.overview} index="01">
          <div className="bs-dd-prose">
            {dd.overview.split("\n\n").map((p, i) => <p key={i}>{p}</p>)}
          </div>
        </BSDDSection>
      )}

      {/* Principles */}
      {dd.principles && dd.principles.length > 0 && (
        <BSDDSection label={labels.principles} index="02">
          <ol className="bs-dd-principles">
            {dd.principles.map(([title, body], i) => (
              <li key={i} data-reveal style={{ "--reveal-delay": `${i * 60}ms` }}>
                <span className="bs-dd-pnum">{String(i + 1).padStart(2, "0")}</span>
                <h3 className="bs-dd-ptitle">{title}</h3>
                <p className="bs-dd-pbody">{body}</p>
              </li>
            ))}
          </ol>
        </BSDDSection>
      )}

      {/* Methodology */}
      {dd.methodology && (
        <BSDDSection label={labels.methodology} index="03">
          <div className="bs-dd-prose"><p>{dd.methodology}</p></div>
        </BSDDSection>
      )}

      {/* Examples / Excerpts */}
      {dd.examples && dd.examples.length > 0 && (
        <BSDDSection label={labels.examples} index="04">
          <div className="bs-dd-examples">
            {dd.examples.map((ex, i) => (
              <figure key={i} className="bs-dd-example" data-reveal style={{ "--reveal-delay": `${i * 80}ms` }}>
                {ex.kind === "code" ? (
                  <pre className="bs-dd-code"><code data-lang={ex.lang}>{ex.body}</code></pre>
                ) : (
                  <div className="bs-fig-art bs-dd-fig">
                    {FIGURES[ex.figure] ? React.createElement(FIGURES[ex.figure]) : null}
                  </div>
                )}
                {ex.caption && (
                  <figcaption>
                    <span className="bs-fig-label">Fig. {i + 1}</span>
                    <span>{ex.caption}</span>
                  </figcaption>
                )}
              </figure>
            ))}
          </div>
        </BSDDSection>
      )}

      {/* Facts (always rendered, sourced from product.facts) */}
      <BSDDSection label={labels.facts} index="05">
        <dl className="bs-dd-facts">
          {product.facts.map(([k, v]) => (
            <div key={k}>
              <dt>{k}</dt>
              <dd>{v}</dd>
            </div>
          ))}
        </dl>
      </BSDDSection>

      {/* Related products */}
      <BSDDSection label={labels.related} index="06">
        <ul className="bs-dd-related">
          {related.map((p) => (
            <li key={p.id}>
              <a href={`/product.html?id=${p.id}`}>
                <span className="bs-dd-related-eye">{p.eyebrow}</span>
                <span className="bs-dd-related-name">{p.short}</span>
                <span className="bs-dd-related-arrow">→</span>
              </a>
            </li>
          ))}
        </ul>
      </BSDDSection>

      {/* Footer CTA */}
      <section className="bs-dd-cta">
        <p className="bs-eyebrow" data-reveal>{DEEPDIVE_DEFAULTS.footerCta.eyebrow}</p>
        <h2 className="bs-h2 bs-dd-cta-h" data-reveal style={{ "--reveal-delay": "80ms" }}>
          {DEEPDIVE_DEFAULTS.footerCta.headline}
        </h2>
        <p className="bs-dd-cta-body" data-reveal style={{ "--reveal-delay": "160ms" }}>
          {DEEPDIVE_DEFAULTS.footerCta.body}
        </p>
        <a className="bs-cta" href={DEEPDIVE_DEFAULTS.footerCta.cta.href} data-reveal style={{ "--reveal-delay": "220ms" }}>
          <span>{DEEPDIVE_DEFAULTS.footerCta.cta.label}</span>
          <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">
            <path d="M3 8h10M9 4l4 4-4 4" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </a>
      </section>
    </React.Fragment>
  );
}

function BSDDSection({ label, index, children }) {
  return (
    <section className="bs-dd-sec">
      <header className="bs-dd-sechead" data-reveal>
        <span className="bs-secindex">§ {index}</span>
        <h2 className="bs-dd-seclabel">{label}</h2>
      </header>
      <div className="bs-dd-secbody">{children}</div>
    </section>
  );
}

// ───────────────────────────────────────────────────────── About / studio

function BSAbout() {
  return (
    <React.Fragment>
      <section className="bs-hero" id="top">
        <p className="bs-eyebrow" data-reveal>{ABOUT.eyebrow}</p>
        <h1 className="bs-h1" data-reveal style={{ "--reveal-delay": "60ms" }}>{ABOUT.headline}</h1>
        <p className="bs-lede" data-reveal style={{ "--reveal-delay": "140ms" }}>{ABOUT.lede}</p>
      </section>

      <section className="bs-about-pillars">
        <header className="bs-secthead" data-reveal>
          <span className="bs-secindex">§ approach</span>
          <h2 className="bs-h2">How we work.</h2>
        </header>
        <ol className="bs-pillars">
          {ABOUT.pillars.map((p, i) => (
            <li key={i} data-reveal style={{ "--reveal-delay": `${i * 60}ms` }}>
              <span className="bs-pillar-num">{String(i + 1).padStart(2, "0")}</span>
              <h3 className="bs-pillar-title">{p.title}</h3>
              <p className="bs-pillar-body">{p.body}</p>
            </li>
          ))}
        </ol>
      </section>

      <section className="bs-about-values">
        <header className="bs-secthead" data-reveal>
          <span className="bs-secindex">§ values</span>
          <h2 className="bs-h2">Three commitments.</h2>
        </header>
        <dl className="bs-values">
          {ABOUT.values.map(([k, v], i) => (
            <div key={i} data-reveal style={{ "--reveal-delay": `${i * 60}ms` }}>
              <dt>{k}</dt>
              <dd>{v}</dd>
            </div>
          ))}
        </dl>
      </section>

      <section className="bs-about-team">
        <header className="bs-secthead" data-reveal>
          <span className="bs-secindex">§ team</span>
          <h2 className="bs-h2">Team.</h2>
        </header>
        <p className="bs-team-note" data-reveal>{ABOUT.team.note}</p>
        <div className="bs-team-grid">
          {Array.from({ length: ABOUT.team.seats }).map((_, i) => (
            <div className="bs-team-seat" key={i} data-reveal style={{ "--reveal-delay": `${i * 80}ms` }}>
              <div className="bs-team-frame" aria-hidden="true"><span>?</span></div>
              <div className="bs-team-meta">
                <div className="bs-team-name">[redacted]</div>
                <div className="bs-team-role">Founder / engineer</div>
              </div>
            </div>
          ))}
        </div>
      </section>
    </React.Fragment>
  );
}

// ───────────────────────────────────────────────────────── Waitlist

function BSWaitlist() {
  const [submitted, setSubmitted] = React.useState(false);
  const [error, setError] = React.useState(null);
  const onSubmit = async (e) => {
    e.preventDefault();
    setError(null);
    try {
      const form = new FormData(e.currentTarget);
      await submitForm("/api/waitlist", Object.fromEntries(form.entries()));
      setSubmitted(true);
    } catch (err) {
      setError(err.message);
    }
  };

  return (
    <React.Fragment>
      <section className="bs-waitlist-hero" id="top">
        <div className="bs-waitlist-text">
          <p className="bs-eyebrow" data-reveal>{WAITLIST.eyebrow}</p>
          <h1 className="bs-h1" data-reveal style={{ "--reveal-delay": "60ms" }}>{WAITLIST.headline}</h1>
          <p className="bs-lede" data-reveal style={{ "--reveal-delay": "140ms" }}>{WAITLIST.lede}</p>
        </div>
        <div className="bs-waitlist-form-wrap" data-reveal style={{ "--reveal-delay": "220ms" }}>
          {submitted ? (
            <div className="bs-form-success bs-waitlist-success">
              You're on the list. We'll be in touch within two business days.
            </div>
          ) : (
            <form className="bs-form bs-waitlist-form" onSubmit={onSubmit}>
              <label className="bs-formfield">
                <span>Name</span>
                <input name="name" type="text" required />
              </label>
              <label className="bs-formfield">
                <span>Work email</span>
                <input name="email" type="email" required />
              </label>
              <label className="bs-formfield">
                <span>Organization</span>
                <input name="organization" type="text" required />
              </label>
              <label className="bs-formfield">
                <span>What are you shipping?</span>
                <textarea name="role" rows="4" placeholder="A protocol, an infra project, a CEX integration — a short line is enough." required />
              </label>
              {error && <p className="bs-form-error">Could not submit: {error}</p>}
              <button type="submit" className="bs-formsubmit">
                <span>{WAITLIST.formCta}</span>
                <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">
                  <path d="M3 8h10M9 4l4 4-4 4" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              </button>
            </form>
          )}
        </div>
      </section>

      <section className="bs-waitlist-benefits">
        <header className="bs-secthead" data-reveal>
          <span className="bs-secindex">§ why</span>
          <h2 className="bs-h2">What you get.</h2>
        </header>
        <ol className="bs-pillars bs-pillars--two">
          {WAITLIST.benefits.map(([k, v], i) => (
            <li key={i} data-reveal style={{ "--reveal-delay": `${i * 60}ms` }}>
              <span className="bs-pillar-num">{String(i + 1).padStart(2, "0")}</span>
              <h3 className="bs-pillar-title">{k}</h3>
              <p className="bs-pillar-body">{v}</p>
            </li>
          ))}
        </ol>
      </section>

      <section className="bs-waitlist-faq">
        <header className="bs-secthead" data-reveal>
          <span className="bs-secindex">§ FAQ</span>
          <h2 className="bs-h2">Common questions.</h2>
        </header>
        <dl className="bs-faq">
          {WAITLIST.faq.map(([q, a], i) => (
            <div key={i} data-reveal style={{ "--reveal-delay": `${i * 40}ms` }}>
              <dt>{q}</dt>
              <dd>{a}</dd>
            </div>
          ))}
        </dl>
      </section>
    </React.Fragment>
  );
}

// ───────────────────────────────────────────────────────── 404 / error

function BSErrorState({ data = ERROR404 }) {
  return (
    <section className="bs-error" id="top">
      <p className="bs-eyebrow" data-reveal>{data.eyebrow}</p>
      <div className="bs-error-code" data-reveal style={{ "--reveal-delay": "60ms" }}>
        {data.code}
      </div>
      <h1 className="bs-error-headline" data-reveal style={{ "--reveal-delay": "140ms" }}>
        {data.headline}
      </h1>
      <p className="bs-error-body" data-reveal style={{ "--reveal-delay": "220ms" }}>{data.body}</p>
      <ul className="bs-error-suggestions" data-reveal style={{ "--reveal-delay": "300ms" }}>
        {data.suggestions.map((s, i) => (
          <li key={i}>
            <a href={s.href}>
              <span>{s.label}</span>
              <svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">
                <path d="M3 8h10M9 4l4 4-4 4" fill="none" stroke="currentColor" strokeWidth="1.25" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </a>
          </li>
        ))}
      </ul>
    </section>
  );
}

// ───────────────────────────────────────────────────────── Disclosure

function BSDisclose() {
  const [submitted, setSubmitted] = React.useState(false);
  const [error, setError] = React.useState(null);
  const onSubmit = async (e) => {
    e.preventDefault();
    setError(null);
    try {
      const form = new FormData(e.currentTarget);
      form.set("_hp", form.get("_hp") || "");
      form.set("form_token", window.__bs_form_token);
      form.set("fingerprint", await window.__bs_fingerprint);
      form.set("hcaptcha_token", window.hcaptcha?.getResponse?.() ?? "");
      await submitForm("/api/disclose", form, { multipart: true });
      setSubmitted(true);
    } catch (err) {
      setError(err.message);
    }
  };

  return (
    <React.Fragment>
      <section className="bs-hero" id="top">
        <p className="bs-eyebrow" data-reveal>{DISCLOSE.eyebrow}</p>
        <h1 className="bs-h1" data-reveal style={{ "--reveal-delay": "60ms" }}>{DISCLOSE.headline}</h1>
        <p className="bs-lede" data-reveal style={{ "--reveal-delay": "140ms" }}>{DISCLOSE.lede}</p>
      </section>

      <section className="bs-disclose-form-sec">
        <header className="bs-secthead" data-reveal>
          <span className="bs-secindex">§ submit</span>
          <h2 className="bs-h2">Submission.</h2>
        </header>
        {submitted ? (
          <div className="bs-form-success">
            Submission received. We'll acknowledge by email within one business day.
          </div>
        ) : (
          <form className="bs-form bs-disclose-form" onSubmit={onSubmit}>
            {DISCLOSE.fields.map((f) => (
              <label key={f.name} className={`bs-formfield ${f.type === "textarea" ? "bs-formfield-wide" : ""}`}>
                <span>{f.label}{f.required && " *"}</span>
                {f.type === "textarea" ? (
                  <textarea name={f.name} rows="8" placeholder={f.placeholder} required={f.required} />
                ) : f.type === "select" ? (
                  <select name={f.name} required={f.required} defaultValue="">
                    <option value="" disabled>Select…</option>
                    {f.options.map((o) => <option key={o}>{o}</option>)}
                  </select>
                ) : (
                  <input name={f.name} type={f.type} placeholder={f.placeholder} required={f.required} />
                )}
              </label>
            ))}
            <div className="bs-formactions">
              {error && <p className="bs-form-error">Could not submit: {error}</p>}
              <button type="submit" className="bs-formsubmit">
                <span>Submit disclosure</span>
                <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">
                  <path d="M3 8h10M9 4l4 4-4 4" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              </button>
              <span className="bs-formalt">PGP key available on request.</span>
            </div>
          </form>
        )}
      </section>

      <section className="bs-disclose-policy">
        <header className="bs-secthead" data-reveal>
          <span className="bs-secindex">§ policy</span>
          <h2 className="bs-h2">What happens next.</h2>
        </header>
        <ol className="bs-steps bs-steps-block">
          {DISCLOSE.policyPoints.map(([k, v], i) => (
            <li key={i} data-reveal style={{ "--reveal-delay": `${i * 60}ms` }}>
              <span className="bs-step-num">{k}</span>
              <span className="bs-step-body">{v}</span>
            </li>
          ))}
        </ol>
      </section>

      <section className="bs-safe-harbor">
        <header className="bs-secthead" data-reveal>
          <span className="bs-secindex">§ safe harbor</span>
          <h2 className="bs-h2">Safe-harbor commitment.</h2>
        </header>
        <p className="bs-safe-harbor-body" data-reveal>{DISCLOSE.safeHarbor}</p>
      </section>
    </React.Fragment>
  );
}

// ───────────────────────────────────────────────────────── Case studies

function BSCases() {
  const hasCases = CASES.entries && CASES.entries.length > 0;
  return (
    <React.Fragment>
      <section className="bs-hero" id="top">
        <p className="bs-eyebrow" data-reveal>{CASES.eyebrow}</p>
        <h1 className="bs-h1" data-reveal style={{ "--reveal-delay": "60ms" }}>{CASES.headline}</h1>
        <p className="bs-lede" data-reveal style={{ "--reveal-delay": "140ms" }}>{CASES.lede}</p>
      </section>

      {hasCases ? (
        <section className="bs-cases-list">
          <header className="bs-secthead" data-reveal>
            <span className="bs-secindex">§ published</span>
            <h2 className="bs-h2">Published engagements.</h2>
          </header>
          <ol className="bs-cases">
            {CASES.entries.map((c) => (
              <li key={c.id} data-reveal>
                <article>
                  <div className="bs-case-meta">
                    <span className="bs-case-ref">{c.ref}</span>
                    <span className="bs-case-year">{c.year}</span>
                    <span className={`bs-status-pill bs-status--${c.status}`}>{c.status}</span>
                  </div>
                  <h3 className="bs-case-title">{c.title}</h3>
                  <p className="bs-case-summary">{c.summary}</p>
                  <div className="bs-case-fine">{c.domain} · severity {c.severity} · partner: {c.partner}</div>
                </article>
              </li>
            ))}
          </ol>
        </section>
      ) : (
        <section className="bs-cases-empty">
          <div className="bs-cases-empty-card" data-reveal>
            <div className="bs-cases-empty-mark" aria-hidden="true">¶</div>
            <h2 className="bs-h2">{CASES.emptyState.title}</h2>
            <p>{CASES.emptyState.body}</p>
            <a className="bs-cta" href={CASES.emptyState.cta.href}>
              <span>{CASES.emptyState.cta.label}</span>
              <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">
                <path d="M3 8h10M9 4l4 4-4 4" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </a>
          </div>
        </section>
      )}
    </React.Fragment>
  );
}

// ───────────────────────────────────────────────────────── Legal

function BSLegalDoc({ doc }) {
  return (
    <React.Fragment>
      <section className="bs-legal-hero" id="top">
        <p className="bs-eyebrow" data-reveal>Legal</p>
        <h1 className="bs-h1 bs-h1-tight" data-reveal style={{ "--reveal-delay": "60ms" }}>{doc.title}</h1>
        <p className="bs-legal-updated" data-reveal style={{ "--reveal-delay": "140ms" }}>{doc.updated}</p>
        <p className="bs-lede" data-reveal style={{ "--reveal-delay": "220ms" }}>{doc.summary}</p>
      </section>

      <section className="bs-legal-body">
        <aside className="bs-legal-toc">
          <div className="bs-secindex" style={{ marginBottom: "14px" }}>§ contents</div>
          <ol>
            {doc.sections.map(([k], i) => (
              <li key={i}>
                <a href={`#sec-${i + 1}`}>
                  <span className="bs-legal-num">{String(i + 1).padStart(2, "0")}</span>
                  <span>{k}</span>
                </a>
              </li>
            ))}
          </ol>
        </aside>
        <div className="bs-legal-text">
          {doc.sections.map(([k, body], i) => (
            <section key={i} id={`sec-${i + 1}`} className="bs-legal-sec" data-reveal>
              <span className="bs-legal-secnum">{String(i + 1).padStart(2, "0")}</span>
              <h2 className="bs-legal-h">{k}</h2>
              <p>{body}</p>
            </section>
          ))}
        </div>
      </section>
    </React.Fragment>
  );
}

Object.assign(window, {
  BSProductDeepDive, BSDDSection,
  BSAbout, BSWaitlist, BSErrorState, BSDisclose, BSCases, BSLegalDoc,
});
