// "Which Will do I need?" — local-state interactive finder. 3 questions, auto-advancing
// with a soft cross-fade, then a tailored result. No backend.
const { useState: useStateWf, useMemo: useMemoWf } = React;

const WF_QUESTIONS = [
  {
    q: 'What is your situation?',
    options: [
      { label: 'Single', icon: 'user', score: { s: 1 } },
      { label: 'Married or partnered', icon: 'heart', score: { t: 1 } },
      { label: 'Children under 18', icon: 'baby', score: { t: 1, p: 1 } },
      { label: 'Blended family or remarried', icon: 'users', score: { p: 2 } },
    ],
  },
  {
    q: 'Do you own property or notable assets?',
    options: [
      { label: 'I rent', icon: 'key', score: { s: 1 } },
      { label: 'I own my home', icon: 'home', score: { t: 1 } },
      { label: 'I own property and other assets', icon: 'building', score: { t: 2 } },
      { label: 'I own a business or multiple properties', icon: 'briefcase', score: { p: 2 } },
    ],
  },
  {
    q: 'Any of these on your mind?',
    options: [
      { label: 'Just want it sorted simply', icon: 'sparkles', score: { s: 2 } },
      { label: 'Protect home from care fees', icon: 'shieldCheck', score: { p: 2 } },
      { label: 'Provide for a vulnerable loved one', icon: 'heartHandshake', score: { p: 2 } },
      { label: 'Reduce future inheritance tax', icon: 'landmark', score: { t: 1, p: 1 } },
    ],
  },
];

const WF_RESULTS = {
  s: {
    title: 'A Straightforward Will',
    body: 'Your situation looks nice and clear, so a simple, well-drafted Will may be all you need. We will make sure it is valid, properly witnessed, and easy to update if life changes.',
    includes: [
      'Clear instructions for who inherits what',
      'Naming the people you trust as executors',
      'Plain-English drafting, checked by a professional',
      'Simple to review and update over time',
    ],
  },
  t: {
    title: 'A Tailored Will',
    body: 'Most families sit somewhere in between, so a tailored Will fits your circumstances rather than a template. We shape it around your property, your people, and any specific wishes you have.',
    includes: [
      'Cover for your property and savings together',
      'Guardianship wishes if you have children',
      'Specific gifts and personal wishes included',
      'Executors and clear, considered instructions',
    ],
  },
  p: {
    title: 'A Will with Protective Trusts',
    body: 'Your answers suggest there is a little more to protect, so a Will with trusts can help shield your home or provide for someone in your care. We explain the options plainly and only suggest what genuinely helps.',
    includes: [
      'Options to help protect your home against future care costs',
      'Provision for a vulnerable or dependent loved one',
      'Structures suited to blended families or a business',
      'Guidance on reducing future inheritance tax',
    ],
  },
};

function computeResult(answers) {
  const tot = { s: 0, t: 0, p: 0 };
  answers.forEach((oi, qi) => {
    if (oi == null) return;
    const sc = WF_QUESTIONS[qi].options[oi].score;
    Object.keys(sc).forEach((k) => { tot[k] += sc[k]; });
  });
  const max = Math.max(tot.s, tot.t, tot.p);
  // Ties prefer Tailored, then Protective, then Straightforward.
  if (tot.t === max) return 't';
  if (tot.p === max) return 'p';
  return 's';
}

function WfOption({ opt, selected, onSelect }) {
  return (
    <button
      type="button"
      onClick={onSelect}
      aria-pressed={selected}
      className="group flex w-full items-center gap-4 rounded-2xl bg-white px-5 py-5 text-left"
      style={{
        boxShadow: selected ? 'inset 0 0 0 1.5px #F0B83C' : 'inset 0 0 0 1.5px rgba(26,48,102,0.14)',
        background: selected ? 'rgba(255,204,87,0.12)' : '#fff',
        transition: 'box-shadow 250ms ' + EASE + ', background-color 250ms ' + EASE + ', transform 250ms ' + EASE,
      }}
      onMouseEnter={(e) => { if (!selected) e.currentTarget.style.boxShadow = 'inset 0 0 0 1.5px rgba(26,48,102,0.3)'; }}
      onMouseLeave={(e) => { if (!selected) e.currentTarget.style.boxShadow = 'inset 0 0 0 1.5px rgba(26,48,102,0.14)'; }}
    >
      <span
        className="inline-flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-full"
        style={{ background: selected ? '#FFCC57' : '#EAF1FA', color: selected ? '#1A3066' : '#4A6FA4', transition: 'background-color 250ms ' + EASE }}
      >
        <Icon name={opt.icon} size={21} strokeWidth={1.9} />
      </span>
      <span className="flex-1 font-sans font-medium text-ink" style={{ fontSize: 16 }}>{opt.label}</span>
      <span
        className="inline-flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full"
        style={{ background: '#F0B83C', color: '#fff', opacity: selected ? 1 : 0, transform: selected ? 'scale(1)' : 'scale(0.5)', transition: 'opacity 220ms ' + EASE + ', transform 220ms ' + EASE }}
      >
        <Icon name="check" size={15} strokeWidth={3} />
      </span>
    </button>
  );
}

function WillFinder() {
  const [step, setStep] = useStateWf(0); // 0..2 questions, 3 = result
  const [answers, setAnswers] = useStateWf([null, null, null]);
  const [visible, setVisible] = useStateWf(true);
  const reduced = usePrefersReducedMotion();
  const staticRender = useStaticRender();
  const dur = staticRender ? 0 : 300;

  const advance = (toStep, mutate) => {
    setVisible(false);
    setTimeout(() => { mutate && mutate(); setStep(toStep); setVisible(true); }, dur);
  };
  const choose = (qi, oi) => {
    const next = [...answers]; next[qi] = oi; setAnswers(next);
    advance(qi + 1, null);
  };
  const restart = () => advance(0, () => setAnswers([null, null, null]));

  const result = useMemoWf(() => (step === 3 ? computeResult(answers) : null), [step, answers]);
  const filled = step + 1;
  const mag = useMagnetic(3);

  const innerStyle = staticRender
    ? {}
    : {
        opacity: visible ? 1 : 0,
        transform: visible ? 'none' : 'translateY(10px)',
        transition: `opacity ${dur}ms ${EASE}, transform ${dur}ms ${EASE}`,
      };

  return (
    <section id="will-finder" className="relative overflow-hidden bg-cream" style={{ paddingTop: 'clamp(72px,10vw,120px)', paddingBottom: 'clamp(72px,10vw,120px)' }}>
      <Grain opacity={0.045} />
      <Blob color="#F4685F" size={360} opacity={0.13} blur={10} speed={34} rotate={7} style={{ top: '40px', left: '-130px' }} />
      <Blob color="#FFCC57" size={300} opacity={0.18} blur={9} speed={-26} rotate={-6} style={{ bottom: '20px', right: '-110px' }} />
      <Blob color="#EAF1FA" size={300} opacity={0.7} blur={8} speed={18} rotate={3} style={{ top: '30%', right: '20%' }} />

      <div className="relative mx-auto max-w-[820px] px-5 sm:px-7">
        <Reveal className="text-center">
          <p className="font-sans font-semibold uppercase text-gold-deep" style={{ fontSize: 13, letterSpacing: '0.18em' }}>Not sure where to start?</p>
          <h2 className="mx-auto mt-3 font-display font-normal text-navy" style={{ fontSize: 'clamp(32px,4.5vw,50px)', lineHeight: 1.1, letterSpacing: '-0.01em', maxWidth: '18ch' }}>
            Which Will do I need? Most people aren't sure.
          </h2>
          <p className="mx-auto mt-4 font-sans text-stone" style={{ fontSize: 17, lineHeight: 1.6, maxWidth: '54ch' }}>
            Answer three quick questions and we will point you to the right starting point. It takes under a minute, and there is no obligation.
          </p>
        </Reveal>

        <Reveal delay={120} className="mx-auto mt-10 rounded-[28px] bg-white p-6 sm:p-8 md:p-12" style={{ boxShadow: '0 40px 90px -40px rgba(26,48,102,0.4)', maxWidth: 820 }}>
          {/* Progress */}
          <div className="mb-2 flex items-center justify-between">
            <span className="font-sans font-semibold uppercase text-stone" style={{ fontSize: 11, letterSpacing: '0.16em' }}>
              {step < 3 ? `Step ${step + 1} of 3` : 'Result'}
            </span>
          </div>
          <div className="flex gap-1.5" aria-hidden="true">
            {[0, 1, 2, 3].map((i) => (
              <div key={i} className="h-1.5 flex-1 overflow-hidden rounded-full" style={{ background: 'rgba(26,48,102,0.1)' }}>
                <div style={{ height: '100%', width: i < filled ? '100%' : '0%', background: 'linear-gradient(90deg,#FFCC57,#F0B83C)', borderRadius: 999, transition: staticRender ? 'none' : 'width 500ms ' + EASE }} />
              </div>
            ))}
          </div>

          {/* Body */}
          <div className="mt-7" style={innerStyle}>
            {step < 3 ? (
              <React.Fragment>
                <h3 className="font-display font-normal text-navy" style={{ fontSize: 'clamp(22px,3.2vw,26px)', lineHeight: 1.2 }}>
                  {WF_QUESTIONS[step].q}
                </h3>
                <div className="mt-5 grid grid-cols-1 gap-3">
                  {WF_QUESTIONS[step].options.map((opt, oi) => (
                    <WfOption key={opt.label} opt={opt} selected={answers[step] === oi} onSelect={() => choose(step, oi)} />
                  ))}
                </div>
              </React.Fragment>
            ) : (
              <div>
                <p className="font-sans font-semibold uppercase text-gold-deep" style={{ fontSize: 12, letterSpacing: '0.16em' }}>Based on your answers</p>
                <h3 className="mt-3 font-display font-normal text-navy" style={{ fontSize: 'clamp(26px,3.6vw,32px)', lineHeight: 1.15 }}>
                  Sounds like {WF_RESULTS[result].title} would suit you.
                </h3>
                <p className="mt-4 font-sans text-ink" style={{ fontSize: 16, lineHeight: 1.65 }}>{WF_RESULTS[result].body}</p>

                <p className="mt-6 font-sans font-semibold text-navy" style={{ fontSize: 14 }}>What this typically includes</p>
                <ul className="mt-3 grid grid-cols-1 gap-2.5 sm:grid-cols-2">
                  {WF_RESULTS[result].includes.map((it) => (
                    <li key={it} className="flex items-start gap-3 font-sans text-ink" style={{ fontSize: 15, lineHeight: 1.5 }}>
                      <span className="mt-0.5 inline-flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-full" style={{ background: '#FFCC57', color: '#1A3066' }}>
                        <Icon name="check" size={13} strokeWidth={3} />
                      </span>
                      {it}
                    </li>
                  ))}
                </ul>

                <div className="mt-8 flex flex-col gap-3 sm:flex-row">
                  <a
                    ref={mag.ref}
                    onMouseMove={mag.onMouseMove}
                    onMouseLeave={mag.onMouseLeave}
                    href="#contact"
                    onClick={(e) => smoothTo(e, '#contact')}
                    className="inline-flex items-center justify-center rounded-full bg-gold px-7 py-3.5 font-sans font-semibold text-[16px] text-navy hover:bg-gold-deep"
                    style={{ boxShadow: '0 14px 30px -12px rgba(240,184,60,0.85)', transition: 'transform 250ms ' + EASE + ', background-color 250ms ' + EASE }}
                  >
                    Book my free chat
                  </a>
                  <a
                    href="#services"
                    onClick={(e) => smoothTo(e, '#services')}
                    className="inline-flex items-center justify-center rounded-full px-7 py-3.5 font-sans font-semibold text-[16px] text-navy"
                    style={{ boxShadow: 'inset 0 0 0 1.5px #1A3066', transition: 'background-color 250ms ' + EASE }}
                    onMouseEnter={(e) => (e.currentTarget.style.background = 'rgba(26,48,102,0.06)')}
                    onMouseLeave={(e) => (e.currentTarget.style.background = 'transparent')}
                  >
                    See all services
                  </a>
                </div>

                <p className="mt-6 font-display italic text-stone" style={{ fontSize: 14, lineHeight: 1.5 }}>
                  This is a guide, not advice. We will confirm the right fit when we talk.
                </p>
                <button type="button" onClick={restart} className="mt-3 font-sans font-medium text-blue underline-offset-4 hover:underline" style={{ fontSize: 14 }}>
                  Start again
                </button>
              </div>
            )}
          </div>
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { WillFinder });
