// ============================================================
// QBE Agentic stage views (right pane).
//
// Every view renders with the ProgressRail at the top and follows
// the QBE visual system:
//   - asymmetric 0 0 32px 0 corner radius on every primary card
//   - 4px cyan top stripe on the primary card (.qbe-stage-card)
//   - 1px #E1E4E8 hairline borders, no drop shadows
//   - Inter, sentence case, curly apostrophes, no emoji / exclamations
// ============================================================

// ---------------------------------------------------------------
// ProgressRail — 4 steps pinned to the top of each right-pane view.
// Current = navy bubble, done = cyan bubble with tick, upcoming = grey.
// ---------------------------------------------------------------
function ProgressRail({ currentIndex }) {
  return (
    <div className="progress-rail">
      {PROGRESS_STEPS.map((label, i) => {
        const state = i < currentIndex ? 'done' : i === currentIndex ? 'active' : 'upcoming';
        return (
          <React.Fragment key={label}>
            <div className={`rail-step rail-step--${state}`}>
              <div className="rail-bubble">
                {state === 'done'
                  ? <span className="rail-bubble__tick">{FilledIcons.tickFilled}</span>
                  : <span className="rail-bubble__num">{i + 1}</span>}
              </div>
              <div className="rail-label">{label}</div>
            </div>
            {i < PROGRESS_STEPS.length - 1 && (
              <div className={`rail-line ${i < currentIndex ? 'rail-line--done' : ''}`} />
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
}

// ---------------------------------------------------------------
// LivePriceBanner — sticky bottom of the view pane from USAGE onward.
// ---------------------------------------------------------------
function LivePriceBanner({ tier, vehicleLabel, suburb, price }) {
  return (
    <div className="live-price-banner">
      <div className="live-price-banner__inner">
        <div className="live-price-banner__text">
          <div className="live-price-banner__label">Current estimate</div>
          <div className="live-price-banner__price">
            ${price.displayed.toFixed(2)}
            <span className="live-price-banner__unit"> /{price.unit}</span>
          </div>
          <div className="live-price-banner__meta">{tier} · {vehicleLabel} · {suburb}</div>
        </div>
        <div className="live-price-banner__info" title="Updated live as you answer. Final quote shown at the end.">
          {FilledIcons.infoFilled}
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------
// Shared primitives
// ---------------------------------------------------------------

// Yes / No pill toggle. Blue-filled active side.
function YesNoToggle({ value, onChange, labels = ['Yes', 'No'] }) {
  return (
    <div className="yesno-toggle">
      {labels.map((label, i) => {
        const v = i === 0 ? 'yes' : 'no';
        const on = value === v;
        return (
          <button
            key={label}
            type="button"
            className={`yesno-toggle__side ${on ? 'yesno-toggle__side--on' : ''}`}
            onClick={() => onChange(v)}
          >
            {label}
          </button>
        );
      })}
    </div>
  );
}

// Filled-SVG icon in a navy-alt square tile. Used by product + usage cards.
function IconTile({ icon, size = 48, color = 'var(--cumulus-blue-deep)', bg = 'rgba(0,61,165,0.08)' }) {
  return (
    <div className="icon-tile" style={{ width: size, height: size, background: bg, color }}>
      {icon}
    </div>
  );
}

// ---------------------------------------------------------------
// Stage 1 — ProductTypeView
// ---------------------------------------------------------------
function ProductTypeView({ selected, onAction }) {
  return (
    <div className="stage-wrap">
      <div className="qbe-stage-card product-type-card">
        <h2 className="qbe-stage-heading">Choose your cover</h2>
        <p className="qbe-stage-sub">Select a product to start your quote. You can change this later.</p>

        <div className="product-type-grid">
          {PRODUCTS.map(p => {
            const isSelected = selected === p.label || (p.preselected && !selected);
            return (
              <button
                key={p.key}
                type="button"
                className={`product-tile ${isSelected ? 'product-tile--selected' : ''}`}
                onClick={() => onAction(p.label)}
                aria-pressed={isSelected}
              >
                {isSelected && (
                  <span className="product-tile__tick" aria-hidden="true">{FilledIcons.tickFilled}</span>
                )}
                <IconTile icon={FilledIcons[p.iconKey]} />
                <h3 className="product-tile__title">{p.label}</h3>
                <p className="product-tile__desc">{p.desc}</p>
                <span className="product-tile__from">
                  {p.fromLabel || `From $${p.from}/mo`}
                </span>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------
// Stage 2 — VehicleLookupView (shimmer + heritage triangle watermark)
// ---------------------------------------------------------------
function VehicleLookupView({ lookup }) {
  return (
    <div className="stage-wrap">
      <div className="qbe-stage-card vehicle-lookup">
        <div className="vehicle-lookup__watermark" aria-hidden="true">
          <QbeSymbol size={160} />
        </div>
        <div className="vehicle-lookup__inner">
          <h2 className="qbe-stage-heading">Finding your vehicle</h2>
          <p className="vehicle-lookup__sub">Pulling your vehicle details from NEVDIS…</p>
          <div className="shimmer-bars" aria-hidden="true">
            <span /><span /><span />
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------
// Stage 3 — VehicleConfirmView
// ---------------------------------------------------------------
function VehicleConfirmView({ lookup, checks, onNext }) {
  const [local, setLocal] = React.useState(checks);
  const set = (k, v) => setLocal(prev => ({ ...prev, [k]: v }));

  const KMS_OPTIONS = [
    'Up to 5,000 KMs',
    '5,000 – 10,000 KMs',
    '10,000 – 20,000 KMs',
    '20,000 – 30,000 KMs',
    'Over 30,000 KMs',
  ];

  return (
    <div className="stage-wrap">
      <div className="qbe-stage-card vehicle-confirm">
        <div className="vehicle-confirm__hero">
          <div className="vehicle-confirm__image">
            <div className="vehicle-confirm__image-frame">
              <img
                src="assets/vw-golf-2020.jpg"
                alt={`${lookup.displayTitle} — reference photo`}
                className="vehicle-confirm__photo"
                onError={(e) => {
                  // If the image isn't on disk yet, swap in the placeholder SVG.
                  const img = e.currentTarget;
                  if (img.dataset.fallbackShown) return;
                  img.dataset.fallbackShown = 'true';
                  img.style.display = 'none';
                  const fallback = img.nextElementSibling;
                  if (fallback) fallback.style.display = 'flex';
                }}
              />
              <div className="vehicle-confirm__image-fallback" aria-hidden="true">
                <svg viewBox="0 0 120 80" width="100%" height="100%" fill="none">
                  <path d="M10 52l6-14c1-2 3-4 6-4h42l12 12h24c4 0 7 3 7 7v8c0 2-2 4-4 4h-6a7 7 0 1 1-14 0H40a7 7 0 1 1-14 0H14c-2 0-4-2-4-4v-9z"
                        stroke="var(--cumulus-gray-300)" strokeWidth="1.6" />
                  <circle cx="33" cy="60" r="6" stroke="var(--cumulus-gray-300)" strokeWidth="1.6" />
                  <circle cx="87" cy="60" r="6" stroke="var(--cumulus-gray-300)" strokeWidth="1.6" />
                </svg>
              </div>
            </div>
            <div className="vehicle-confirm__image-micro">Car colours may vary</div>
          </div>

          <div className="vehicle-confirm__details">
            <h1 className="vehicle-confirm__title">{lookup.displayTitle}</h1>
            <div className="vehicle-confirm__meta">{lookup.seats} {lookup.body}</div>
            <div className="vehicle-confirm__meta">{lookup.engine}</div>
            <a className="vehicle-confirm__mismatch" href="#" onClick={(e) => e.preventDefault()}>
              These details don’t match my vehicle
            </a>
          </div>
        </div>

        <div className="vehicle-confirm__divider" />

        <div className="toggle-rows">
          <div className="toggle-row">
            <span className="toggle-row__label">Registered and roadworthy?</span>
            <YesNoToggle value={local.registered} onChange={(v) => set('registered', v)} />
          </div>
          <div className="toggle-row">
            <span className="toggle-row__label">Any existing damage?</span>
            <YesNoToggle value={local.damage} onChange={(v) => set('damage', v)} />
          </div>
          <div className="toggle-row">
            <span className="toggle-row__label">Bought in the last 6 months?</span>
            <YesNoToggle value={local.recentlyBought} onChange={(v) => set('recentlyBought', v)} />
          </div>
        </div>

        <div className="vehicle-confirm__kms">
          <label className="field-label">Kilometres per year</label>
          <select
            className="field-select"
            value={local.kmsPerYear}
            onChange={(e) => set('kmsPerYear', e.target.value)}
          >
            {KMS_OPTIONS.map(k => <option key={k} value={k}>{k}</option>)}
          </select>
        </div>

        <div className="stage-footer stage-footer--end">
          <button className="btn-next-navy" onClick={() => onNext(local)}>
            Next
          </button>
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------
// Stage 4 — GarageView
// ---------------------------------------------------------------
function GarageView({ garage, onSubmit }) {
  const [value, setValue] = React.useState(garage?.line || '');
  const [focused, setFocused] = React.useState(false);
  const [confirmed, setConfirmed] = React.useState(!!garage);
  const SUGGESTIONS = [
    '22 Sydney Street, Rose Bay NSW 2029',
    '14 New South Head Road, Rose Bay NSW 2029',
    '5/40 Dover Road, Rose Bay NSW 2029',
  ];
  const showMenu = focused && value.trim().length >= 2 && !confirmed;

  const pick = (s) => {
    setValue(s);
    setFocused(false);
    setConfirmed(true);
    // Slight delay so the reasoning panel can animate in before transitioning.
    setTimeout(() => onSubmit(s), 700);
  };

  const clear = () => {
    setValue('');
    setConfirmed(false);
  };

  return (
    <div className="stage-wrap">
      <div className="qbe-stage-card garage-card">
        <h2 className="qbe-stage-heading">Where is the car usually kept when not being driven?</h2>

        <div className={`address-input ${confirmed ? 'address-input--confirmed' : ''}`}>
          <span className="address-input__lead">{FilledIcons.mapPinFilled}</span>
          <input
            value={value}
            onChange={(e) => { setValue(e.target.value); setConfirmed(false); }}
            onFocus={() => setFocused(true)}
            onBlur={() => setTimeout(() => setFocused(false), 120)}
            placeholder="Start typing address…"
            aria-label="Garage address"
          />
          {value && (
            <button
              className="address-input__clear"
              type="button"
              onClick={clear}
              aria-label="Clear address"
            >
              {FilledIcons.xFilled}
            </button>
          )}
          {confirmed && (
            <span className="address-input__tick">{FilledIcons.tickFilled}</span>
          )}
          {showMenu && (
            <div className="address-input__menu">
              {SUGGESTIONS.map(s => (
                <button
                  key={s}
                  type="button"
                  className="address-input__menu-item"
                  onMouseDown={() => pick(s)}
                >
                  <span>{FilledIcons.mapPinFilled}</span>
                  {s}
                </button>
              ))}
            </div>
          )}
        </div>

        <div className="garage-card__help">
          <p className="garage-card__helper">If applicable, include your unit or apartment number, for example, Unit 5, 22 Sydney Street, Sydney</p>
          <a className="garage-card__notfound" href="#" onClick={(e) => e.preventDefault()}>
            I can’t find the address
          </a>
        </div>

        {confirmed && (
          <div className="reasoning-card">
            {GARAGE_MOCK_ADDRESS.reasoning}
          </div>
        )}
      </div>
    </div>
  );
}

// ---------------------------------------------------------------
// Stage 5 — UsageView
// ---------------------------------------------------------------
function UsageView({ value, onChange, onContinue }) {
  const USES = [
    { key: 'Private use',  icon: FilledIcons.carCloud },
    { key: 'Business use', icon: FilledIcons.briefcase },
    { key: 'Ridesharing',  icon: FilledIcons.carPeople },
  ];
  const FINANCE = [
    { key: 'No Finance', icon: FilledIcons.cardNo },
    { key: 'Finance',    icon: FilledIcons.card },
  ];

  return (
    <div className="stage-wrap">
      <div className="qbe-stage-card">
        <h2 className="qbe-stage-heading">How do you use your 2020 Volkswagen Golf?</h2>

        <div className="selection-row selection-row--3">
          {USES.map(u => {
            const on = value.primary === u.key;
            return (
              <button
                key={u.key}
                type="button"
                className={`selection-card ${on ? 'selection-card--on' : ''}`}
                onClick={() => onChange({ primary: u.key })}
                aria-pressed={on}
              >
                {on && <span className="selection-card__tick">{FilledIcons.tickFilled}</span>}
                <IconTile icon={u.icon} size={40} />
                <span className="selection-card__label">{u.key}</span>
              </button>
            );
          })}
        </div>
        <a className="inline-link" href="#" onClick={(e) => e.preventDefault()}>What’s the difference?</a>
      </div>

      <div className="qbe-stage-card">
        <h2 className="qbe-stage-heading">Is there any finance on this car?</h2>

        <div className="selection-row selection-row--2">
          {FINANCE.map(f => {
            const on = value.finance === f.key;
            return (
              <button
                key={f.key}
                type="button"
                className={`selection-card ${on ? 'selection-card--on' : ''}`}
                onClick={() => onChange({ finance: f.key })}
                aria-pressed={on}
              >
                {on && <span className="selection-card__tick">{FilledIcons.tickFilled}</span>}
                <IconTile icon={f.icon} size={40} />
                <span className="selection-card__label">{f.key}</span>
              </button>
            );
          })}
        </div>
        <a className="inline-link" href="#" onClick={(e) => e.preventDefault()}>Which applies?</a>
      </div>

      <div className="stage-footer stage-footer--end">
        <button className="btn-next-navy" onClick={onContinue}>Continue</button>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------
// Stage 6 — MainDriverView
// ---------------------------------------------------------------
function MainDriverView({ value, onChange, onCleanRecord }) {
  const [local, setLocal] = React.useState(value || { dob: '', gender: 'Prefer not to say', licenceYears: '5+ years', history: [] });

  const set = (k, v) => {
    const next = { ...local, [k]: v };
    setLocal(next);
    onChange(next);
  };

  const HISTORY_ITEMS = [
    'Accidents or claims (any fault)',
    'Licence suspended, cancelled or restricted',
    'Charged with or convicted of a criminal offence',
    'Had an insurance claim denied for fraud or dishonesty',
    'Insurance cancelled or refused by another insurer',
    'More than 0 demerit points',
  ];
  const LICENCE_YEARS = ['Less than 1 year', '1–2 years', '3–4 years', '5+ years'];

  const toggleHistory = (item) => {
    const on = local.history.includes(item);
    const next = { ...local, history: on ? local.history.filter(h => h !== item) : [...local.history, item] };
    setLocal(next);
    onChange(next);
  };

  return (
    <div className="stage-wrap">
      <div className="qbe-stage-card">
        <h2 className="qbe-stage-heading">Main Driver</h2>

        <div className="field-row">
          <div className="field">
            <label className="field-label">Date of birth</label>
            <input
              className="field-input"
              placeholder="dd/mm/yyyy"
              value={local.dob}
              onChange={(e) => set('dob', e.target.value)}
            />
          </div>
          <div className="field">
            <label className="field-label">Gender</label>
            <div className="pill-toggle pill-toggle--3">
              {['Male', 'Female', 'Prefer not to say'].map(g => (
                <button
                  key={g}
                  type="button"
                  className={`pill-toggle__side ${local.gender === g ? 'pill-toggle__side--on' : ''}`}
                  onClick={() => set('gender', g)}
                >{g}</button>
              ))}
            </div>
          </div>
        </div>

        <div className="field">
          <label className="field-label">For how many years has this driver held a full, including provisional, Australian driver’s licence?</label>
          <select
            className="field-select"
            value={local.licenceYears}
            onChange={(e) => set('licenceYears', e.target.value)}
          >
            {LICENCE_YEARS.map(y => <option key={y} value={y}>{y}</option>)}
          </select>
        </div>
      </div>

      <div className="qbe-stage-card">
        <h3 className="qbe-stage-subheading">In the last 3 years, any of these apply?</h3>

        <ul className="history-checklist">
          {HISTORY_ITEMS.map(item => (
            <li key={item}>
              <label className="history-checklist__row">
                <input
                  type="checkbox"
                  checked={local.history.includes(item)}
                  onChange={() => toggleHistory(item)}
                />
                <span>{item}</span>
              </label>
            </li>
          ))}
        </ul>

        <button className="btn-none-of-above" onClick={onCleanRecord}>
          None of the above
        </button>
        <a className="inline-link muted" href="#" onClick={(e) => e.preventDefault()}>
          I need to declare something
        </a>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------
// Stage 7 — OtherDriversView
// ---------------------------------------------------------------
function OtherDriversView({ mainDriver, value, onChangeEmail }) {
  // Derive the "35 years old" line from dob if present, otherwise use a
  // sensible mock so the summary still reads well on the happy path.
  const ageLine = mainDriver?.dob ? `${mainDriver.licenceYears} licensed` : '35 years old, clean record, 5+ years licensed';

  return (
    <div className="stage-wrap">
      <div className="qbe-stage-card">
        <div className="driver-summary">
          <div className="driver-summary__heading">Main Driver</div>
          <div className="driver-summary__line">
            {mainDriver?.dob
              ? `${mainDriver.gender || 'Driver'}, ${mainDriver.licenceYears || '5+ years'} licensed`
              : ageLine}
          </div>
          <button className="driver-summary__edit" type="button">
            Edit <span aria-hidden="true">✎</span>
          </button>
        </div>
      </div>

      <div className="qbe-stage-card">
        <div className="add-driver">
          <h3 className="qbe-stage-subheading">Add more drivers?</h3>
          <a className="inline-link" href="#" onClick={(e) => e.preventDefault()}>
            Do I need to list all drivers?
          </a>
          <button className="btn-outline-add" type="button">
            <Icon name="plus" size={16} /> Add
          </button>
        </div>
      </div>

      <div className="inline-field-card">
        <label className="field-label">Email your quote (optional)</label>
        <input
          className="field-input"
          type="email"
          placeholder="name@example.com"
          value={value.email}
          onChange={(e) => onChangeEmail(e.target.value)}
        />
      </div>
    </div>
  );
}

// ---------------------------------------------------------------
// Stage 8 — QuoteView (the payoff)
// ---------------------------------------------------------------
function QuoteView({ quote, price, targetBudget, onChange, onContinue }) {
  const FEATURE_TICKS = [
    '2024 Finder Green Insurer of the Year Award winner',
    'Our highest level of cover, including accident damage, fire and theft, weather events',
    'Choice of repairer from the Cumulus Accredited network',
  ];

  const tabs = [
    { key: 'Comprehensive',      label: 'Comprehensive' },
    { key: 'ThirdPartyProperty', label: 'Third Party Property Damage' },
  ];

  // True when the user negotiated a budget and the adjustment is live.
  const hasBudgetAdjustment = (quote.budgetDiscount || 0) > 0 && targetBudget != null;

  return (
    <div className="stage-wrap">
      <div className="qbe-stage-card quote-card">

        {/* Tier tabs */}
        <div className="quote-tabs" role="tablist">
          {tabs.map(t => {
            const on = quote.tier === t.key;
            return (
              <button
                key={t.key}
                role="tab"
                aria-selected={on}
                className={`quote-tab ${on ? 'quote-tab--on' : ''}`}
                onClick={() => onChange({ tier: t.key })}
              >
                {on && <span className="quote-tab__tick">{FilledIcons.tickFilled}</span>}
                <span>{t.label}</span>
              </button>
            );
          })}
        </div>

        {/* Price hero */}
        <div className="quote-hero">
          {hasBudgetAdjustment && (
            <div className="quote-hero__budget-eyebrow">
              Matched to your ${Number(targetBudget).toFixed(0)} budget
            </div>
          )}
          <div className="quote-hero__price">
            <span className="quote-hero__amt">${price.displayed.toFixed(2)}</span>
            <span className="quote-hero__per"> / {price.unit === 'mo' ? 'month' : 'year'}</span>
          </div>
          <div className="quote-hero__sub">
            ${(price.monthly * 12).toFixed(2)} for 12 months · incl. GST and government charges
          </div>
          <div className="quote-hero__badge" aria-hidden="true">
            <div className="finder-badge">
              <div className="finder-badge__inner">
                <div className="finder-badge__label">Finder</div>
                <div className="finder-badge__rule" />
                <div className="finder-badge__value">Green Insurer</div>
                <div className="finder-badge__years">2020–2024</div>
              </div>
            </div>
          </div>
        </div>

        <div className="pay-toggle">
          {[
            { key: 'annual',  label: 'Pay annually'  },
            { key: 'monthly', label: 'Pay monthly' },
          ].map(f => {
            const on = quote.frequency === f.key;
            return (
              <button
                key={f.key}
                type="button"
                className={`pay-toggle__side ${on ? 'pay-toggle__side--on' : ''}`}
                onClick={() => onChange({ frequency: f.key })}
              >{f.label}</button>
            );
          })}
        </div>

        <ul className="feature-ticks">
          {FEATURE_TICKS.map(ft => (
            <li key={ft}>
              <span className="feature-ticks__tick">{FilledIcons.tickFilled}</span>
              <span>{ft}</span>
            </li>
          ))}
        </ul>

        <div className="discount-callout">
          <strong>A $75 discount has been applied</strong>
          <span>New Comprehensive Car Insurance policies purchased online receive a $75 discount.</span>
        </div>

        {hasBudgetAdjustment && (
          <div className="discount-callout discount-callout--budget" role="status" aria-live="polite">
            <div className="discount-callout__eyebrow">Adjusted for you</div>
            <strong>Budget-friendly adjustment applied</strong>
            <span>
              −${Number(quote.budgetDiscount).toFixed(2)}/mo to match your ${Number(targetBudget).toFixed(0)} budget
              {' '}· excess set to ${Number(quote.excess).toLocaleString()}
            </span>
          </div>
        )}

        {/* Adjust your cover */}
        <h3 className="qbe-stage-subheading">Adjust your cover</h3>

        <div className="adjust-group">
          <label className="field-label">Excess</label>
          <input
            type="range"
            className="excess-slider"
            min={0}
            max={EXCESS_TICKS.length - 1}
            step={1}
            value={EXCESS_TICKS.indexOf(quote.excess)}
            onChange={(e) => onChange({ excess: EXCESS_TICKS[parseInt(e.target.value, 10)] })}
          />
          <div className="excess-ticks">
            {EXCESS_TICKS.map(t => (
              <span key={t} className={t === quote.excess ? 'excess-ticks__item excess-ticks__item--on' : 'excess-ticks__item'}>
                ${t.toLocaleString()}
              </span>
            ))}
          </div>
          <p className="field-helper">Higher excess = lower monthly cost</p>
        </div>

        <div className="adjust-group">
          <label className="field-label" htmlFor="sumInsured">Car sum insured</label>
          <input
            id="sumInsured"
            className="field-input"
            type="number"
            value={quote.sumInsured}
            step={500}
            min={10000}
            max={100000}
            onChange={(e) => onChange({ sumInsured: parseInt(e.target.value, 10) || 0 })}
          />
        </div>

        <div className="adjust-group">
          <label className="field-label">Optional extras</label>
          <ul className="extras-list">
            {EXTRAS.map(x => {
              const on = quote.extras.includes(x.key);
              return (
                <li key={x.key}>
                  <label className={`extra-row ${on ? 'extra-row--on' : ''}`}>
                    <input
                      type="checkbox"
                      checked={on}
                      onChange={() => {
                        const next = on ? quote.extras.filter(k => k !== x.key) : [...quote.extras, x.key];
                        onChange({ extras: next });
                      }}
                    />
                    <span className="extra-row__label">{x.key}</span>
                    <span className="extra-row__price">+${x.price}/mo</span>
                  </label>
                </li>
              );
            })}
          </ul>
        </div>

        <div className="stage-footer stage-footer--split">
          <button className="btn-blue-outline" type="button">Email quote</button>
          <button className="btn-yellow-filled" type="button" onClick={onContinue}>Continue</button>
        </div>

      </div>
    </div>
  );
}

// ---------------------------------------------------------------
// Stage 9 — CheckoutView (preserved; wired to the new answers shape)
// ---------------------------------------------------------------
function CheckoutView({ answers, price, onSubmit }) {
  const { quote, vehicle, garage, mainDriver } = answers;
  const [form, setForm] = React.useState({
    firstName: 'Chloe',
    lastName:  '',
    dob:       mainDriver?.dob || '',
    email:     answers.otherDrivers?.email || '',
    mobile:    '',
    address:   garage?.line || '',
    startDate: '',
    rego:      vehicle?.rego || '',
    agreeTerms: false,
    agreePrivacy: false,
  });
  const set = (k, v) => setForm(p => ({ ...p, [k]: v }));
  const canSubmit = form.firstName && form.lastName && form.email && form.mobile && form.agreeTerms && form.agreePrivacy;
  const tierLabel = quote.tier === 'ThirdPartyProperty' ? 'Third Party Property Damage' : 'Comprehensive Car Insurance';

  return (
    <div className="stage-wrap">
      <div className="qbe-stage-card">
        <h2 className="qbe-stage-heading">Finalise your cover</h2>
        <p className="qbe-stage-sub">Last few details, then you’re protected.</p>

        <div className="checkout-summary">
          <div>
            <div className="checkout-summary__product">{tierLabel}</div>
            <div className="checkout-summary__meta">
              {vehicle?.lookup?.displayTitle || 'VW Golf'} · {garage?.suburb || 'Rose Bay'} · Excess ${quote.excess}
            </div>
          </div>
          <div className="checkout-summary__price">${price.displayed.toFixed(2)} /{price.unit}</div>
        </div>

        <div className="field-row">
          <div className="field">
            <label className="field-label">First name</label>
            <input className="field-input" value={form.firstName} onChange={e => set('firstName', e.target.value)} />
          </div>
          <div className="field">
            <label className="field-label">Last name</label>
            <input className="field-input" value={form.lastName} onChange={e => set('lastName', e.target.value)} />
          </div>
        </div>
        <div className="field">
          <label className="field-label">Date of birth</label>
          <input className="field-input" placeholder="dd/mm/yyyy" value={form.dob} onChange={e => set('dob', e.target.value)} />
        </div>
        <div className="field-row">
          <div className="field">
            <label className="field-label">Email</label>
            <input className="field-input" type="email" value={form.email} onChange={e => set('email', e.target.value)} />
          </div>
          <div className="field">
            <label className="field-label">Mobile</label>
            <input className="field-input" type="tel" value={form.mobile} onChange={e => set('mobile', e.target.value)} />
          </div>
        </div>
        <div className="field">
          <label className="field-label">Residential address</label>
          <input className="field-input" value={form.address} onChange={e => set('address', e.target.value)} placeholder="Start typing address…" />
        </div>
        <div className="field-row">
          <div className="field">
            <label className="field-label">Cover start date</label>
            <input className="field-input" type="date" value={form.startDate} onChange={e => set('startDate', e.target.value)} />
          </div>
          <div className="field">
            <label className="field-label">Vehicle rego</label>
            <input className="field-input" value={form.rego} onChange={e => set('rego', e.target.value.toUpperCase())} placeholder="e.g. BXA58T" />
          </div>
        </div>

        <div className="consents">
          <label>
            <input type="checkbox" checked={form.agreeTerms} onChange={e => set('agreeTerms', e.target.checked)} />
            <span>I agree to the Cumulus Terms and Conditions and confirm I have read the Product Disclosure Statement (PDS) and Target Market Determination (TMD).</span>
          </label>
          <label>
            <input type="checkbox" checked={form.agreePrivacy} onChange={e => set('agreePrivacy', e.target.checked)} />
            <span>I consent to Cumulus collecting and using my personal information as outlined in the Cumulus Privacy Policy.</span>
          </label>
        </div>

        <button
          className="btn-yellow-filled stage-footer__full"
          onClick={onSubmit}
          disabled={!canSubmit}
        >
          Submit application
        </button>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------
// Stage 10 — ConfirmationView
// ---------------------------------------------------------------
function ConfirmationView({ answers, price }) {
  const { quote, vehicle, garage } = answers;
  const ref = React.useMemo(() => `CUM-2026-${Math.floor(100000 + Math.random() * 900000)}`, []);
  const tierLabel = quote.tier === 'ThirdPartyProperty' ? 'Third Party Property Damage' : 'Comprehensive Car Insurance';

  return (
    <div className="stage-wrap">
      <div className="qbe-stage-card confirm-card">
        <div className="confirm-check" aria-hidden="true">{FilledIcons.tickFilled}</div>
        <h2 className="qbe-stage-heading centered">Welcome to Cumulus</h2>
        <p className="qbe-stage-sub centered">Your application has been submitted successfully.</p>

        <div className="confirm-box">
          <div className="confirm-row"><span>Product</span><span>{tierLabel}</span></div>
          <div className="confirm-row"><span>Vehicle</span><span>{vehicle?.lookup?.displayTitle || '2020 Volkswagen Golf'}</span></div>
          <div className="confirm-row"><span>Garage</span><span>{garage?.suburb || 'Rose Bay'}, {garage?.state || 'NSW'}</span></div>
          <div className="confirm-row"><span>Monthly premium</span><span>${price.monthly.toFixed(2)}</span></div>
          <div className="confirm-row"><span>Application ref</span><span>{ref}</span></div>
          <div className="confirm-row"><span>Standard excess</span><span>${quote.excess}</span></div>
        </div>

        <div className="confirm-next">
          <h4>Next steps</h4>
          <ul>
            <li><span>{FilledIcons.tickFilled}</span> Confirmation email sent to your inbox with your Certificate of Currency.</li>
            <li><span>{FilledIcons.tickFilled}</span> Download the My Cumulus app to manage your policy.</li>
            <li><span>{FilledIcons.tickFilled}</span> Save our 24/7 claims line: <b>133 723</b>.</li>
          </ul>
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------
// AgenticSearchBand — entry ramp on the homepage. Preserved.
// ---------------------------------------------------------------
function AgenticSearchBand({ onStartChat }) {
  const [value, setValue] = React.useState('');
  const suggestions = ['Get a car quote', 'Insurance for my new home', 'Make a claim', 'Help & support'];

  const send = (v) => {
    const msg = (v ?? value).trim();
    if (!msg) return;
    onStartChat(msg);
    setValue('');
  };

  return (
    <div className="agentic-search-band">
      <div className="inner">
        <div className="card">
          <div className="row">
            <div className="logo-round">
              <QbeSymbol size={30} />
            </div>
            <div className="input-wrap">
              <input
                value={value}
                onChange={e => setValue(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && send()}
                placeholder="What can we help you with today?"
              />
              <button onClick={() => send()}>
                <Icon name="send" size={16} />
              </button>
            </div>
          </div>
          <div className="suggestions">
            {suggestions.map(s => (
              <button key={s} className="sug" onClick={() => send(s)}>{s}</button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  ProgressRail,
  LivePriceBanner,
  YesNoToggle,
  IconTile,
  ProductTypeView,
  VehicleLookupView,
  VehicleConfirmView,
  GarageView,
  UsageView,
  MainDriverView,
  OtherDriversView,
  QuoteView,
  CheckoutView,
  ConfirmationView,
  AgenticSearchBand,
});
