// Two-tier "finder". One shell, two configs:
//   - ServiceFinder (home page): which service do I need? -> routes to a service page.
//   - WillFinder (wills page): which kind of Will? -> routes to the right route/trust.
// Local state only, 3 questions, auto-advancing with a soft cross-fade. No backend.
const { useState: useStateWf, useMemo: useMemoWf } = React;

// ---------------------------------------------------------------------------
// Config A — Which WILL do I need? (lives on the wills page)
// ---------------------------------------------------------------------------
const WILL_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, b: 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: 'Protect my business and my family', icon: 'briefcase', score: { b: 3 } },
      { label: 'Reduce future inheritance tax', icon: 'landmark', score: { t: 1, p: 1, b: 1 } },
    ],
  },
];

const WILL_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',
    ],
    service: { href: 'online-wills.html', label: 'Start your Will online' },
  },
  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',
    ],
    service: { href: 'book-an-appointment.html?service=Wills', label: 'Book a consultation' },
  },
  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',
    ],
    service: { href: 'family-property-trusts.html', label: 'See Family & Property Trusts' },
  },
  b: {
    title: 'A Will for Business Owners',
    body: 'Running a business adds a layer of complexity to any Will. We help make sure your company, your family, and the legacy you have built are all properly protected.',
    includes: [
      'Business succession planning built into your Will',
      'Protection for partners and shareholders',
      'Inheritance tax reliefs for business assets',
      'Personal wishes and guardianship alongside',
    ],
    service: { href: 'wills-for-business-owners.html', label: 'See Wills for Business Owners' },
  },
};

function computeWill(answers) {
  const tot = { s: 0, t: 0, p: 0, b: 0 };
  answers.forEach((oi, qi) => {
    if (oi == null) return;
    const sc = WILL_QUESTIONS[qi].options[oi].score;
    Object.keys(sc).forEach((k) => { tot[k] = (tot[k] || 0) + sc[k]; });
  });
  const max = Math.max(tot.s, tot.t, tot.p, tot.b);
  if (tot.b === max) return 'b';
  if (tot.t === max) return 't';
  if (tot.p === max) return 'p';
  return 's';
}

const WILL_FINDER = {
  id: 'will-finder',
  kicker: 'Not sure which Will?',
  headingLead: 'Which Will do I need?',
  headingEm: "Most people aren't sure.",
  intro: 'Answer three quick questions and we will point you to the right starting point. It takes under a minute, and there is no obligation.',
  questions: WILL_QUESTIONS,
  results: WILL_RESULTS,
  compute: computeWill,
};

// ---------------------------------------------------------------------------
// Config B — Which SERVICE do I need? (lives on the home page)
// ---------------------------------------------------------------------------
const SERVICE_QUESTIONS = [
  {
    q: 'What is prompting you to plan today?',
    options: [
      { label: 'Deciding who inherits what I leave behind', icon: 'fileText', score: { will: 2 } },
      { label: 'Making sure someone can act for me if I cannot', icon: 'heartHandshake', score: { lpa: 2 } },
      { label: 'Protecting my home or a vulnerable loved one', icon: 'shieldCheck', score: { trust: 2 } },
      { label: 'Sorting out the estate of someone who has died', icon: 'scale', score: { probate: 5 } },
    ],
  },
  {
    q: 'Tell us a bit more about your situation.',
    options: [
      { label: 'I have nothing in place yet', icon: 'sparkles', score: { will: 1, lpa: 1 } },
      { label: 'I run a business or am self-employed', icon: 'briefcase', score: { bizwill: 2, bizlpa: 2 } },
      { label: 'I worry about care fees or family disputes', icon: 'home', score: { trust: 2 } },
      { label: 'I am concerned about inheritance tax', icon: 'landmark', score: { iht: 3 } },
    ],
  },
  {
    q: 'What matters most to you?',
    options: [
      { label: 'Keeping things simple and properly sorted', icon: 'check', score: { will: 2 } },
      { label: 'Protecting assets for the next generation', icon: 'landmark', score: { trust: 2, iht: 1 } },
      { label: 'My wishes being followed if I become unwell', icon: 'heartHandshake', score: { lpa: 2, bizlpa: 1 } },
      { label: 'Keeping my business running if something happens', icon: 'briefcase', score: { bizwill: 2, bizlpa: 2 } },
    ],
  },
];

const SERVICE_RESULTS = {
  will: {
    title: 'a Will',
    body: 'A clear, professionally drafted Will is the foundation of any plan. It sets out who inherits what, names the people you trust, and gives you the final say rather than leaving it to the law.',
    includes: [
      'Clear instructions for who inherits what',
      'The people you trust named as executors',
      'Guardianship wishes for any children under 18',
      'Plain-English drafting, simple to keep current',
    ],
    service: { href: 'wills.html', label: 'See our Wills service' },
  },
  lpa: {
    title: 'a Lasting Power of Attorney',
    body: 'An LPA lets you choose, while you still can, who would make decisions for you if illness or an accident ever took that ability away. Without one, even close family may have to apply to a court.',
    includes: [
      'Decisions kept with people you choose',
      'Cover for finances, or health and care, or both',
      'Protection if capacity is ever lost',
      'We complete and register the paperwork for you',
    ],
    service: { href: 'lasting-power-of-attorney.html', label: 'See our LPA service' },
  },
  trust: {
    title: 'a Trust',
    body: 'Where there is a little more to protect, a trust can help shield your home or provide for someone in your care. We explain the options plainly and only suggest one where it genuinely helps.',
    includes: [
      'Options to help protect your home',
      'Provision for a vulnerable or dependent loved one',
      'Structures suited to blended families',
      'Honest advice on whether you need one at all',
    ],
    service: { href: 'trusts.html', label: 'See our Trusts service' },
  },
  probate: {
    title: 'Probate support',
    body: 'Losing someone is hard enough without the paperwork. We can guide you through probate and estate administration at your own pace, taking as much of the weight off your shoulders as you would like.',
    includes: [
      'Guidance through the probate process',
      'Help with estate administration and forms',
      'Support at a pace that suits you',
      'A calm, human point of contact throughout',
    ],
    service: { href: 'probate.html', label: 'See our Probate service' },
  },
  storage: {
    title: 'Will Storage & Updates',
    body: 'If your Will is already written, the next job is keeping it safe and current. We store it securely and keep it up to date as life changes, so it is ready and valid the moment it is needed.',
    includes: [
      'Secure, insured storage',
      'A certificate so your executors can find it',
      'Unlimited updates as life changes',
      'A digital backup, so nothing is ever lost',
    ],
    service: { href: 'will-storage-and-updates.html', label: 'See Will Storage' },
  },
  bizwill: {
    title: 'a Will for Business Owners',
    body: 'A standard Will often is not enough when a business is involved. We help business owners put a Will in place that protects the company, the family, and the legacy they have built.',
    includes: [
      'Business succession planning built into your Will',
      'Protection for partners and shareholders',
      'Inheritance tax reliefs for business assets',
      'Guardianship and personal wishes alongside',
    ],
    service: { href: 'wills-for-business-owners.html', label: 'See Wills for Business Owners' },
  },
  bizlpa: {
    title: 'a Business LPA',
    body: 'If you run a business, a Business LPA makes sure someone you trust can keep things running if you lose capacity. It works alongside your personal LPAs to cover every angle.',
    includes: [
      'A trusted person authorised to run your business',
      'Continuity for employees, clients and suppliers',
      'Separate from your personal LPAs',
      'Registered with the Office of the Public Guardian',
    ],
    service: { href: 'business-lasting-power-of-attorney.html', label: 'See Business LPAs' },
  },
  iht: {
    title: 'Inheritance Tax Planning',
    body: 'Inheritance Tax can take a significant bite out of the estate you leave behind. With the right planning, much of this can be reduced or avoided altogether, leaving more for the people who matter most.',
    includes: [
      'Practical, honest advice tailored to your estate',
      'Gifting strategies and exemptions explained plainly',
      'Trust options to reduce your taxable estate',
      'A plan that fits your family, not a one-size template',
    ],
    service: { href: 'inheritance-tax-planning.html', label: 'See IHT Planning' },
  },
};

function computeService(answers) {
  const tot = { will: 0, lpa: 0, trust: 0, probate: 0, storage: 0, bizwill: 0, bizlpa: 0, iht: 0 };
  answers.forEach((oi, qi) => {
    if (oi == null) return;
    const sc = SERVICE_QUESTIONS[qi].options[oi].score;
    Object.keys(sc).forEach((k) => { tot[k] = (tot[k] || 0) + sc[k]; });
  });
  const max = Math.max.apply(null, Object.keys(tot).map((k) => tot[k]));
  if (max <= 0) return 'will';
  const priority = ['bizwill', 'bizlpa', 'iht', 'will', 'lpa', 'trust', 'probate', 'storage'];
  return priority.find((k) => tot[k] === max) || 'will';
}

const SERVICE_FINDER = {
  id: 'service-finder',
  kicker: 'Not sure where to start?',
  headingLead: 'What do you need?',
  headingEm: "Let's find your starting point.",
  intro: 'Answer three quick questions and we will point you to the service that fits. It takes under a minute, and there is no obligation.',
  questions: SERVICE_QUESTIONS,
  results: SERVICE_RESULTS,
  compute: computeService,
};

// ---------------------------------------------------------------------------
// Shared option button
// ---------------------------------------------------------------------------
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>
  );
}

// ---------------------------------------------------------------------------
// Shared finder shell
// ---------------------------------------------------------------------------
function Finder({ config }) {
  const qs = config.questions;
  const [step, setStep] = useStateWf(0); // 0..qs.length-1 questions, qs.length = result
  const [answers, setAnswers] = useStateWf(qs.map(() => 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(qs.map(() => null)));

  const result = useMemoWf(() => (step === qs.length ? config.compute(answers) : null), [step, answers]);
  const res = result ? config.results[result] : null;
  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={config.id} className="relative overflow-hidden bg-cream" style={{ paddingTop: 'clamp(56px,8vw,92px)', paddingBottom: 'clamp(56px,8vw,92px)' }}>
      <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' }}>{config.kicker}</p>
          <h2 className="mx-auto mt-3 font-display font-normal text-navy" style={{ fontSize: 'clamp(32px,4.5vw,50px)', lineHeight: 1.12, letterSpacing: '-0.015em', maxWidth: '20ch' }}>
            {config.headingLead} <em style={{ fontStyle: 'italic', color: '#4A6FA4' }}>{config.headingEm}</em>
          </h2>
          <p className="mx-auto mt-4 font-sans text-stone" style={{ fontSize: 17, lineHeight: 1.6, maxWidth: '54ch' }}>
            {config.intro}
          </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 < qs.length ? `Step ${step + 1} of ${qs.length}` : 'Result'}
            </span>
          </div>
          <div className="flex gap-1.5" aria-hidden="true">
            {Array.from({ length: qs.length + 1 }, (_, i) => i).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 < qs.length ? (
              <React.Fragment>
                <h3 className="font-display font-normal text-navy" style={{ fontSize: 'clamp(22px,3.2vw,26px)', lineHeight: 1.2 }}>
                  {qs[step].q}
                </h3>
                <div className="mt-5 grid grid-cols-1 gap-3">
                  {qs[step].options.map((opt, oi) => (
                    <WfOption key={opt.label} opt={opt} selected={answers[step] === oi} onSelect={() => choose(step, oi)} />
                  ))}
                </div>
              </React.Fragment>
            ) : (
              <div>
                <span className="inline-flex h-12 w-12 items-center justify-center rounded-full" style={{ background: 'radial-gradient(circle at 35% 30%, #FFD97A, #F0B83C)', color: '#1A3066', boxShadow: '0 10px 24px -10px rgba(240,184,60,0.9)' }}>
                  <Icon name="sparkles" size={22} strokeWidth={1.8} />
                </span>
                <p className="mt-4 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(28px,4vw,40px)', lineHeight: 1.12, letterSpacing: '-0.015em' }}>
                  Sounds like <em style={{ fontStyle: 'italic', color: '#C9912A' }}>{res.title}</em> would suit you.
                </h3>
                <p className="mt-4 font-sans text-ink" style={{ fontSize: 16, lineHeight: 1.65 }}>{res.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">
                  {res.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={res.service.href}
                    className="inline-flex items-center justify-center gap-2 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 }}
                  >
                    {res.service.label}
                    <Icon name="arrowRight" size={16} strokeWidth={2.2} />
                  </a>
                  <a
                    href="book-an-appointment.html"
                    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')}
                  >
                    Book a free chat
                  </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>
  );
}

function WillFinder() { return <Finder config={WILL_FINDER} />; }
function ServiceFinder() { return <Finder config={SERVICE_FINDER} />; }

Object.assign(window, { WillFinder, ServiceFinder, Finder });
