/* Quiz — multi-step matching flow */

const QUESTIONS = [
  {
    id: "reasons",
    type: "multi",
    title: "What brings you here today?",
    sub: "Pick all that apply. We use this to weight your matches.",
    options: [
      "Cost concerns",
      "A US cycle didn't work",
      "I want a donor program",
      "Single mother by choice",
      "Same-sex couple",
      "Just researching for now",
    ],
  },
  {
    id: "age",
    type: "single",
    title: "How old are you?",
    sub: "Age is the single biggest input on protocol and clinic match.",
    options: ["Under 30", "30–34", "35–37", "38–40", "41–43", "44+"],
  },
  {
    id: "amh",
    type: "single",
    title: "Do you know your AMH level?",
    sub: "If not, no problem — many patients don't yet.",
    options: ["Yes, I know my number", "Roughly — pick a range", "No, not yet", "Prefer not to say"],
  },
  {
    id: "cycles",
    type: "single",
    title: "How many IVF cycles have you completed?",
    options: ["None", "1", "2", "3 or more"],
  },
  {
    id: "donor",
    type: "single",
    title: "Are you considering using donor eggs?",
    options: ["Yes, definitely", "Maybe", "No", "Tell me more about this"],
  },
  {
    id: "household",
    type: "single",
    title: "Are you partnered, single, or in a same-sex couple?",
    options: ["Partnered (different-sex)", "Single", "Same-sex couple"],
  },
  {
    id: "timeline",
    type: "single",
    title: "What's your timeline for starting a cycle?",
    options: ["Within 3 months", "3–6 months", "6–12 months", "Just exploring"],
  },
  {
    id: "email",
    type: "email",
    title: "Where should we send your matches?",
    sub: "We'll email your shortlist plus the full clinic profiles. No list-broking. One email, one human team.",
  },
  {
    id: "budget",
    type: "single",
    title: "What's your monthly out-of-pocket budget for the full cycle, including travel?",
    options: ["Under $8,000", "$8,000–$12,000", "$12,000–$18,000", "$18,000+", "Still figuring it out"],
  },
  {
    id: "medical",
    type: "multi",
    title: "Any specific medical concerns?",
    sub: "Multi-select. We share these only with the matched clinics, with your permission.",
    options: ["Endometriosis", "PCOS", "Low ovarian reserve", "Recurrent loss", "Male factor", "None I know of", "Prefer not to say"],
  },
  {
    id: "notes",
    type: "text",
    title: "Anything else we should know?",
    sub: "Optional. Up to 500 characters. Skip if nothing comes to mind.",
  },
];

const MOCK_MATCHES = [
  {
    name: "Vida Fertility",
    city: "Alicante",
    volume: "1,400+ cycles / yr",
    rate: "61%",
    cost: "€6,400 – €9,800",
    why: [
      "Strong donor egg outcomes for the 38–40 age band.",
      "End-to-end English-language operations (intake → discharge).",
      "Cycle data published quarterly with methodology disclosure.",
    ],
    tag: "Best clinical fit",
  },
  {
    name: "Equipo Juana Crespo",
    city: "Valencia",
    volume: "950 cycles / yr",
    rate: "58%",
    cost: "€7,200 – €11,000",
    why: [
      "Specialist in cases with prior failed cycles or low AMH.",
      "Senior embryologist on every retrieval.",
      "Generous donor pool with phenotypic matching.",
    ],
    tag: "Strong second opinion",
  },
  {
    name: "Eugin Madrid",
    city: "Madrid",
    volume: "2,100 cycles / yr",
    rate: "55%",
    cost: "€5,600 – €8,900",
    why: [
      "High volume + reliable scheduling for tight timelines.",
      "Direct flights from JFK, ORD, MIA, LAX, BOS to MAD.",
      "Coordinated US-side OB-GYN handoff.",
    ],
    tag: "Most flexible scheduling",
  },
];

const ProgressBar = ({ pct }) => (
  <div className="w-full h-[3px] bg-sand rounded-full overflow-hidden">
    <div className="h-full bg-teal transition-all duration-500 ease-out" style={{ width: `${pct}%` }} />
  </div>
);

const QuizPage = () => {
  const [step, setStep] = React.useState(0); // 0..QUESTIONS.length, then "loading", "results"
  const [phase, setPhase] = React.useState("intro"); // intro | quiz | loading | results
  const [answers, setAnswers] = React.useState({});

  const total = QUESTIONS.length;
  const q = QUESTIONS[step];
  const pct = phase === "intro" ? 0 : phase === "results" ? 100 : ((step + 1) / total) * 100;

  const setAns = (id, val) => setAnswers(a => ({ ...a, [id]: val }));
  const isAnswered = q && (
    q.type === "multi" ? (answers[q.id] || []).length > 0 :
    q.type === "text"  ? true :
    q.type === "email" ? !!(answers.email && answers.email.includes("@") && answers.firstName) :
    !!answers[q.id]
  );

  const next = () => {
    if (step + 1 < total) setStep(step + 1);
    else { setPhase("loading"); setTimeout(() => setPhase("results"), 4500); }
  };
  const prev = () => { if (step > 0) setStep(step - 1); };

  return (
    <PageShell>
      <div className="min-h-[calc(100vh-4rem)] bg-bone flex flex-col">
        {/* Top progress + meta */}
        <div className="px-6 md:px-10 pt-4 pb-6 max-w-[1100px] w-full mx-auto">
          <div className="flex items-center justify-between mb-3 text-[12px] uppercase tracking-[0.18em] text-inksoft/55">
            <span className="font-mono">
              {phase === "intro" ? "00" : phase === "results" ? "12" : String(step + 1).padStart(2, "0")} / {String(total).padStart(2, "0")}
            </span>
            <span>The matching quiz · ~5 min</span>
            <span className="font-mono">{Math.round(pct)}%</span>
          </div>
          <ProgressBar pct={pct} />
        </div>

        <div className="flex-1 px-6 md:px-10 pb-20">
          <div className="max-w-[1100px] mx-auto">
            {phase === "intro" && <Intro onStart={() => setPhase("quiz")} />}
            {phase === "quiz" && (
              <QuizCard
                q={q}
                value={answers[q.id]}
                emailValue={answers.email}
                firstNameValue={answers.firstName}
                setAns={setAns}
                onNext={next}
                onBack={prev}
                canBack={step > 0}
                canNext={isAnswered}
                step={step}
                total={total}
              />
            )}
            {phase === "loading" && <Loading />}
            {phase === "results" && <Results firstName={answers.firstName} />}
          </div>
        </div>
      </div>
    </PageShell>
  );
};

const Intro = ({ onStart }) => (
  <div className="grid grid-cols-12 gap-10 items-center pt-8 md:pt-16">
    <div className="col-span-12 md:col-span-7">
      <Eyebrow>The matching quiz</Eyebrow>
      <h1 className="mt-4 font-serif text-[52px] md:text-[80px] leading-[0.92] tracking-displaytight">
        Twelve quiet questions. <span className="italic text-teal">Two or three matches.</span>
      </h1>
      <p className="mt-6 text-[17px] text-inksoft leading-relaxed max-w-xl">
        Skip anything you don't know. Save your progress at the email step.
        We'll send your shortlist within minutes — and you can talk to a real
        advisor whenever you're ready.
      </p>
      <div className="mt-8 flex items-center gap-4">
        <Btn onClick={onStart} variant="teal">Start question 1</Btn>
        <a href="#/" className="text-[14px] text-inksoft underline underline-offset-4 decoration-inksoft/20 hover:decoration-inksoft">Back home</a>
      </div>
      <ul className="mt-12 grid grid-cols-1 sm:grid-cols-3 gap-4 max-w-2xl">
        {[
          { i: <IClock size={18} />, t: "About 5 minutes", s: "12 questions, one per screen." },
          { i: <IShield size={18} />, t: "Your data stays here", s: "Shared only with matched clinics, with permission." },
          { i: <IScale size={18} />, t: "Standard commission", s: "We can't be paid to recommend a clinic." },
        ].map(x => (
          <li key={x.t} className="rounded-xl border border-sand p-4">
            <div className="text-teal mb-2">{x.i}</div>
            <div className="font-medium text-[14px]">{x.t}</div>
            <div className="text-[12.5px] text-inksoft/70 mt-0.5 leading-snug">{x.s}</div>
          </li>
        ))}
      </ul>
    </div>
    <div className="col-span-12 md:col-span-5">
      <div className="relative aspect-[4/5] rounded-2xl overflow-hidden border border-sand">
        <img
          src="https://images.unsplash.com/photo-1518770660439-4636190af475?w=1200&q=80&auto=format&fit=crop"
          alt=""
          className="w-full h-full object-cover"
        />
        <div className="absolute inset-0 bg-gradient-to-t from-ink/50 via-transparent to-transparent" />
        <div className="absolute bottom-5 left-5 right-5 text-bone">
          <div className="font-serif italic text-[16px] mb-1 text-bone/80">Today's match queue</div>
          <div className="font-serif text-[42px] leading-[0.95] tracking-displaytight">37 patients matched this week.</div>
        </div>
      </div>
    </div>
  </div>
);

const QuizCard = ({ q, value, emailValue, firstNameValue, setAns, onNext, onBack, canBack, canNext, step, total }) => {
  const renderInput = () => {
    if (q.type === "single") {
      return (
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          {q.options.map(opt => {
            const active = value === opt;
            return (
              <button
                key={opt}
                onClick={() => { setAns(q.id, opt); setTimeout(onNext, 220); }}
                className={`text-left p-5 rounded-xl border transition-all ${
                  active ? "border-teal bg-teal/5 text-ink" : "border-sand bg-bone hover:border-teal/40"
                }`}
              >
                <div className="flex items-center justify-between">
                  <span className="text-[15.5px]">{opt}</span>
                  <span className={`flex h-6 w-6 items-center justify-center rounded-full border ${active ? "bg-teal border-teal text-bone" : "border-sand text-transparent"}`}>
                    <ICheck size={13} stroke={2.5}/>
                  </span>
                </div>
              </button>
            );
          })}
        </div>
      );
    }
    if (q.type === "multi") {
      const sel = value || [];
      const toggle = (opt) => {
        const has = sel.includes(opt);
        setAns(q.id, has ? sel.filter(s => s !== opt) : [...sel, opt]);
      };
      return (
        <>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            {q.options.map(opt => {
              const active = sel.includes(opt);
              return (
                <button
                  key={opt}
                  onClick={() => toggle(opt)}
                  className={`text-left p-5 rounded-xl border transition-all ${
                    active ? "border-teal bg-teal/5 text-ink" : "border-sand bg-bone hover:border-teal/40"
                  }`}
                >
                  <div className="flex items-center justify-between">
                    <span className="text-[15.5px]">{opt}</span>
                    <span className={`flex h-6 w-6 items-center justify-center rounded-md border ${active ? "bg-teal border-teal text-bone" : "border-sand text-transparent"}`}>
                      <ICheck size={13} stroke={2.5}/>
                    </span>
                  </div>
                </button>
              );
            })}
          </div>
          <div className="mt-4 text-[12.5px] text-inksoft/60">{sel.length} selected</div>
        </>
      );
    }
    if (q.type === "text") {
      return (
        <textarea
          className="ci-input min-h-[140px] resize-none"
          maxLength={500}
          placeholder="A previous diagnosis, a question we should answer up front, your worry list…"
          value={value || ""}
          onChange={(e) => setAns(q.id, e.target.value)}
        />
      );
    }
    if (q.type === "email") {
      return (
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 max-w-xl">
          <div>
            <label className="text-[11.5px] uppercase tracking-[0.18em] text-inksoft/55">First name</label>
            <input className="ci-input mt-1.5" placeholder="e.g. Maya" value={firstNameValue || ""} onChange={(e) => setAns("firstName", e.target.value)} />
          </div>
          <div>
            <label className="text-[11.5px] uppercase tracking-[0.18em] text-inksoft/55">Email</label>
            <input type="email" className="ci-input mt-1.5" placeholder="you@email.com" value={emailValue || ""} onChange={(e) => setAns("email", e.target.value)} />
          </div>
          <div className="sm:col-span-2 mt-2 text-[12.5px] text-inksoft/65 leading-relaxed flex items-start gap-2">
            <IShield size={14} className="text-teal mt-0.5 shrink-0" />
            We send your shortlist here. We never share your email with clinics until you opt in.
          </div>
        </div>
      );
    }
  };

  return (
    <div className="pt-6 md:pt-12 pb-12 max-w-[860px] mx-auto">
      <div className="mb-7">
        <div className="text-[11.5px] uppercase tracking-[0.18em] text-teal mb-3 font-mono">Question {String(step + 1).padStart(2, "0")} / {String(total).padStart(2, "0")}</div>
        <h2 className="font-serif text-[36px] md:text-[52px] leading-[1.02] tracking-displaytight text-ink">
          {q.title}
        </h2>
        {q.sub && <p className="mt-3 text-[15.5px] text-inksoft leading-relaxed max-w-2xl">{q.sub}</p>}
      </div>

      {renderInput()}

      <div className="mt-10 flex items-center justify-between">
        <button
          onClick={onBack}
          disabled={!canBack}
          className={`text-[14px] inline-flex items-center gap-2 ${canBack ? "text-inksoft hover:text-ink" : "text-inksoft/30 cursor-not-allowed"}`}
        >
          <span className="rotate-180"><IArrow size={14} stroke={2}/></span> Back
        </button>
        <Btn onClick={onNext} variant={canNext ? "teal" : "outline"} className={!canNext ? "opacity-50 pointer-events-none" : ""}>
          {step + 1 === total ? "See my matches" : "Continue"}
        </Btn>
      </div>
    </div>
  );
};

const Loading = () => {
  const [phaseText, setPhaseText] = React.useState("Reviewing your answers…");
  React.useEffect(() => {
    const seq = [
      "Reviewing your answers…",
      "Filtering 32 vetted clinics on your medical fit…",
      "Cross-checking success-rate transparency…",
      "Ranking by clinical match, not commission…",
      "Drafting your match rationale…",
    ];
    let i = 0;
    const id = setInterval(() => { i = (i + 1) % seq.length; setPhaseText(seq[i]); }, 850);
    return () => clearInterval(id);
  }, []);
  return (
    <div className="min-h-[60vh] flex flex-col items-center justify-center text-center">
      <div className="relative w-20 h-20">
        <div className="absolute inset-0 rounded-full border-2 border-sand" />
        <div className="absolute inset-0 rounded-full border-2 border-teal border-t-transparent animate-spin" />
        <div className="absolute inset-3 rounded-full bg-teal/10 flex items-center justify-center text-teal">
          <ISpark size={22} />
        </div>
      </div>
      <div className="mt-7 font-serif text-[34px] tracking-display max-w-xl">Matching you to your clinics.</div>
      <div className="mt-3 text-[14.5px] text-inksoft/70">{phaseText}</div>
    </div>
  );
};

const Results = ({ firstName }) => (
  <div className="pt-6 md:pt-10 pb-12">
    <div className="grid grid-cols-12 gap-8 mb-10">
      <div className="col-span-12 md:col-span-8">
        <Eyebrow>Your matches</Eyebrow>
        <h1 className="mt-4 font-serif text-[44px] md:text-[64px] leading-[0.95] tracking-displaytight">
          {firstName ? <>{firstName}, here are your <span className="italic text-teal">three clinics</span>.</> : <>Here are your <span className="italic text-teal">three clinics</span>.</>}
        </h1>
        <p className="mt-4 text-[15.5px] text-inksoft max-w-2xl leading-relaxed">
          Ordered by clinical fit, not by who pays us — because they all pay us
          the same. You can book a free consultation with any of them. Or talk
          this through with a human first.
        </p>
      </div>
      <div className="col-span-12 md:col-span-4 md:pt-12 flex md:justify-end">
        <div className="rounded-xl border border-sand bg-cream p-5 max-w-sm">
          <div className="text-[12px] uppercase tracking-[0.2em] text-inksoft/55 mb-1">Want a human first?</div>
          <div className="font-serif text-[22px] tracking-display">Book a free 20-min advisor call.</div>
          <a href="#/" className="mt-3 inline-flex items-center gap-2 text-teal text-[14px] font-medium underline underline-offset-4 decoration-teal/30 hover:decoration-teal">
            See available times <IArrow size={14} stroke={2}/>
          </a>
        </div>
      </div>
    </div>

    <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
      {MOCK_MATCHES.map((m, i) => (
        <article key={m.name} className={`rounded-2xl border ${i === 0 ? "border-teal bg-teal/[0.04]" : "border-sand bg-bone"} p-7 flex flex-col`}>
          <div className="flex items-start justify-between mb-5">
            <span className={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[10.5px] uppercase tracking-[0.15em] font-medium ${i === 0 ? "bg-coral text-ink" : "bg-sand text-inksoft"}`}>
              <IDot size={8} /> {m.tag}
            </span>
            <span className="text-[11.5px] uppercase tracking-[0.18em] text-inksoft/50 font-mono">#{i + 1}</span>
          </div>
          <h3 className="font-serif text-[28px] leading-[1.05] tracking-display">{m.name}</h3>
          <div className="mt-1 flex items-center gap-2 text-[13px] text-inksoft/70">
            <IPin size={13} /> {m.city}, Spain
          </div>

          <div className="mt-5 grid grid-cols-3 gap-3 py-4 border-y border-sand/80">
            <Stat label="Volume" value={m.volume} />
            <Stat label="35-yr success" value={m.rate} />
            <Stat label="Est. cost" value={m.cost} />
          </div>

          <div className="mt-5">
            <div className="text-[11.5px] uppercase tracking-[0.18em] text-inksoft/55 mb-2">Why we matched you</div>
            <ul className="space-y-2">
              {m.why.map(w => (
                <li key={w} className="flex items-start gap-2 text-[13.5px] text-ink leading-snug">
                  <span className="mt-[6px] shrink-0 w-1 h-1 rounded-full bg-teal" /> {w}
                </li>
              ))}
            </ul>
          </div>

          <div className="mt-auto pt-6 flex items-center gap-3">
            <Btn variant={i === 0 ? "teal" : "outline"} href="#/">Book free consult</Btn>
            <a href="#/" className="text-[13.5px] text-inksoft hover:text-ink underline underline-offset-4 decoration-inksoft/20">Full profile</a>
          </div>
        </article>
      ))}
    </div>

    <div className="mt-10 rounded-2xl bg-ink text-bone p-7 md:p-10 grid grid-cols-12 gap-6 items-center">
      <div className="col-span-12 md:col-span-8">
        <Eyebrow dark>Optional next layer</Eyebrow>
        <h3 className="mt-3 font-serif text-[32px] md:text-[40px] leading-[1] tracking-displaytight">
          Ready for hands-off logistics? <span className="italic text-coral">Add White-Glove.</span>
        </h3>
        <p className="mt-3 text-[14.5px] text-bone/70 max-w-xl">
          Airport pickup, apartment near the clinic, on-call translator, partner-travel
          coordination, post-cycle OB-GYN handoff. €1,997–€2,997, optional.
        </p>
      </div>
      <div className="col-span-12 md:col-span-4 md:flex md:justify-end">
        <Btn href="#/concierge" variant="coral">See concierge tiers</Btn>
      </div>
    </div>
  </div>
);

const Stat = ({ label, value }) => (
  <div>
    <div className="text-[10.5px] uppercase tracking-[0.16em] text-inksoft/55">{label}</div>
    <div className="font-mono text-[13.5px] text-ink mt-1">{value}</div>
  </div>
);

Object.assign(window, { QuizPage });
