// pages-misc.jsx — About, Resources, Contact
const { useState: useStateMx } = React;

/* ═══════════════════════════════════════════════════════════════════════
   ABOUT
   ═══════════════════════════════════════════════════════════════════════ */

function PageAbout({ setRoute }) {
  return (
    <main id="main" className="page-enter">
      <section style={{ paddingTop: 80, paddingBottom: 48 }}>
        <div className="wrap-wide">
          <div className="eyebrow">06 / Company</div>
          <h1 className="h-display" style={{ marginTop: 16, maxWidth: 22 + "ch" }}>
            We built the product we wished we had <em>running large Salesforce programs.</em>
          </h1>
        </div>
      </section>

      <section style={{ paddingBottom: 80 }}>
        <div className="wrap-wide">
          <div className="grid grid-2" style={{ gap: 64 }}>
            <div>
              <h2 className="h2" style={{ marginBottom: 20 }}>The premise</h2>
              <p className="body" style={{ color: "var(--text-secondary)" }}>
                CrestIron started inside a Salesforce CoE supporting a federal civilian
                agency. The same pattern repeated in every Fortune 500 platform we
                worked with afterward — financial services, healthcare, energy: a decade
                of well-intentioned automation, hundreds of permission sets, and a
                release process held together by spreadsheets. The CAB meeting was the
                place where surprises happened.
              </p>
              <p className="body" style={{ marginTop: 16, color: "var(--text-secondary)" }}>
                There was no shortage of static analyzers, deployment tools, or
                governance frameworks. There was a shortage of products that turned the
                output of all of them into something a CIO could read on Friday and a
                release manager could act on Monday.
              </p>
              <p className="body" style={{ marginTop: 16, color: "var(--text-secondary)" }}>
                CrestIron is what we built instead of writing another internal toolkit.
              </p>
            </div>

            <div>
              <h2 className="h2" style={{ marginBottom: 20 }}>How we work</h2>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 20 }}>
                <PrincipleRow num="01" title="Prioritization over detection."
                  body="The market does not need another tool that finds 173 things. It needs one that tells you which nine to fix this sprint and why." />
                <PrincipleRow num="02" title="Explainability over magic."
                  body="Every score, every verdict, every priority can be traced to the rules and signals that produced it. No black boxes." />
                <PrincipleRow num="03" title="Auditable by default."
                  body="If we wouldn't be comfortable handing the audit trail to an OIG investigator, the feature isn't shipped." />
                <PrincipleRow num="04" title="Accessibility, not a checkbox."
                  body="Section 508 and WCAG 2.2 AA are not toggles. They are how every screen is built and reviewed — whether your buyer is a federal agency or a regulated commercial CoE." />
              </ul>
            </div>
          </div>
        </div>
      </section>

      <section className="section">
        <div className="wrap-wide">
          <div className="eyebrow">// Leadership</div>
          <h2 className="h1" style={{ marginTop: 12, marginBottom: 40 }}>People behind the platform</h2>

          <div className="grid grid-3" style={{ gap: 24 }}>
            <TeamCard
              initials="M·R"
              name="Mara Rendell"
              role="Co-founder & CEO"
              bio="Former Salesforce CoE Director for a US federal civilian agency. Twelve years building governed delivery programs across multiple cabinet-level departments."
            />
            <TeamCard
              initials="K·O"
              name="Kavi Okonkwo"
              role="Co-founder & CTO"
              bio="Engineering lead on Apex/metadata tooling at two public-sector Salesforce SIs. Three-time Salesforce Architect of the Year (regional)."
            />
            <TeamCard
              initials="J·H"
              name="Jordan Halverson"
              role="Head of Governance"
              bio="Former QA Director on a $400M federal Salesforce program. CAC/PIV-cleared. Wrote the policy packs CrestIron ships with."
            />
            <TeamCard
              initials="P·V"
              name="Priya Venkatesh"
              role="Head of Federal"
              bio="Twenty years in federal cloud go-to-market. Led FedRAMP and StateRAMP authorizations for two SaaS platforms."
            />
            <TeamCard
              initials="L·B"
              name="Liam Brennan"
              role="Head of Design"
              bio="Built accessible design systems for healthcare.gov, USAJobs.gov, and a federal benefits platform. Reduced-motion before reduced-motion was cool."
            />
            <TeamCard
              initials="S·F"
              name="Sofia Friedman"
              role="Head of Customer Engineering"
              bio="Eight years in Salesforce Solution Architecture across federal civilian and defense. Wrote OrgLens AI's Agentforce-readiness rule library."
            />
          </div>
        </div>
      </section>

      <section className="section">
        <div className="wrap-wide">
          <div className="grid grid-2" style={{ gap: 64, alignItems: "center" }}>
            <div>
              <div className="eyebrow">// Trust</div>
              <h2 className="h2" style={{ marginTop: 12 }}>Compliance posture</h2>
              <p className="body" style={{ marginTop: 16 }}>
                CrestIron is built for the most demanding Salesforce environments —
                regulated commercial CoEs and federal-ready deployments alike. Both
                applications were designed with SOC 2 and FedRAMP High control mappings
                in mind — not as certifications we claim today, but as the framework the
                product was architected against from day one. Data residency is US-only,
                and a GovCloud-resident tenant is available for defense and intel programs.
              </p>
            </div>
            <div className="card" style={{ padding: 28 }}>
              <ComplianceRow k="Salesforce Native" v="Managed package · runs inside your org" />
              <ComplianceRow k="Zero data egress" v="No PII or PHI ever leaves your org" />
              <ComplianceRow k="Section 508 / WCAG 2.2 AA" v="Conformant · VPAT available on request" />
              <ComplianceRow k="SOC 2" v="Designed against control mapping" />
              <ComplianceRow k="FedRAMP High" v="Designed against control mapping" />
              <ComplianceRow k="ISO 27001" v="Roadmap · 2026" />
              <ComplianceRow k="CMMC Level 2" v="Roadmap · 2026" last />
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

function PrincipleRow({ num, title, body }) {
  return (
    <li style={{ display: "grid", gridTemplateColumns: "44px 1fr", gap: 16 }}>
      <span className="mono-sm" style={{ color: "var(--accent)", letterSpacing: "0.08em" }}>{num}</span>
      <div>
        <div style={{ fontSize: 15, fontWeight: 500, color: "var(--text-primary)" }}>{title}</div>
        <div className="body-sm" style={{ marginTop: 4 }}>{body}</div>
      </div>
    </li>
  );
}

function TeamCard({ initials, name, role, bio }) {
  return (
    <div className="card" style={{ padding: 24 }}>
      <div style={{
        width: 56, height: 56, borderRadius: 8,
        background: "var(--surface-2)",
        border: "1px solid var(--border)",
        display: "flex", alignItems: "center", justifyContent: "center",
        fontFamily: "var(--font-mono)", fontSize: 14, letterSpacing: "0.08em",
        color: "var(--text-secondary)", marginBottom: 20,
      }}>{initials}</div>
      <div className="h4" style={{ marginBottom: 4 }}>{name}</div>
      <div className="mono-sm" style={{ color: "var(--accent)", letterSpacing: "0.04em", marginBottom: 12 }}>{role}</div>
      <p className="body-sm" style={{ margin: 0 }}>{bio}</p>
    </div>
  );
}

function ComplianceRow({ k, v, last }) {
  return (
    <div style={{
      display: "grid", gridTemplateColumns: "1fr auto",
      padding: "14px 0",
      borderBottom: last ? "none" : "1px solid var(--border-subtle)",
      gap: 16, alignItems: "baseline",
    }}>
      <span style={{ fontSize: 14, color: "var(--text-primary)" }}>{k}</span>
      <span className="mono-sm" style={{ color: "var(--text-secondary)" }}>{v}</span>
    </div>
  );
}

/* ═══════════════════════════════════════════════════════════════════════
   RESOURCES
   ═══════════════════════════════════════════════════════════════════════ */

function PageResources({ setRoute }) {
  return (
    <main id="main" className="page-enter">
      <section style={{ paddingTop: 80, paddingBottom: 48 }}>
        <div className="wrap-wide">
          <div className="eyebrow">07 / Resources</div>
          <h1 className="h-display" style={{ marginTop: 16, maxWidth: 22 + "ch" }}>
            Read before you scan. <em>Cite after you ship.</em>
          </h1>
          <p className="lead" style={{ marginTop: 24 }}>
            Documentation, policy pack references, and writing from our team on
            governed Salesforce delivery in the public sector.
          </p>
        </div>
      </section>

      <section style={{ paddingBottom: 64 }}>
        <div className="wrap-wide">
          <div className="grid grid-3" style={{ gap: 24, marginBottom: 48 }}>
            <ResourceCard
              tag="DOCS"
              title="OrgLens AI scoring model"
              meta="Reference · 18 min read"
              body="The full priority formula: severity × blast radius × usage weight × business sensitivity × confidence, minus fix complexity penalty. Every input documented."
            />
            <ResourceCard
              tag="DOCS"
              title="Authoring a ReleaseGuard policy pack"
              meta="Guide · 24 min read"
              body="From a blank YAML file to a CoE-grade policy. Required artifacts, waiver routing, AI-disclosure rules, and blackout windows."
            />
            <ResourceCard
              tag="DOCS"
              title="Section 508 review patterns"
              meta="Reference · 11 min read"
              body="The five accessibility checks every regulated Salesforce release should include — and how to make them artifact-producing."
            />
          </div>

          <div className="row between" style={{ marginBottom: 24 }}>
            <h2 className="h2">From the field</h2>
            <button className="btn btn-ghost btn-sm">All articles <IconArrow /></button>
          </div>

          <div className="grid grid-2" style={{ gap: 16 }}>
            <ArticleRow
              date="2026-04"
              title="Agentforce readiness is a metadata-quality problem"
              author="Sofia Friedman"
              snippet="The fastest path to trustworthy agents is not bigger models — it is field descriptions, picklist consistency, and a permission model an auditor can read out loud."
            />
            <ArticleRow
              date="2026-04"
              title="Your CAB is a queue, not a control"
              author="Jordan Halverson"
              snippet="What changes when governance moves from a Thursday meeting to a policy pack that runs at intake. Notes from three CoE program lines."
            />
            <ArticleRow
              date="2026-03"
              title="Notes from a Salesforce ATO"
              author="Priya Venkatesh"
              snippet="Eleven months, four artifacts that mattered most, and the three questions every regulated Salesforce buyer should ask their vendor before signing."
            />
            <ArticleRow
              date="2026-02"
              title="How we score automation conflict on Opportunity-analog objects"
              author="Kavi Okonkwo"
              snippet="A walkthrough of the heuristic that surfaces overlapping flow + trigger + workflow rule + process builder stacks — and why we weight Opportunity higher than Lead."
            />
            <ArticleRow
              date="2026-01"
              title="What we mean by 'explainable verdict'"
              author="Mara Rendell"
              snippet="A blocked release is only useful if the reasoning is reviewable. A taxonomy of explanations we owe every approver."
            />
            <ArticleRow
              date="2025-12"
              title="The Section 508 patterns we keep finding in Salesforce orgs"
              author="Liam Brennan"
              snippet="Five recurring accessibility gaps in custom Lightning components, the rules that catch them, and the artifacts that close them at release."
            />
          </div>
        </div>
      </section>

      <section style={{ paddingBottom: 96 }}>
        <div className="wrap-wide">
          <div className="card" style={{ padding: 40 }}>
            <div className="row between" style={{ flexWrap: "wrap", gap: 24 }}>
              <div>
                <div className="eyebrow">// Security</div>
                <h3 className="h2" style={{ marginTop: 12, marginBottom: 12 }}>Security & vulnerability disclosure</h3>
                <p className="body-sm" style={{ maxWidth: 56 + "ch" }}>
                  Report a vulnerability or request our SOC 2 / FedRAMP control-mapping
                  documentation and VPAT. Regulated and federal customers can also request
                  our continuous-monitoring package and POA&M template.
                </p>
              </div>
              <div className="col gap-8" style={{ minWidth: 220 }}>
                <button className="btn btn-secondary" onClick={() => setRoute("contact")}>Request reports</button>
                <span className="mono-sm muted" style={{ textAlign: "right" }}>security@crestiron.ai</span>
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

function ResourceCard({ tag, title, meta, body }) {
  return (
    <div className="card card-hover" style={{ padding: 24, cursor: "default" }}>
      <div className="row between" style={{ marginBottom: 20 }}>
        <span className="pill">{tag}</span>
        <span className="mono-sm muted">{meta}</span>
      </div>
      <h3 className="h3" style={{ marginBottom: 10 }}>{title}</h3>
      <p className="body-sm" style={{ margin: 0 }}>{body}</p>
      <div className="mono-sm" style={{ marginTop: 20, color: "var(--accent)", display: "inline-flex", alignItems: "center", gap: 6 }}>
        Read <IconArrow s={12} />
      </div>
    </div>
  );
}

function ArticleRow({ date, title, author, snippet }) {
  return (
    <article style={{
      padding: 24,
      borderTop: "1px solid var(--border-subtle)",
      display: "grid",
      gridTemplateColumns: "80px 1fr",
      gap: 24,
    }}>
      <div className="mono-sm muted" style={{ letterSpacing: "0.06em" }}>{date}</div>
      <div>
        <h4 className="h4" style={{ marginBottom: 8 }}>{title}</h4>
        <div className="mono-sm muted" style={{ marginBottom: 12 }}>By {author}</div>
        <p className="body-sm" style={{ margin: 0 }}>{snippet}</p>
      </div>
    </article>
  );
}

/* ═══════════════════════════════════════════════════════════════════════
   CONTACT
   ═══════════════════════════════════════════════════════════════════════ */

function PageContact() {
  const [form, setForm] = useStateMx({
    name: "", email: "", agency: "", role: "", interest: "both",
    orgs: "1-3", message: "",
  });
  const [submitted, setSubmitted] = useStateMx(false);
  const [sending, setSending] = useStateMx(false);
  const [errors, setErrors] = useStateMx({});
  const [serverError, setServerError] = useStateMx("");

  const update = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const validate = () => {
    const errs = {};
    if (!form.name.trim()) errs.name = "Required";
    if (!form.email.trim()) errs.email = "Required";
    else if (!/^[^@]+@[^@]+\.[^@]+$/.test(form.email)) errs.email = "Enter a valid email";
    if (!form.agency.trim()) errs.agency = "Required";
    return errs;
  };

  const submit = async (e) => {
    e.preventDefault();
    const errs = validate();
    setErrors(errs);
    if (Object.keys(errs).length > 0) return;

    setSending(true);
    setServerError("");
    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      if (!res.ok) {
        const payload = await res.json().catch(() => ({}));
        throw new Error(payload.error || `Server error ${res.status}`);
      }
      setSubmitted(true);
    } catch (err) {
      setServerError(err.message || "Something went wrong — please try again.");
    } finally {
      setSending(false);
    }
  };

  return (
    <main id="main" className="page-enter">
      <section className="contact-section" style={{ paddingTop: 80, paddingBottom: 96 }}>
        <div className="wrap-wide">
          <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1.2fr)", gap: 64 }}
               className="contact-grid">
            <div>
              <div className="eyebrow">08 / Contact</div>
              <h1 className="h-display" style={{ marginTop: 16, maxWidth: 18 + "ch" }}>
                Tell us about the org.
              </h1>
              <p className="lead" style={{ marginTop: 24 }}>
                Sales briefings run 30 minutes. We will not ask for credentials or pull
                from production. Expect a response within one business day.
              </p>

              <div className="contact-info-stack" style={{ marginTop: 40, display: "flex", flexDirection: "column", gap: 24 }}>
                <ContactBlock k="Enterprise sales" v="sales@crestiron.ai" />
                <ContactBlock k="Federal sales" v="federal@crestiron.ai" />
                <ContactBlock k="Partner program" v="partners@crestiron.ai" />
                <ContactBlock k="Security disclosure" v="security@crestiron.ai" />
                <ContactBlock k="General" v="hello@crestiron.ai" />
              </div>

              <div className="contact-accessibility" style={{ marginTop: 40, padding: 20, background: "var(--bg-elevated)", border: "1px solid var(--border-subtle)", borderRadius: "var(--r-2)" }}>
                <div className="mono-sm" style={{ color: "var(--accent)", letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 8 }}>
                  On accessibility
                </div>
                <p className="body-sm" style={{ margin: 0 }}>
                  This form is Section 508 / WCAG 2.2 AA conformant. If you encounter a
                  barrier, email <span style={{ color: "var(--text-primary)" }}>accessibility@crestiron.ai</span> and we will
                  respond within one business day with an alternate channel.
                </p>
              </div>
            </div>

            <div className="card contact-card" style={{ padding: 36 }}>
              {submitted ? (
                <div className="contact-success" style={{ minHeight: 480, display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "flex-start" }}>
                  <div style={{
                    width: 56, height: 56, borderRadius: 12,
                    background: "var(--ok-dim)", border: "1px solid rgba(95,176,134,0.35)",
                    display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ok)",
                    marginBottom: 24,
                  }}>
                    <IconCheck s={24} />
                  </div>
                  <h2 className="h2" style={{ marginBottom: 12 }}>Briefing requested.</h2>
                  <p className="body" style={{ margin: 0 }}>
                    We'll be in touch at <span style={{ color: "var(--text-primary)" }}>{form.email}</span> within one business day with three time options.
                  </p>
                  <div className="mono-sm muted" style={{ marginTop: 24 }}>
                    Reference · CR-{Math.floor(Math.random() * 90000 + 10000)}-FED
                  </div>
                </div>
              ) : (
                <form onSubmit={submit} noValidate>
                  <h2 className="h3" style={{ marginBottom: 24 }}>Request a briefing</h2>
                  <div className="contact-form-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
                    <FormField label="Name" required value={form.name} onChange={update("name")} error={errors.name} />
                    <FormField label="Government / work email" type="email" required value={form.email} onChange={update("email")} error={errors.email} />
                    <FormField label="Agency / organization" required value={form.agency} onChange={update("agency")} error={errors.agency} colSpan={2} />
                    <FormField label="Your role" value={form.role} onChange={update("role")} placeholder="e.g. Release Manager · CoE Director · Platform Owner" colSpan={2} />
                    <FormSelect label="Interested in" value={form.interest} onChange={update("interest")}
                                options={[
                                  ["both", "Both products"],
                                  ["orglens", "OrgLens AI only"],
                                  ["releaseguard", "ReleaseGuard AI only"],
                                  ["partner", "Partner program"],
                                ]} />
                    <FormSelect label="Connected orgs" value={form.orgs} onChange={update("orgs")}
                                options={[
                                  ["1-3", "1–3 orgs"],
                                  ["4-10", "4–10 orgs"],
                                  ["10+", "10+ orgs"],
                                  ["si", "Multi-client (SI)"],
                                ]} />
                    <FormField label="Anything we should know" textarea value={form.message} onChange={update("message")} colSpan={2}
                               placeholder="Audit deadlines, compliance constraints, current toolchain — whatever helps us prepare." />
                  </div>

                  {serverError && (
                    <div className="mono-sm" style={{ marginTop: 16, color: "var(--risk)" }}>
                      {serverError}
                    </div>
                  )}
                  <div className="row between contact-submit-row" style={{ marginTop: 28, flexWrap: "wrap", gap: 12 }}>
                    <span className="mono-sm muted">We do not share contact info with third parties.</span>
                    <button type="submit" className="btn btn-primary btn-lg" disabled={sending}
                            style={{ opacity: sending ? 0.65 : 1 }}>
                      {sending ? "Sending…" : <><span>Request briefing</span> <IconArrow /></>}
                    </button>
                  </div>
                </form>
              )}
            </div>
          </div>
        </div>
      </section>

      <style>{`
        @media (max-width: 900px) {
          .contact-section { padding-top: 56px !important; padding-bottom: 72px !important; }
          .contact-grid { grid-template-columns: 1fr !important; gap: 40px !important; }
          .contact-info-stack { margin-top: 32px !important; gap: 18px !important; }
          .contact-accessibility { margin-top: 32px !important; }
          .contact-success { min-height: 360px !important; }
        }

        @media (max-width: 640px) {
          .contact-section { padding-top: 40px !important; padding-bottom: 56px !important; }
          .contact-grid { gap: 28px !important; }
          .contact-card { padding: 22px !important; border-radius: var(--r-2) !important; }
          .contact-form-grid { grid-template-columns: 1fr !important; gap: 16px !important; }
          .contact-form-grid .field { grid-column: 1 / -1 !important; }
          .contact-submit-row { align-items: stretch !important; }
          .contact-submit-row > * { width: 100%; }
          .contact-success { min-height: 300px !important; }
        }

        @media (max-width: 420px) {
          .contact-card { padding: 18px !important; }
          .contact-accessibility { padding: 16px !important; }
        }
      `}</style>
    </main>
  );
}

function ContactBlock({ k, v }) {
  return (
    <div className="contact-block">
      <div className="mono-sm muted" style={{ letterSpacing: "0.08em", textTransform: "uppercase" }}>{k}</div>
      <div style={{ fontSize: 16, color: "var(--text-primary)", marginTop: 4, overflowWrap: "anywhere" }}>{v}</div>
    </div>
  );
}

function FormField({ label, value, onChange, type = "text", textarea, required, error, placeholder, colSpan = 1 }) {
  const id = `f-${label.replace(/\W+/g, "-").toLowerCase()}`;
  return (
    <div className="field" style={{ gridColumn: `span ${colSpan}` }}>
      <label htmlFor={id}>
        {label} {required && <span style={{ color: "var(--accent)" }}>*</span>}
      </label>
      {textarea ? (
        <textarea id={id} value={value} onChange={onChange} placeholder={placeholder}
                  aria-invalid={!!error} aria-describedby={error ? `${id}-err` : undefined} />
      ) : (
        <input id={id} type={type} value={value} onChange={onChange} placeholder={placeholder}
               aria-invalid={!!error} aria-describedby={error ? `${id}-err` : undefined} required={required} />
      )}
      {error && <span id={`${id}-err`} className="mono-sm" style={{ color: "var(--risk)" }}>{error}</span>}
    </div>
  );
}

function FormSelect({ label, value, onChange, options }) {
  const id = `f-${label.replace(/\W+/g, "-").toLowerCase()}`;
  return (
    <div className="field">
      <label htmlFor={id}>{label}</label>
      <select id={id} value={value} onChange={onChange}>
        {options.map(([val, lbl]) => <option key={val} value={val}>{lbl}</option>)}
      </select>
    </div>
  );
}

Object.assign(window, { PageAbout, PageResources, PageContact });
