// === Find Your Fit — sizing wizard ===
// Four-question decision tool. Scores Solo/Crew/Command and explains why.

const WIZ_STEPS = [
  {
    id: "crew",
    label: "Crew",
    question: "How many people does the trailer need to support?",
    sub: "We size battery and outlet count to crew, not just kilowatts.",
    options: [
      { v: "solo",  title: "Just me",        sub: "1 operator · lifestyle / single trade",  weights: { 1: 3, 2: 1, 3: 0 } },
      { v: "small", title: "Small team",     sub: "2–6 people · trade crew, small build",   weights: { 1: 1, 2: 3, 3: 1 } },
      { v: "large", title: "Full operation", sub: "7+ people · multi-trade, multi-shift",   weights: { 1: 0, 2: 1, 3: 3 } },
    ],
  },
  {
    id: "load",
    label: "Loads",
    question: "What kit needs to run?",
    sub: "Pick everything that applies. We'll tally peak load.",
    multi: true,
    options: [
      { v: "tools",   title: "Power tools",          sub: "Drills, saws, compressor",        weights: { 1: 1, 2: 2, 3: 2 } },
      { v: "fridge",  title: "Refrigeration",        sub: "Site fridge, milk vat, cool room", weights: { 1: 1, 2: 2, 3: 3 } },
      { v: "lights",  title: "Lighting rig",         sub: "Tower lights, event wash, stage", weights: { 1: 0, 2: 2, 3: 3 } },
      { v: "comms",   title: "Audio / comms",        sub: "PA, radios, networking, CCTV",    weights: { 1: 1, 2: 2, 3: 2 } },
      { v: "heavy",   title: "EV / 3-phase / weld",  sub: "EV charging, 3φ machinery",       weights: { 1: 0, 2: 1, 3: 3 } },
    ],
  },
  {
    id: "duty",
    label: "Run time",
    question: "How long does it need to run between sun?",
    sub: "Drives battery sizing. Cloudy stretches and night work cost storage, not panels.",
    options: [
      { v: "half",  title: "Half-day bursts",     sub: "≤ 4 hr · day work, sun-tracking",     weights: { 1: 3, 2: 2, 3: 1 } },
      { v: "full",  title: "Full working day",    sub: "8–12 hr · standard site rhythm",      weights: { 1: 2, 2: 3, 3: 2 } },
      { v: "multi", title: "Continuous / 24-hr",  sub: "Lighting, refrigeration, comms on",   weights: { 1: 0, 2: 2, 3: 3 } },
    ],
  },
  {
    id: "tow",
    label: "Tow rig",
    question: "What's pulling it?",
    sub: "Tare and braked-tow rating constrain which platforms you can hitch.",
    options: [
      { v: "ute1",  title: "1-tonne ute",          sub: "Hilux SR, Ranger XL, Triton",       weights: { 1: 3, 2: 0, 3: 0 } },
      { v: "ute25", title: "2.5-tonne tow rated",  sub: "Ranger Wildtrak, Amarok, LDV T60",  weights: { 1: 2, 2: 3, 3: 1 } },
      { v: "heavy", title: "3.5 t+ / truck",       sub: "Heavy 4WD, Iveco, Hino",            weights: { 1: 1, 2: 2, 3: 3 } },
    ],
  },
];

const WIZ_TIERS = {
  1: {
    name: "Solo",
    slug: "Tier 01 · Single axle",
    price: 19500,
    hireDay: 150,
    blurb: "One operator. Off-grid bach, small builds, lifestyle blocks.",
    bullets: [
      "5–15 kWh LiFePO₄ · 3 kW pure sine inverter",
      "2 × 15 A outlets, USB-C PD, 12 V Anderson",
      "Tare ~520 kg · tows behind a 1-tonne ute",
    ],
  },
  2: {
    name: "Crew",
    slug: "Tier 02 · Tandem flagship",
    price: 36500,
    hireDay: 320,
    blurb: "Small teams. Mid builds, dairy, festivals, hospitality.",
    bullets: [
      "20–40 kWh LiFePO₄ · 5 kW split-phase inverter",
      "4 × 15 A · 1 × 32 A 3-phase · 12 V/24 V DC",
      "Tare ~1,150 kg · braked tandem · 2.5 t rig and up",
    ],
  },
  3: {
    name: "Command",
    slug: "Tier 03 · Tandem braked premium",
    price: 58000,
    hireDay: 520,
    blurb: "Big ops. Major sites, multi-day events, civil defence.",
    bullets: [
      "40–80 kWh LiFePO₄ · 10 kW split / 3-phase",
      "6 × 15 A · 2 × 32 A 3φ · EV optional · full DC",
      "Tare ~1,850 kg · 3.5 t+ tow vehicle required",
    ],
  },
};

function Wizard() {
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState({ crew: null, load: [], duty: null, tow: null });
  const [done, setDone] = React.useState(false);

  const current = WIZ_STEPS[step];
  const total = WIZ_STEPS.length;

  // Score tiers from current answers
  const score = React.useMemo(() => {
    const s = { 1: 0, 2: 0, 3: 0 };
    WIZ_STEPS.forEach(stp => {
      const a = answers[stp.id];
      if (!a) return;
      const picks = stp.multi ? a : [a];
      picks.forEach(v => {
        const opt = stp.options.find(o => o.v === v);
        if (!opt) return;
        s[1] += opt.weights[1];
        s[2] += opt.weights[2];
        s[3] += opt.weights[3];
      });
    });
    return s;
  }, [answers]);

  const winner = React.useMemo(() => {
    let top = 1, max = -1;
    [1, 2, 3].forEach(n => { if (score[n] > max) { max = score[n]; top = n; } });
    return top;
  }, [score]);

  // Plain-English reasons drawn from picked options
  const reasons = React.useMemo(() => {
    const r = [];
    if (answers.crew) {
      const o = WIZ_STEPS[0].options.find(x => x.v === answers.crew);
      r.push({ k: "Crew", v: o.title.toLowerCase() });
    }
    if (answers.load && answers.load.length) {
      const titles = answers.load.map(v => WIZ_STEPS[1].options.find(x => x.v === v).title.toLowerCase());
      r.push({ k: "Loads", v: titles.join(" · ") });
    }
    if (answers.duty) {
      const o = WIZ_STEPS[2].options.find(x => x.v === answers.duty);
      r.push({ k: "Duty cycle", v: o.title.toLowerCase() });
    }
    if (answers.tow) {
      const o = WIZ_STEPS[3].options.find(x => x.v === answers.tow);
      r.push({ k: "Tow rig", v: o.title.toLowerCase() });
    }
    return r;
  }, [answers]);

  const canAdvance = (() => {
    if (current.multi) return Array.isArray(answers[current.id]) && answers[current.id].length > 0;
    return !!answers[current.id];
  })();

  const pick = (stepId, value, multi) => {
    setAnswers(prev => {
      if (multi) {
        const list = Array.isArray(prev[stepId]) ? prev[stepId] : [];
        const next = list.includes(value) ? list.filter(v => v !== value) : [...list, value];
        return { ...prev, [stepId]: next };
      }
      return { ...prev, [stepId]: value };
    });
  };

  const next = () => {
    if (step < total - 1) setStep(step + 1);
    else setDone(true);
  };
  const prev = () => { if (step > 0) setStep(step - 1); };
  const reset = () => { setAnswers({ crew: null, load: [], duty: null, tow: null }); setStep(0); setDone(false); };

  const tier = WIZ_TIERS[winner];
  const totalScore = score[1] + score[2] + score[3] || 1;

  return (
    <section className="wiz section-pad" id="findyourfit">
      <div className="shell">
        <div className="wiz-head">
          <div>
            <div className="eyebrow">§ 10.5 — Sizing</div>
            <h2 className="kicker" style={{marginTop:14}}>Find <span style={{color:'var(--signal)'}}>your fit.</span></h2>
          </div>
          <p className="body-lg" style={{opacity:0.78}}>
            Four questions. We'll size you to a tier, explain why, and show what it costs to own or hire. Takes about thirty seconds. No email.
          </p>
        </div>

        <div className={`wiz-shell ${done ? 'is-done' : ''}`}>
          {/* Step rail */}
          <div className="wiz-rail" role="tablist" aria-label="Wizard progress">
            {WIZ_STEPS.map((s, i) => {
              const filled = done || i < step || (i === step && canAdvance);
              return (
                <button key={s.id} className={`wiz-rail-step ${i===step && !done?'active':''} ${filled?'filled':''}`}
                        onClick={() => { if (!done) setStep(i); }}
                        disabled={done}>
                  <span className="wiz-rail-num">0{i+1}</span>
                  <span className="wiz-rail-label">{s.label}</span>
                </button>
              );
            })}
            <button className={`wiz-rail-step result ${done?'active filled':''}`} disabled={!done}>
              <span className="wiz-rail-num">▶</span>
              <span className="wiz-rail-label">Result</span>
            </button>
          </div>

          {!done ? (
            <div className="wiz-body" key={current.id}>
              <div className="wiz-q">
                <div className="wiz-stepcount">Question {step+1} of {total}{current.multi ? ' · select all that apply' : ''}</div>
                <h3 className="wiz-question">{current.question}</h3>
                <p className="wiz-sub">{current.sub}</p>
              </div>

              <div className={`wiz-options ${current.multi ? 'multi' : ''}`}>
                {current.options.map(opt => {
                  const selected = current.multi
                    ? (answers[current.id] || []).includes(opt.v)
                    : answers[current.id] === opt.v;
                  return (
                    <button key={opt.v}
                      className={`wiz-opt ${selected?'selected':''}`}
                      onClick={() => pick(current.id, opt.v, current.multi)}
                      aria-pressed={selected}>
                      <div className="wiz-opt-check">
                        <span className="wiz-opt-check-mark" aria-hidden="true">{current.multi ? '✓' : '●'}</span>
                      </div>
                      <div className="wiz-opt-text">
                        <div className="wiz-opt-title">{opt.title}</div>
                        <div className="wiz-opt-sub">{opt.sub}</div>
                      </div>
                    </button>
                  );
                })}
              </div>

              <div className="wiz-nav">
                <button className="btn btn-outline-dark" onClick={prev} disabled={step===0}>← Back</button>
                <div className="wiz-nav-dots">
                  {WIZ_STEPS.map((_, i) => (
                    <span key={i} className={`wiz-dot ${i===step?'active':''} ${i<step?'done':''}`}/>
                  ))}
                </div>
                <button className="btn btn-dark" onClick={next} disabled={!canAdvance}>
                  {step === total-1 ? 'See result' : 'Next'} <ArrowRight size={14} stroke={2} className="arrow"/>
                </button>
              </div>
            </div>
          ) : (
            <div className="wiz-result">
              <div className="wiz-result-l">
                <div className="wiz-result-eyebrow">Recommended platform</div>
                <div className="wiz-result-slug">{tier.slug}</div>
                <h3 className="wiz-result-name">{tier.name}</h3>
                <p className="wiz-result-blurb">{tier.blurb}</p>

                <div className="wiz-result-bullets">
                  {tier.bullets.map((b,i) => (
                    <div className="wiz-bullet" key={i}>
                      <span className="wiz-bullet-dot"/>
                      <span>{b}</span>
                    </div>
                  ))}
                </div>

                <div className="wiz-result-prices">
                  <div className="wiz-price">
                    <div className="wiz-price-eyebrow">Buy from</div>
                    <div className="wiz-price-num">${tier.price.toLocaleString()}</div>
                    <div className="wiz-price-sub">NZD ex-GST · launch parity pricing</div>
                  </div>
                  <div className="wiz-price">
                    <div className="wiz-price-eyebrow">Or hire from</div>
                    <div className="wiz-price-num">${tier.hireDay}<span className="per">/day</span></div>
                    <div className="wiz-price-sub">All-in · no fuel</div>
                  </div>
                </div>

                <div className="wiz-cta-row">
                  <a href="#contact" className="btn btn-primary">Reserve a {tier.name} build <ArrowRight size={14} stroke={2} className="arrow"/></a>
                  <a href="#buyhire" className="btn btn-outline-dark">See hire terms</a>
                </div>
              </div>

              <div className="wiz-result-r">
                <div className="wiz-result-card">
                  <div className="wiz-card-head">
                    <span className="live-dot"/>
                    <span>FIT REPORT · GENERATED {new Date().toLocaleDateString('en-NZ').replace(/\//g,'.')}</span>
                  </div>

                  <div className="wiz-score-rows">
                    {[1,2,3].map(n => {
                      const t = WIZ_TIERS[n];
                      const pct = Math.round((score[n] / totalScore) * 100);
                      const isWin = n === winner;
                      return (
                        <div className={`wiz-score-row ${isWin?'win':''}`} key={n}>
                          <div className="wiz-score-name">
                            <span className="wiz-score-tier">T0{n}</span>
                            <span className="wiz-score-tname">{t.name}</span>
                            {isWin && <span className="wiz-score-badge">Best fit</span>}
                          </div>
                          <div className="wiz-score-bar"><span style={{width: `${pct}%`}}/></div>
                          <div className="wiz-score-pct">{pct}<span>%</span></div>
                        </div>
                      );
                    })}
                  </div>

                  <div className="wiz-reasons">
                    <div className="wiz-reasons-eyebrow">Inputs</div>
                    {reasons.map((r,i) => (
                      <div className="wiz-reason" key={i}>
                        <span className="wiz-reason-k">{r.k}</span>
                        <span className="wiz-reason-v">{r.v}</span>
                      </div>
                    ))}
                  </div>

                  <button className="wiz-restart" onClick={reset}>↺ Start over</button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

window.Wizard = Wizard;
