// altriks-sections.jsx — landing sections below the hero.

/* ---------- compact line-icon set ---------- */
function Icon({ name }) {
  const p = { fill: "none", stroke: "currentColor", strokeWidth: 1.7, strokeLinecap: "round", strokeLinejoin: "round" };
  const paths = {
    inbox: <g {...p}><path d="M3 13l3 0 1.5 2.5h5L14 13h3"/><path d="M3 13l2.5-7h9L17 13v4a1 1 0 01-1 1H4a1 1 0 01-1-1z"/></g>,
    scan: <g {...p}><path d="M5 4h3M5 4v3M15 4h-3M15 4v3M5 16h3M5 16v-3M15 16h-3M15 16v-3"/><path d="M3 10h14"/></g>,
    match: <g {...p}><circle cx="7" cy="10" r="3.4"/><circle cx="13" cy="10" r="3.4"/></g>,
    send: <g {...p}><path d="M17 3L9 11"/><path d="M17 3l-5 14-3-6-6-3 14-5z"/></g>,
    doc: <g {...p}><path d="M6 3h6l4 4v10a1 1 0 01-1 1H6a1 1 0 01-1-1V4a1 1 0 011-1z"/><path d="M12 3v4h4M8 12h6M8 15h4"/></g>,
    link: <g {...p}><path d="M8 12a3 3 0 003 3h1.5a3.5 3.5 0 000-7H11M12 8a3 3 0 00-3-3H7.5a3.5 3.5 0 000 7H9"/></g>,
    filter: <g {...p}><path d="M3 5h14l-5.5 6.5V16l-3 1.5v-6L3 5z"/></g>,
    plug: <g {...p}><path d="M7 3v4M13 3v4M5 7h10v3a5 5 0 01-10 0V7zM10 15v3"/></g>,
    log: <g {...p}><path d="M5 4h10v12H5zM8 8h4M8 11h4M8 14h2"/><circle cx="6.5" cy="8" r=".2"/></g>,
    layers: <g {...p}><path d="M10 3l7 4-7 4-7-4 7-4zM3 11l7 4 7-4M3 14l7 4 7-4"/></g>,
    lock: <g {...p}><rect x="4" y="9" width="12" height="8" rx="1.5"/><path d="M7 9V6a3 3 0 016 0v3"/></g>,
    shield: <g {...p}><path d="M10 3l6 2v5c0 4-2.7 6.3-6 7-3.3-.7-6-3-6-7V5l6-2z"/><path d="M7.5 10l1.8 1.8L13 8"/></g>,
    key: <g {...p}><circle cx="7" cy="13" r="3"/><path d="M9 11l7-7M14 6l2 2M12 8l1.5 1.5"/></g>,
  };
  return <svg width="22" height="22" viewBox="0 0 20 20" aria-hidden="true">{paths[name] || null}</svg>;
}

/* ---------- Proof bar ---------- */
function ProofStrip({ showMetrics = true }) {
  if (!showMetrics) return null;
  return (
    <section className="alt-proof">
      <div className="alt-proof__metrics">
        {PROOF.map((s, i) => (
          <Reveal as="div" className="alt-proofstat" delay={i * 70} key={s.label}>
            <div className="alt-proofstat__value"><CountUp text={s.value} /></div>
            <div className="alt-proofstat__label">{s.label}</div>
          </Reveal>
        ))}
      </div>
      <p className="alt-proof__src">Based on Altriks internal benchmark runs on representative POs. Production results will vary.</p>
    </section>
  );
}

/* ---------- The problem (dark band) ---------- */
function Problem() {
  return (
    <section className="alt-problem">
      <div className="alt-problem__inner">
        <Reveal as="h2" className="alt-h2 alt-problem__title">Order entry is still a copy-paste job.</Reveal>
        <Reveal className="alt-problem__body" delay={80}>
          <p>
            POs land as PDFs and email attachments. Someone opens each one, reads it, and re-types it into
            the ERP — line by line. It's slow. It doesn't scale. And it breaks in the worst way: a
            fat-fingered quantity becomes a misship, a backlog becomes a late order, a new account becomes overtime.
          </p>
          <p className="alt-problem__kicker">
            There's nothing intelligent about manual order entry. <span>So we took the typing out of it — entirely.</span>
          </p>
        </Reveal>
      </div>
    </section>
  );
}

/* ---------- How it works (animated pipeline echo) ---------- */
function HowItWorks() {
  const icons = ["inbox", "scan", "match", "send"];
  const ref = React.useRef(null);
  const [inView, setInView] = React.useState(false);
  const [lit, setLit] = React.useState(0);

  React.useEffect(() => {
    if (__prefersReduce || typeof IntersectionObserver === "undefined") { setInView(true); setLit(4); return; }
    const el = ref.current;
    if (!el) return;
    const timers = [];
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {
        io.unobserve(el);
        setInView(true);
        [0, 1, 2, 3].forEach((i) => timers.push(setTimeout(() => setLit(i + 1), 350 + i * 450)));
      }
    }, { threshold: 0.3 });
    io.observe(el);
    return () => { io.disconnect(); timers.forEach(clearTimeout); };
  }, []);

  return (
    <section className={`alt-how ${inView ? "is-in" : ""}`} id="how-it-works" ref={ref}>
      <div className="alt-how__head">
        <div className="alt-eyebrow alt-eyebrow--sm">How it works</div>
        <h2 className="alt-h2 alt-h2--center">From inbox to ERP — without the keystrokes.</h2>
        <p className="alt-how__dek">Watch one purchase order travel the whole pipeline.</p>
      </div>
      <div className="alt-how__steps">
        <svg className="alt-how__line" viewBox="0 0 1000 2" preserveAspectRatio="none" aria-hidden="true">
          <path d="M0 1 H1000" pathLength="1000" />
        </svg>
        {STEPS.map((s, i) => (
          <Reveal as="div" className="alt-step" delay={i * 90} key={s.n}>
            <div className="alt-step__top">
              <span className={`alt-step__icon ${i < lit ? "is-lit" : ""}`}><Icon name={icons[i]} /></span>
              <span className="alt-step__num">{s.n}</span>
            </div>
            <h3 className="alt-step__title">{s.k}</h3>
            <p className="alt-step__body">{s.d}</p>
            <div className={`alt-step__state ${i < lit ? "is-on" : ""}`}>{s.state}</div>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

/* ---------- Features grid ---------- */
function Features() {
  const icons = ["doc", "match", "filter", "plug", "log", "layers"];
  return (
    <section className="alt-features" id="features">
      <div className="alt-how__head">
        <div className="alt-eyebrow alt-eyebrow--sm">Features</div>
        <h2 className="alt-h2 alt-h2--center">Everything order entry needs. Nothing it doesn't.</h2>
      </div>
      <div className="alt-features__grid">
        {FEATURES.map((f, i) => (
          <Reveal as="div" className="alt-fcard" delay={i * 70} key={f.k}>
            <span className="alt-fcard__icon"><Icon name={icons[i]} /></span>
            <h3 className="alt-fcard__title">{f.k}</h3>
            <p className="alt-fcard__body">{f.d}</p>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

/* ---------- Integrations (animated marquee) ---------- */
function Integrations() {
  return (
    <section className="alt-erp" id="integrations">
      <div className="alt-eyebrow alt-eyebrow--sm">Integrations</div>
      <h2 className="alt-h2 alt-h2--center">Connects to any ERP — your tools or ours.</h2>
      <div className="alt-erp__flow">
        <span className="alt-erp__io"><em>In</em> Email · PDF · API</span>
        <span className="alt-erp__arrow" aria-hidden="true"><Arrow /></span>
        <span className="sr-only"> produces </span>
        <span className="alt-erp__io"><em>Out</em> REST API · webhooks · file</span>
      </div>
      <p className="alt-erp__lead">Altriks is open by design. Build directly on our REST API and webhooks, plug in your own iPaaS or middleware, or let our team build the integration with you — whatever fits how you work. No proprietary connector to license, no black box to maintain.</p>
      <div className="alt-mq" aria-hidden="true">
        <div className="alt-mq__track">
          {[...INTEGRATIONS, ...INTEGRATIONS].map((n, i) => (
            <span className="alt-mq__logo" key={i}>{n}</span>
          ))}
        </div>
      </div>
      <p className="alt-erp__list">If your ERP speaks API or accepts a file, Altriks integrates with it.</p>
      <p className="alt-erp__note">Don't see yours? If it takes an API or a file, we'll integrate with it — using your integration tools or ours.</p>
    </section>
  );
}

/* ---------- Security & trust ---------- */
function Security() {
  const icons = ["lock", "log", "shield", "key"];
  return (
    <section className="alt-security" id="security">
      <div className="alt-security__inner">
        <div className="alt-security__copy">
          <div className="alt-eyebrow alt-eyebrow--sm">Security &amp; trust</div>
          <h2 className="alt-h2">Enterprise-grade from the first order.</h2>
        </div>
        <ul className="alt-security__list">
          {SECURITY.map((s, i) => (
            <Reveal as="li" delay={i * 80} key={s}>
              <span className="alt-security__icon"><Icon name={icons[i]} /></span>
              <span>{s}</span>
            </Reveal>
          ))}
        </ul>
      </div>
    </section>
  );
}

/* ---------- Roadmap teaser ---------- */
function Roadmap() {
  const live = ["PO automation", "Quotes", "Customer, site & product matching", "API integration", "Webhooks"];
  const soon = ["EDI processing", "Invoices", "3-way matching", "Business rules engine", "Automated workflows", "Data mapper", "Reports", "Dispute resolution by messaging", "Partner portal"];
  return (
    <section className="alt-roadmap" id="roadmap">
      <div className="alt-roadmap__card">
        <div className="alt-eyebrow alt-eyebrow--sm">What's next</div>
        <h2 className="alt-h3">PO automation today. The full order lifecycle next.</h2>
        <p className="alt-roadmap__body">
          We started where the pain is sharpest. PO automation, quotes, and master-data matching are live
          today — EDI, invoices, and 3-way matching are next. We ship based on where the demand is.
        </p>
        <div className="alt-roadmap__groups">
          <div className="alt-roadmap__group">
            <div className="alt-roadmap__glabel is-live"><span className="alt-roadmap__gdot"></span>Live now</div>
            <div className="alt-roadmap__chips">
              {live.map((m) => (
                <span className="alt-modchip is-live" key={m}>
                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true"><path d="M3 7.2l2.6 2.6L11 4.4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  {m}
                </span>
              ))}
            </div>
          </div>
          <div className="alt-roadmap__group">
            <div className="alt-roadmap__glabel"><span className="alt-roadmap__gdot"></span>Coming soon</div>
            <div className="alt-roadmap__chips">
              {soon.map((m) => (
                <span className="alt-modchip" key={m}>{m}</span>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Design-partner credibility block (honest — no fabricated customer quote) ---------- */
function FounderNote() {
  return (
    <section className="alt-quote alt-founder">
      <Reveal>
        <div className="alt-eyebrow alt-eyebrow--sm" style={{ display: "inline-flex" }}>Design partners</div>
        <h2 className="alt-h3 alt-h3--center alt-founder__h">We're picking a small group of design partners — on purpose.</h2>
        <p className="alt-founder__body">
          Altriks is live and runs real purchase orders end to end. Before we open the doors, we're inviting
          a handful of distributors and manufacturers to work hand-in-hand with us — making the exception
          queue feel effortless on their messiest POs. Partners get direct access to the team, influence over
          the roadmap, and preferential pricing at GA.
        </p>
        <div className="alt-quote__by" style={{ justifyContent: "center" }}>
          <div className="alt-quote__avatar">A</div>
          <div>
            <div className="alt-quote__name">The Altriks team</div>
            <div className="alt-quote__role">Building autonomous order entry</div>
          </div>
        </div>
      </Reveal>
    </section>
  );
}

/* ---------- Final CTA (inline capture) ---------- */
function FinalCTA() {
  return (
    <section className="alt-cta" id="join">
      <div className="alt-cta__card">
        <h2 className="alt-cta__title">See your own purchase orders processed automatically.</h2>
        <p className="alt-cta__sub">Become a design partner. Bring a real PO — we'll run it live on a 30-minute call. No commitment, no card.</p>
        <div style={{ display: "flex", justifyContent: "center", margin: "26px 0 4px", position: "relative", zIndex: 1 }}>
          <Button variant="primary" size="lg" href="/contact">Apply to become a design partner</Button>
        </div>
        <p className="alt-cta__helper">Pre-GA — we onboard a small group of design partners at a time.</p>
      </div>
    </section>
  );
}

/* ---------- Footer ---------- */
function Footer() {
  return (
    <footer className="alt-footer alt-footer--min">
      <div className="alt-footer__min">
        <Logo />
        <address className="alt-footer__addr">
          <span className="alt-footer__addr-name">McKinney / Craig Ranch</span>
          7300 State Highway 121, Suite 300<br />
          McKinney, Texas 75070
        </address>
        <a className="alt-footer__email" href="mailto:info@altriks.com">info@altriks.com</a>
      </div>
      <div className="alt-footer__bottom">
        <span>© 2026 Altriks. All rights reserved.</span>
        <span><a href="#" onClick={(e) => e.preventDefault()}>Privacy</a></span>
      </div>
    </footer>
  );
}

/* ---------- Sticky capture bar (session-aware, suppressed after submit) ---------- */
function StickyCTA() {
  const [show, setShow] = React.useState(false);
  const [dismissed, setDismissed] = React.useState(() => {
    try { return sessionStorage.getItem("alt_sticky_dismissed") === "1"; } catch (e) { return false; }
  });
  const [converted, setConverted] = React.useState(false);

  React.useEffect(() => {
    // Ignore the bar's OWN submit so its success panel can paint; other surfaces suppress it.
    const onLead = (e) => { if (e.detail && e.detail.surface === "compact") return; setConverted(true); };
    window.addEventListener("alt_lead", onLead);
    const onScroll = () => {
      const y = window.scrollY, vh = window.innerHeight;
      const cta = document.querySelector(".alt-cta");
      const nearFooter = cta ? cta.getBoundingClientRect().top < vh + 200 : false;
      setShow(y > vh * 0.9 && !nearFooter);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => { window.removeEventListener("scroll", onScroll); window.removeEventListener("alt_lead", onLead); };
  }, []);

  if (dismissed || converted) return null;
  const dismiss = () => {
    setDismissed(true);
    try { sessionStorage.setItem("alt_sticky_dismissed", "1"); } catch (e) {}
  };

  return (
    <div className={`alt-sticky ${show ? "is-in" : ""}`} role="complementary" aria-label="Become a design partner">
      <div className="alt-sticky__inner">
        <div className="alt-sticky__msg">
          <b>See it run on your own PO.</b>
          <span>Become a design partner — a live 30-minute run.</span>
        </div>
        <a className="alt-btn alt-btn--primary alt-btn--md alt-sticky__cta" href="/contact">Apply now</a>
        <button className="alt-sticky__x" type="button" aria-label="Dismiss" onClick={dismiss}>✕</button>
      </div>
    </div>
  );
}

function Sections({ heroVariant }) {
  // statgrid and bold heroes already show the proof metrics, so skip them in the proof bar.
  const showMetrics = !(heroVariant === "statgrid" || heroVariant === "bold");
  return (
    <React.Fragment>
      <ProofStrip showMetrics={showMetrics} />
      <Problem />
      <HowItWorks />
      <Features />
      <Integrations />
      <Security />
      <Roadmap />
      <FounderNote />
      <FinalCTA />
      <Footer />
    </React.Fragment>
  );
}

Object.assign(window, { Sections, StickyCTA });
