const { useState, useEffect, useRef, useMemo } = React;

// ---------- Content ----------
const BRAND = "Mortar";

// Bump this whenever the landing page copy/layout meaningfully changes.
// Used as an analytics user/event property so we can slice funnel metrics
// by which landing variant the user saw.
const LANDING_VERSION = "v1-mortar-launch";

const LANDING = {
  eyebrow: "For independent community pharmacies",
  title: "They paid you in December.",
  titleEm: "Took it in April.",
  sub: "Real-time audit risk scoring catches every missing signature, DEA error, and NDC mismatch before submission.",
  cta: "See how it works",
  micro: "2 minutes · 3 questions · no credit card",
};

const I_AM_OPTIONS = [
  { id: "owner",  label: "Pharmacy owner",           hint: "PIC / DOR / independent operator" },
  { id: "pharm",  label: "Pharmacist",               hint: "Staff or floater RPh" },
  { id: "tech",   label: "Pharmacy technician",      hint: "CPhT / lead tech" },
  { id: "mgmt",   label: "Operations / management",  hint: "Multi-store, GPO, buying group" },
  { id: "other",  label: "Something else",           hint: "Curious, consultant, vendor" },
];

const THUMB_QS = [
  {
    id: "q_audits",
    eyebrow: "Question 2 of 3",
    prompt: "Have PBM audits cost your pharmacy money in the last 12 months?",
  },
  {
    id: "q_time",
    eyebrow: "Question 3 of 3",
    prompt: "Does audit response eat more than 10 hours of your team's time per month?",
  },
];

// ---------- Utils ----------
const cx = (...a) => a.filter(Boolean).join(" ");
const fmtPhone = (raw) => {
  const d = raw.replace(/\D/g, "").slice(0, 10);
  if (d.length < 4) return d;
  if (d.length < 7) return `(${d.slice(0,3)}) ${d.slice(3)}`;
  return `(${d.slice(0,3)}) ${d.slice(3,6)}-${d.slice(6)}`;
};

// Safe no-op if tracker isn't loaded (e.g. ad blockers, or analytics not yet wired).
// NOTE: name is intentionally NOT `track` — Babel Standalone hoists top-level
// `const` into `window` under a classic script tag, which would shadow
// `window.track` from index.html and cause infinite recursion.
const fire = (name, params) => { try { window.track && window.track(name, params); } catch (e) {} };

// ---------- App ----------
function App() {
  const [step, setStep] = useState(0);
  const [answers, setAnswers] = useState({ role: null, q_audits: null, q_time: null });
  const [dir, setDir] = useState(1);
  const [capture, setCapture] = useState({ phone: "", email: "" });

  const totalSteps = 4;

  useEffect(() => {
    fire("landing_viewed");
    fire("landing_cohort_loaded", { cohort: LANDING_VERSION });
    try {
      if (window.amplitude) {
        const id = new amplitude.Identify();
        id.set("landing_cohort", LANDING_VERSION);
        amplitude.identify(id);
      }
    } catch (e) {}
  }, []);

  const go = (next) => {
    setDir(next > step ? 1 : -1);
    setStep(next);
  };

  const setAnswer = (key, val) => {
    setAnswers((a) => ({ ...a, [key]: val }));
    fire(`${key}_answered`, { answer: String(val) });
    setTimeout(() => go(step + 1), 260);
  };

  return (
    <>
      <TopBar step={step} total={totalSteps} onHome={() => go(0)} />

      <main style={{ position: "relative", zIndex: 1, flex: 1, display: "flex", flexDirection: "column" }}>
        {step === 0 && <Landing onStart={(position = "hero") => {
          fire("landing_cta_clicked", { position });
          fire("AddToCart", { value: 1, currency: "USD" }); // Meta retail-funnel signal
          go(1);
        }} />}

        {step === 1 && (
          <QuizFrame key="s1" dir={dir} eyebrow="Question 1 of 3" title="I am…" sub="Tap one to continue.">
            <IAmGrid value={answers.role} onPick={(v) => setAnswer("role", v)} />
            <BackNext canBack={true} onBack={() => go(0)} canNext={!!answers.role} onNext={() => go(2)} />
          </QuizFrame>
        )}

        {step >= 2 && step <= 3 && (() => {
          const q = THUMB_QS[step - 2];
          const val = answers[q.id];
          return (
            <QuizFrame key={q.id} dir={dir} eyebrow={q.eyebrow} title={q.prompt}>
              <ThumbsRow value={val} onPick={(v) => setAnswer(q.id, v)} />
              <BackNext canBack={true} onBack={() => go(step - 1)} canNext={val !== null && val !== undefined} onNext={() => go(step + 1)} />
            </QuizFrame>
          );
        })()}

        {step === 4 && (
          <QuizFrame
            key="capture"
            dir={dir}
            title="You qualify for priority access to Mortar Rx."
            sub="Create your free account to get started."
          >
            <CaptureForm
              value={capture}
              onChange={setCapture}
              onSubmit={() => {
                const props = {
                  role: answers.role,
                  phone: capture.phone,
                  email: capture.email,
                  q_audits: answers.q_audits,
                  q_time: answers.q_time,
                };
                try {
                  if (window.amplitude) {
                    if (capture.email) amplitude.setUserId(capture.email);
                    else if (capture.phone) amplitude.setUserId(capture.phone);
                    const id = new amplitude.Identify();
                    if (capture.email) id.set("email", capture.email);
                    if (capture.phone) id.set("phone", capture.phone);
                    id.set("role", answers.role);
                    amplitude.identify(id);
                  }
                } catch (e) {}
                fire("capture_submitted", props);
                fire("Purchase", { ...props, value: 1, currency: "USD" });
                // TODO: POST to your backend / form service (Formspree, Netlify Forms, etc.)
                go(5);
              }}
            />
          </QuizFrame>
        )}

        {step === 5 && <ThankYou answers={answers} capture={capture} onRestart={() => { setAnswers({ role:null,q_audits:null,q_time:null }); setCapture({phone:"",email:""}); go(0); }} />}
      </main>

      <Footer />
    </>
  );
}

// ---------- Top bar + progress ----------
function TopBar({ step, total, onHome }) {
  const showBar = step > 0 && step <= total;
  const pct = showBar ? ((step) / total) * 100 : 0;
  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 10, background: "rgba(244,238,226,0.86)",
      backdropFilter: "blur(10px)", WebkitBackdropFilter: "blur(10px)",
      borderBottom: "1px solid var(--rule-soft)",
    }}>
      <div style={{
        maxWidth: 1200, margin: "0 auto", padding: "18px 28px",
        display: "flex", alignItems: "center", justifyContent: "space-between", gap: 20,
      }}>
        <button onClick={onHome} style={{ display: "flex", alignItems: "center", gap: 10, padding: 0 }}>
          <Logo />
          <span style={{ fontFamily: "var(--serif)", fontSize: 22, letterSpacing: -0.3 }}>{BRAND}</span>
        </button>
      </div>
      <div style={{ height: 2, background: "transparent", position: "relative" }}>
        <div style={{
          position: "absolute", left: 0, top: 0, bottom: 0, width: `${pct}%`,
          background: "var(--terra)", transition: "width 420ms cubic-bezier(.2,.8,.2,1)",
        }} />
      </div>
    </header>
  );
}

function Logo() {
  // Mortar Rx amber-bottle mark (B4 finalist from icon exploration): amber bottle
  // silhouette with cream rectangular label and Rx (R + slash). Same SVG geometry
  // is shared with favicon.svg so the mark reads identically across surfaces.
  return (
    <svg width="28" height="28" viewBox="160 160 704 704" fill="none" aria-hidden>
      <path d="M 432 200 L 592 200 L 592 268 L 612 268 Q 644 268 644 300 L 644 392 Q 700 432 700 488 L 700 800 Q 700 836 664 836 L 360 836 Q 324 836 324 800 L 324 488 Q 324 432 380 392 L 380 300 Q 380 268 412 268 L 432 268 Z" fill="var(--terra)" />
      <path d="M 412 268 L 432 268 L 432 200 L 592 200 L 592 268 L 612 268 Q 644 268 644 300 L 644 392" fill="none" stroke="var(--terra-deep)" strokeWidth="3" opacity="0.4" />
      <rect x="372" y="544" width="280" height="190" fill="var(--paper)" rx="3" />
      <line x1="376" y1="558" x2="648" y2="558" stroke="var(--ink)" strokeWidth="3" />
      <line x1="376" y1="720" x2="648" y2="720" stroke="var(--ink)" strokeWidth="3" />
      <text x="486" y="680" fontFamily="Instrument Serif, serif" fontSize="170" fill="var(--ink)" textAnchor="middle">R</text>
      <line x1="510" y1="635" x2="590" y2="715" stroke="var(--ink)" strokeWidth="11" strokeLinecap="round" />
    </svg>
  );
}

// ---------- Landing ----------
function Landing({ onStart }) {
  return (
    <section style={{ position: "relative", zIndex: 1 }}>
      <div style={{
        maxWidth: 1200, margin: "0 auto", padding: "56px 28px 28px",
        display: "grid", gridTemplateColumns: "1.05fr 0.95fr", gap: 56, alignItems: "center",
      }} className="landing-grid">
        <div>
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 10, padding: "7px 12px",
            border: "1px solid var(--rule-soft)", borderRadius: 999,
            fontFamily: "var(--mono)", fontSize: 11, letterSpacing: 0.6, textTransform: "uppercase",
            color: "var(--ink-2)", background: "rgba(255,255,255,0.35)",
          }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--terra)" }} />
            {LANDING.eyebrow}
          </div>

          <h1 style={{
            fontFamily: "var(--serif)", fontWeight: 400, fontSize: "clamp(44px, 6.2vw, 84px)",
            lineHeight: 1.06, letterSpacing: -1.2, margin: "22px 0 0", color: "var(--ink)",
            textWrap: "balance",
          }}>
            {LANDING.title}<br />
            <em style={{ fontStyle: "italic", color: "var(--terra-deep)" }}>{LANDING.titleEm}</em>
          </h1>

          <p style={{
            fontSize: 18, lineHeight: 1.5, color: "var(--ink-2)", maxWidth: 520,
            margin: "22px 0 30px", textWrap: "pretty",
          }}>
            {LANDING.sub}
          </p>

          <div style={{ display: "flex", alignItems: "center", gap: 18, flexWrap: "wrap" }}>
            <PrimaryCTA onClick={() => onStart("hero")}>{LANDING.cta}</PrimaryCTA>
            <span style={{ fontFamily: "var(--mono)", fontSize: 12, color: "var(--ink-3)" }}>
              {LANDING.micro}
            </span>
          </div>

          <div style={{
            marginTop: 44, paddingTop: 22, borderTop: "1px dashed var(--rule-soft)",
            display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 18, maxWidth: 560,
          }}>
            {[
              ["$26,144", "avg recoupment / audit", "PAAS National", "https://paasnational.com/audit-assistance/"],
              ["+17%", "more audits than last year", "PAAS / Drug Topics", "https://www.drugtopics.com/view/q-a-common-reasons-independent-pharmacies-face-pbm-audits"],
              ["~1 / day", "indies closing, 2023–24 (NCPA)", "NCPA 2024 Digest", "https://ncpa.org/newsroom/news-releases/2024/10/27/ncpa-releases-2024-digest-report"],
            ].map(([n, l, src, href]) => (
              <div key={l}>
                <div style={{ fontFamily: "var(--serif)", fontSize: 26, lineHeight: 1, color: "var(--ink)" }}>{n}</div>
                <div style={{ fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: 0.4, textTransform: "uppercase", color: "var(--ink-3)", marginTop: 8 }}>{l}</div>
                <a
                  href={href}
                  target="_blank"
                  rel="noreferrer noopener"
                  onClick={() => fire("landing_stat_source_clicked", { stat: n, label: l, source: src, href })}
                  onAuxClick={(e) => { if (e.button === 1) fire("landing_stat_source_clicked", { stat: n, label: l, source: src, href, button: "middle" }); }}
                  style={{
                    display: "inline-block", marginTop: 6,
                    fontFamily: "var(--mono)", fontSize: 9.5, letterSpacing: 0.3,
                    color: "var(--ink-4)", textDecoration: "none", borderBottom: "1px dotted var(--rule-soft)",
                  }}
                  onMouseEnter={(e) => { e.currentTarget.style.color = "var(--ink-3)"; }}
                  onMouseLeave={(e) => { e.currentTarget.style.color = "var(--ink-4)"; }}
                >
                  {src}
                </a>
              </div>
            ))}
          </div>
        </div>

        <HeroPhoto />
      </div>

      <div className="landing-footer-cta" style={{
        maxWidth: 1200, margin: "0 auto", padding: "12px 28px 56px",
        display: "none", flexDirection: "column", alignItems: "center", gap: 12,
      }}>
        <PrimaryCTA onClick={() => onStart("footer")}>{LANDING.cta}</PrimaryCTA>
        <span style={{ fontFamily: "var(--mono)", fontSize: 12, color: "var(--ink-3)" }}>
          {LANDING.micro}
        </span>
      </div>

      <style>{`
        @media (max-width: 900px) {
          .landing-grid { grid-template-columns: 1fr !important; gap: 36px !important; padding-top: 32px !important; }
          .landing-footer-cta { display: flex !important; }
        }
      `}</style>
    </section>
  );
}

function HeroPhoto() {
  return (
    <div style={{ position: "relative" }}>
      <div style={{
        aspectRatio: "4 / 5", borderRadius: "var(--radius-lg)", overflow: "hidden",
        background: "var(--paper-2)", border: "1px solid var(--rule-soft)",
        boxShadow: "0 1px 0 rgba(255,255,255,0.6) inset, 0 30px 60px -30px rgba(28,26,23,0.35)",
        position: "relative",
      }}>
        <img
          src="hero.jpg"
          alt="Pharmacist handing a prescription bag to a customer at the counter."
          style={{ display: "block", width: "100%", height: "100%", objectFit: "cover" }}
        />

        <div style={{
          position: "absolute", left: 18, right: 18, bottom: 18,
          background: "rgba(28,26,23,0.88)", color: "#F4EEE2",
          padding: "14px 16px", borderRadius: 12,
          display: "flex", alignItems: "center", gap: 12,
          backdropFilter: "blur(4px)",
        }}>
          <span style={{ width: 8, height: 8, borderRadius: 999, background: "#7BC08A", boxShadow: "0 0 0 4px rgba(123,192,138,0.25)" }} />
          <div style={{ lineHeight: 1.3 }}>
            <div style={{ fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: 0.6, textTransform: "uppercase", opacity: 0.75 }}>
              live at counter
            </div>
            <div style={{ fontSize: 14 }}>3 risk flags caught on last claim.</div>
          </div>
        </div>
      </div>

      <div style={{
        position: "absolute", top: -14, right: -14, transform: "rotate(6deg)",
        background: "var(--paper)", border: "1px solid var(--rule-soft)",
        padding: "8px 12px", borderRadius: 8, fontFamily: "var(--mono)", fontSize: 11,
        color: "var(--ink-2)", boxShadow: "0 10px 24px -18px rgba(28,26,23,0.5)",
      }}>
        rx-7821 · flagged
      </div>
    </div>
  );
}

// ---------- Quiz shell ----------
function QuizFrame({ dir, eyebrow, title, sub, tag, children }) {
  const [mounted, setMounted] = useState(false);
  useEffect(() => { const t = requestAnimationFrame(() => setMounted(true)); return () => cancelAnimationFrame(t); }, []);
  const enterStyle = {
    transform: mounted ? "translateY(0)" : `translateY(${dir > 0 ? 14 : -14}px)`,
    opacity: mounted ? 1 : 0,
    transition: "transform 420ms cubic-bezier(.2,.8,.2,1), opacity 320ms ease",
  };
  return (
    <section style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", padding: "40px 24px 60px" }}>
      <div style={{ width: "min(760px, 100%)", ...enterStyle }}>
        {eyebrow && (
          <div style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: 1, textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 18 }}>
            {eyebrow}
          </div>
        )}
        <h2 style={{
          fontFamily: "var(--serif)", fontWeight: 400,
          fontSize: "clamp(34px, 4.4vw, 54px)", lineHeight: 1.02, letterSpacing: -0.6,
          margin: 0, color: "var(--ink)", textWrap: "balance",
        }}>
          {title}
        </h2>
        {sub && <p style={{ marginTop: 14, color: "var(--ink-2)", fontSize: 17, lineHeight: 1.5, maxWidth: 580 }}>{sub}</p>}
        {tag && (
          <div style={{ marginTop: 10, fontFamily: "var(--mono)", fontSize: 10.5, color: "var(--terra-deep)", letterSpacing: 0.4 }}>
            {tag}
          </div>
        )}
        <div style={{ marginTop: 34 }}>
          {children}
        </div>
      </div>
    </section>
  );
}

// ---------- I am grid ----------
function IAmGrid({ value, onPick }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }} className="iam-grid">
      {I_AM_OPTIONS.map((opt) => {
        const active = value === opt.id;
        return (
          <button
            key={opt.id}
            onClick={() => onPick(opt.id)}
            style={{
              textAlign: "left", padding: "18px 20px",
              background: active ? "var(--ink)" : "rgba(255,255,255,0.45)",
              color: active ? "var(--paper)" : "var(--ink)",
              border: `1px solid ${active ? "var(--ink)" : "var(--rule-soft)"}`,
              borderRadius: "var(--radius)",
              display: "flex", alignItems: "center", justifyContent: "space-between", gap: 14,
              transition: "transform 180ms ease, background 180ms ease, border-color 180ms ease",
            }}
            onMouseDown={(e) => e.currentTarget.style.transform = "scale(0.985)"}
            onMouseUp={(e) => e.currentTarget.style.transform = ""}
            onMouseLeave={(e) => e.currentTarget.style.transform = ""}
          >
            <div>
              <div style={{ fontSize: 18, fontWeight: 500, letterSpacing: -0.2 }}>{opt.label}</div>
              <div style={{ fontSize: 13, color: active ? "rgba(244,238,226,0.6)" : "var(--ink-3)", marginTop: 4 }}>{opt.hint}</div>
            </div>
            <div style={{
              width: 28, height: 28, borderRadius: 999,
              border: `1px solid ${active ? "var(--paper)" : "var(--rule-soft)"}`,
              display: "grid", placeItems: "center", flexShrink: 0,
              background: active ? "var(--terra)" : "transparent",
              transition: "all 180ms ease",
            }}>
              {active && <Check color="var(--paper)" />}
            </div>
          </button>
        );
      })}
      <style>{`
        .iam-grid button:hover { background: rgba(255,255,255,0.75) !important; }
        .iam-grid button[style*="rgb(28, 26, 23)"]:hover { background: var(--ink) !important; }
        @media (max-width: 620px) { .iam-grid { grid-template-columns: 1fr !important; } }
      `}</style>
    </div>
  );
}

function Check({ color = "white" }) {
  return (
    <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
      <path d="M2.5 7.5 L5.5 10.5 L11.5 3.5" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

// ---------- Thumbs ----------
function ThumbsRow({ value, onPick }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }} className="thumbs-grid">
      <ThumbCard kind="up" active={value === "up"} onPick={() => onPick("up")} />
      <ThumbCard kind="down" active={value === "down"} onPick={() => onPick("down")} />
      <style>{`
        @media (max-width: 620px) { .thumbs-grid { grid-template-columns: 1fr !important; } }
      `}</style>
    </div>
  );
}

function ThumbCard({ kind, active, onPick }) {
  const isUp = kind === "up";
  const accent = isUp ? "var(--ok)" : "var(--bad)";
  return (
    <button
      onClick={onPick}
      style={{
        padding: "32px 22px",
        background: active ? accent : "rgba(255,255,255,0.5)",
        color: active ? "var(--paper)" : "var(--ink)",
        border: `1px solid ${active ? accent : "var(--rule-soft)"}`,
        borderRadius: "var(--radius-lg)",
        display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 14,
        transition: "transform 180ms ease, background 180ms, border-color 180ms",
        minHeight: 160,
      }}
      onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = "rgba(255,255,255,0.82)"; }}
      onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = "rgba(255,255,255,0.5)"; }}
      onMouseDown={(e) => e.currentTarget.style.transform = "scale(0.985)"}
      onMouseUp={(e) => e.currentTarget.style.transform = ""}
    >
      <Thumb up={isUp} color={active ? "var(--paper)" : "var(--ink)"} />
      <div style={{ fontFamily: "var(--serif)", fontSize: 30, letterSpacing: -0.4, lineHeight: 1 }}>
        {isUp ? "Yes" : "No"}
      </div>
      <div style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: 0.6, textTransform: "uppercase", opacity: 0.75 }}>
        {isUp ? "thumbs up" : "thumbs down"}
      </div>
    </button>
  );
}

function Thumb({ up, color }) {
  const rot = up ? 0 : 180;
  return (
    <svg width="40" height="40" viewBox="0 0 40 40" fill="none" style={{ transform: `rotate(${rot}deg)`, transition: "transform 220ms" }}>
      <path
        d="M12 17 L16 17 L19 8.5 C 19.6 6.8 22 7 22 9 L 22 16 L 29 16 C 30.7 16 32 17.3 32 19 L 30.5 29 C 30.2 30.7 28.7 32 27 32 L 17 32 C 15 32 14 31 14 29 L 14 19 C 14 17.9 12.9 17 12 17 Z"
        stroke={color} strokeWidth="1.6" strokeLinejoin="round" fill="none"
      />
      <rect x="6" y="17" width="6" height="15" rx="1.6" stroke={color} strokeWidth="1.6" fill="none" />
    </svg>
  );
}

// ---------- Back/Next ----------
function BackNext({ canBack, onBack, canNext, onNext }) {
  return (
    <div style={{ marginTop: 30, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
      <button
        onClick={onBack}
        disabled={!canBack}
        style={{
          fontFamily: "var(--mono)", fontSize: 12, letterSpacing: 0.6, textTransform: "uppercase",
          color: canBack ? "var(--ink-2)" : "var(--ink-4)",
          padding: "10px 0", cursor: canBack ? "pointer" : "not-allowed",
        }}
      >
        ← Back
      </button>
      <button
        onClick={onNext}
        disabled={!canNext}
        style={{
          fontFamily: "var(--mono)", fontSize: 12, letterSpacing: 0.6, textTransform: "uppercase",
          color: canNext ? "var(--paper)" : "var(--ink-4)",
          background: canNext ? "var(--ink)" : "var(--paper-3)",
          padding: "12px 22px", borderRadius: 999,
          transition: "background 180ms, color 180ms",
          cursor: canNext ? "pointer" : "not-allowed",
        }}
      >
        Next →
      </button>
    </div>
  );
}

// ---------- Primary CTA ----------
function PrimaryCTA({ children, onClick }) {
  return (
    <button
      onClick={onClick}
      style={{
        background: "var(--ink)", color: "var(--paper)",
        padding: "18px 28px", borderRadius: 999,
        fontSize: 16, fontWeight: 500, letterSpacing: -0.1,
        display: "inline-flex", alignItems: "center", gap: 12,
        transition: "transform 180ms ease, background 180ms ease",
        boxShadow: "0 20px 40px -24px rgba(28,26,23,0.55)",
      }}
      onMouseEnter={(e) => { e.currentTarget.style.background = "var(--terra-deep)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.background = "var(--ink)"; }}
      onMouseDown={(e) => e.currentTarget.style.transform = "scale(0.98)"}
      onMouseUp={(e) => e.currentTarget.style.transform = ""}
    >
      {children}
      <span style={{
        width: 26, height: 26, borderRadius: 999, background: "var(--terra)",
        display: "grid", placeItems: "center",
      }}>
        <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
          <path d="M2 6h8M7 3l3 3-3 3" stroke="var(--paper)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </span>
    </button>
  );
}

// ---------- Capture ----------
function CaptureForm({ value, onChange, onSubmit }) {
  const [mode, setMode] = useState("phone");
  const [errors, setErrors] = useState({});
  const phoneRaw = value.phone.replace(/\D/g, "");
  const phoneOk = phoneRaw.length === 10;
  const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.email);
  const valid = mode === "phone" ? phoneOk : emailOk;

  const submit = (e) => {
    e.preventDefault();
    const errs = {};
    if (mode === "phone" && !phoneOk) errs.phone = "10-digit US phone number";
    if (mode === "email" && !emailOk) errs.email = "Valid email please";
    setErrors(errs);
    if (Object.keys(errs).length === 0) onSubmit();
  };

  return (
    <form onSubmit={submit} style={{ display: "grid", gap: 14 }}>
      {mode === "phone" ? (
        <Field
          key="phone"
          label="Mobile phone"
          placeholder="(555) 123-4567"
          value={value.phone}
          onChange={(v) => onChange({ ...value, phone: fmtPhone(v) })}
          inputMode="tel"
          error={errors.phone}
          autoFocus
        />
      ) : (
        <Field
          key="email"
          label="Email"
          placeholder="you@pharmacy.com"
          value={value.email}
          onChange={(v) => onChange({ ...value, email: v })}
          inputMode="email"
          error={errors.email}
          autoFocus
        />
      )}

      <div>
        <button
          type="button"
          onClick={() => { setErrors({}); setMode(mode === "phone" ? "email" : "phone"); }}
          style={{
            fontFamily: "var(--mono)", fontSize: 11, letterSpacing: 0.6, textTransform: "uppercase",
            color: "var(--ink-3)", padding: "4px 0", textDecoration: "underline", textUnderlineOffset: 3,
          }}
        >
          Use {mode === "phone" ? "email" : "mobile"} instead
        </button>
      </div>

      <div style={{ marginTop: 10, display: "flex", justifyContent: "flex-end" }}>
        <button type="submit"
          style={{
            background: valid ? "var(--ink)" : "var(--paper-3)",
            color: valid ? "var(--paper)" : "var(--ink-4)",
            padding: "16px 26px", borderRadius: 999,
            fontSize: 15, fontWeight: 500, letterSpacing: -0.1,
            display: "inline-flex", alignItems: "center", gap: 10,
            transition: "background 180ms, color 180ms",
            cursor: valid ? "pointer" : "not-allowed",
          }}>
          Get started
          <svg width="14" height="14" viewBox="0 0 12 12" fill="none">
            <path d="M2 6h8M7 3l3 3-3 3" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </button>
      </div>

      <div style={{ marginTop: 6, fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-3)", lineHeight: 1.5 }}>
        No spam, no sales calls.
      </div>
    </form>
  );
}

function Field({ label, value, onChange, placeholder, inputMode, error, autoFocus }) {
  const [focus, setFocus] = useState(false);
  return (
    <label style={{ display: "block" }}>
      <div style={{
        fontFamily: "var(--mono)", fontSize: 11, letterSpacing: 0.6, textTransform: "uppercase",
        color: error ? "var(--bad)" : "var(--ink-3)", marginBottom: 8,
      }}>
        {label}{error && <span> · {error}</span>}
      </div>
      <div style={{
        display: "flex", alignItems: "center",
        background: "rgba(255,255,255,0.7)",
        border: `1px solid ${error ? "var(--bad)" : focus ? "var(--ink)" : "var(--rule-soft)"}`,
        borderRadius: "var(--radius)",
        padding: "4px 6px 4px 16px",
        transition: "border-color 160ms",
      }}>
        <input
          autoFocus={autoFocus}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          onFocus={() => setFocus(true)}
          onBlur={() => setFocus(false)}
          placeholder={placeholder}
          inputMode={inputMode}
          style={{
            border: 0, outline: "none", background: "transparent",
            flex: 1, fontSize: 17, padding: "14px 0", color: "var(--ink)",
            fontFamily: "var(--sans)",
          }}
        />
      </div>
    </label>
  );
}

// ---------- Thank you ----------
function ThankYou({ answers, capture, onRestart }) {
  const contact = capture.phone || capture.email || "you";
  return (
    <section style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", padding: "48px 24px 60px" }}>
      <div style={{ width: "min(720px, 100%)", textAlign: "center" }}>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 10, fontFamily: "var(--mono)", fontSize: 11, letterSpacing: 0.8, textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 20 }}>
          <span style={{ width: 8, height: 8, borderRadius: 999, background: "var(--ok)" }} />
          You're in
        </div>
        <h2 style={{ fontFamily: "var(--serif)", fontWeight: 400, fontSize: "clamp(44px, 6vw, 72px)", lineHeight: 1, letterSpacing: -0.8, margin: 0, textWrap: "balance" }}>
          You're registered.<br />
          <em style={{ fontStyle: "italic", color: "var(--terra-deep)" }}>We'll reach out to get you started.</em>
        </h2>
        <p style={{ maxWidth: 500, margin: "22px auto 0", color: "var(--ink-2)", fontSize: 17, lineHeight: 1.5 }}>
          A real human from {BRAND} will follow up at <b>{contact}</b> to get your audit shield set up.
        </p>

        <button onClick={onRestart} style={{ marginTop: 30, fontFamily: "var(--mono)", fontSize: 12, letterSpacing: 0.6, textTransform: "uppercase", color: "var(--ink-2)" }}>
          ← Restart
        </button>
      </div>
    </section>
  );
}

// ---------- Footer ----------
function Footer() {
  return (
    <footer style={{ position: "relative", zIndex: 1, padding: "28px 28px 38px", borderTop: "1px solid var(--rule-soft)", marginTop: 24 }}>
      <div style={{ maxWidth: 1200, margin: "0 auto", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16, fontFamily: "var(--mono)", fontSize: 11, color: "var(--ink-3)", letterSpacing: 0.4, textTransform: "uppercase" }}>
        <span>© {BRAND} · built for independents</span>
        <span>hello@mortarrx.com</span>
      </div>
    </footer>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
