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

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

const LANDING = {
  eyebrow: "For independent community pharmacies",
  title: "Stop PBM clawbacks",
  titleEm: "before they happen.",
  sub: "An AI audit shield for independent pharmacies. We catch the missing signature, the illegible DEA, the NDC mismatch — at the counter, before Caremark, Express Scripts, or OptumRx ever sees the claim.",
  cta: "Start free audit check",
  micro: "2 minutes · 4 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 4",
    prompt: "Have PBM audits cost your pharmacy money in the last 12 months?",
  },
  {
    id: "q_time",
    eyebrow: "Question 3 of 4",
    prompt: "Does audit response eat more than 10 hours of your team's time per month?",
  },
  {
    id: "q_interest",
    eyebrow: "Question 4 of 4",
    prompt: "Would an agent that pre-checks every claim against Big-3 PBM rulebooks be useful to you?",
  },
];

// ---------- 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)
const track = (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, q_interest: null });
  const [dir, setDir] = useState(1);
  const [capture, setCapture] = useState({ pharmacy: "", phone: "", email: "" });

  const totalSteps = 5;

  useEffect(() => { track("landing_view"); }, []);

  const go = (next) => {
    setDir(next > step ? 1 : -1);
    setStep(next);
    track("funnel_step", { step: next, step_name: stepName(next) });
  };

  const setAnswer = (key, val) => {
    setAnswers((a) => ({ ...a, [key]: val }));
    track("quiz_answer", { question: key, 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={() => { track("landing_cta_click"); go(1); }} />}

        {step === 1 && (
          <QuizFrame key="s1" dir={dir} eyebrow="Question 1 of 4" 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 <= 4 && (() => {
          const q = THUMB_QS[step - 2];
          const val = answers[q.id];
          return (
            <QuizFrame key={q.id} dir={dir} eyebrow={q.eyebrow} title={q.prompt} tag={q.tag}>
              <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 === 5 && (
          <QuizFrame
            key="capture"
            dir={dir}
            eyebrow="Almost done"
            title="Where should we send your audit risk report?"
            sub="We'll text you a short link. No spam, no sales calls — a real report."
          >
            <CaptureForm
              value={capture}
              onChange={setCapture}
              onSubmit={() => {
                track("Lead", { role: answers.role, pharmacy: capture.pharmacy });
                track("lead_submitted", { role: answers.role });
                // TODO: POST to your backend / form service (Formspree, Netlify Forms, etc.)
                go(6);
              }}
              onBack={() => go(4)}
            />
          </QuizFrame>
        )}

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

      <Footer />
    </>
  );
}

function stepName(n) {
  return ["landing","role","q_audits","q_time","q_interest","capture","thank_you"][n] || String(n);
}

// ---------- 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>
        <nav style={{ display: "flex", alignItems: "center", gap: 22, fontSize: 13, color: "var(--ink-3)" }}>
          <span style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: 0.6, textTransform: "uppercase" }}>
            audit shield · v0.1
          </span>
        </nav>
      </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() {
  return (
    <svg width="28" height="28" viewBox="0 0 32 32" fill="none" aria-hidden>
      <circle cx="16" cy="16" r="14" stroke="var(--ink)" strokeWidth="1.5" />
      <path d="M7 19 C 11 15, 21 15, 25 19" stroke="var(--terra)" strokeWidth="1.8" strokeLinecap="round" />
      <circle cx="16" cy="16" r="1.6" fill="var(--ink)" />
    </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}>{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"],
              ["15–30", "audit events / yr"],
              ["~1 / day", "indies closing, 2024–26"],
            ].map(([n, l]) => (
              <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>
              </div>
            ))}
          </div>
        </div>

        <HeroPhoto />
      </div>

      <style>{`
        @media (max-width: 900px) {
          .landing-grid { grid-template-columns: 1fr !important; gap: 36px !important; padding-top: 32px !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",
      }}>
        <svg width="100%" height="100%" viewBox="0 0 400 500" preserveAspectRatio="xMidYMid slice" style={{ display: "block" }}>
          <defs>
            <pattern id="stripes" width="14" height="14" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
              <rect width="14" height="14" fill="#EADFC7" />
              <rect width="7" height="14" fill="#E3D6B9" />
            </pattern>
            <linearGradient id="warm" x1="0" y1="0" x2="1" y2="1">
              <stop offset="0" stopColor="#EEDFC1" />
              <stop offset="1" stopColor="#D9C8A6" />
            </linearGradient>
          </defs>
          <rect width="400" height="500" fill="url(#warm)" />
          <rect width="400" height="500" fill="url(#stripes)" opacity="0.55" />
          <g opacity="0.55" stroke="#1C1A17" strokeWidth="1">
            <line x1="40" y1="40" x2="80" y2="40" />
            <line x1="40" y1="40" x2="40" y2="80" />
            <line x1="360" y1="40" x2="320" y2="40" />
            <line x1="360" y1="40" x2="360" y2="80" />
            <line x1="40" y1="460" x2="80" y2="460" />
            <line x1="40" y1="460" x2="40" y2="420" />
            <line x1="360" y1="460" x2="320" y2="460" />
            <line x1="360" y1="460" x2="360" y2="420" />
          </g>
          <g transform="translate(200 250)" textAnchor="middle" fontFamily="JetBrains Mono, monospace" fill="#1C1A17">
            <text y="-8" fontSize="13" letterSpacing="2">[ PHOTO PLACEHOLDER ]</text>
            <text y="16" fontSize="11" opacity="0.7">pharmacist at counter · 4:5 · warm tone</text>
          </g>
        </svg>

        <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, onBack }) {
  const [errors, setErrors] = useState({});
  const phoneOk = value.phone.replace(/\D/g, "").length === 10;
  const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.email);
  const pharmOk = value.pharmacy.trim().length >= 2;
  const valid = phoneOk && emailOk && pharmOk;

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

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

      <div style={{ marginTop: 10, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 14, flexWrap: "wrap" }}>
        <button type="button" onClick={onBack}
          style={{ fontFamily: "var(--mono)", fontSize: 12, letterSpacing: 0.6, textTransform: "uppercase", color: "var(--ink-2)" }}>
          ← Back
        </button>
        <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 my audit risk report
          <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 }}>
        By submitting you agree to receive one text with your report. No sales calls. Unsubscribe anytime.
      </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 role = (I_AM_OPTIONS.find(o => o.id === answers.role) || {}).label || "—";
  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)" }} />
          Received
        </div>
        <h2 style={{ fontFamily: "var(--serif)", fontWeight: 400, fontSize: "clamp(44px, 6vw, 72px)", lineHeight: 1, letterSpacing: -0.8, margin: 0, textWrap: "balance" }}>
          Thank you.<br />
          <em style={{ fontStyle: "italic", color: "var(--terra-deep)" }}>We'll be in touch shortly.</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 text <b>{capture.phone || "your phone"}</b> within one business day with your pharmacy's audit-risk snapshot.
        </p>

        <div style={{
          marginTop: 36, padding: "18px 20px", maxWidth: 440, marginLeft: "auto", marginRight: "auto",
          border: "1px dashed var(--rule-soft)", borderRadius: "var(--radius)", textAlign: "left",
          background: "rgba(255,255,255,0.5)",
        }}>
          <div style={{ fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: 0.6, textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 10 }}>
            Receipt
          </div>
          <SmallRow k="Role" v={role} />
          <SmallRow k="Pharmacy" v={capture.pharmacy || "—"} />
          <SmallRow k="Phone" v={capture.phone || "—"} />
          <SmallRow k="Email" v={capture.email || "—"} />
          <SmallRow k="Answers" v={`${answers.q_audits || "–"} · ${answers.q_time || "–"} · ${answers.q_interest || "–"}`} />
        </div>

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

function SmallRow({ k, v }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", gap: 14, padding: "6px 0", borderBottom: "1px dotted var(--rule-soft)", fontSize: 14 }}>
      <span style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: 0.4, textTransform: "uppercase", color: "var(--ink-3)" }}>{k}</span>
      <span style={{ color: "var(--ink)", textAlign: "right" }}>{v}</span>
    </div>
  );
}

// ---------- 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@dosoria.co</span>
      </div>
    </footer>
  );
}

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