/* IGI — Multi-step Quote Flow */

function QuoteFlow({ navigate }) {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({
    product: 'motor',
    plan: 'standard',
    addons: ['roadside'],
    vehicle: { make: 'Toyota', model: 'Corolla Altis 1.6', year: '2024', value: 4500000, city: 'Karachi' },
    driver: { name: '', cnic: '', mobile: '', email: '', dob: '1990-01-01', license: '5+ years' },
    coverStart: '2026-05-15',
  });
  const setField = (path, val) => {
    setData(d => {
      const next = { ...d };
      const keys = path.split('.');
      let cur = next;
      for (let i = 0; i < keys.length - 1; i++) {
        cur[keys[i]] = { ...cur[keys[i]] };
        cur = cur[keys[i]];
      }
      cur[keys[keys.length - 1]] = val;
      return next;
    });
  };

  const steps = ['What to insure', 'Vehicle details', 'Choose plan', 'Add-ons', 'Your details', 'Review & pay'];
  const next = () => setStep(s => Math.min(steps.length - 1, s + 1));
  const back = () => setStep(s => Math.max(0, s - 1));

  // Premium calc (illustrative)
  const basePrices = { thirdparty: 2500, standard: 18500, comp: 28900 };
  const planPrice = basePrices[data.plan === 'thirdparty' ? 'thirdparty' : data.plan === 'comp' ? 'comp' : 'standard'];
  const addonPrices = { roadside: 1800, accident: 1200, depreciation: 3400, replacement: 2100 };
  const addonsTotal = data.addons.reduce((s, a) => s + (addonPrices[a] || 0), 0);
  const tax = Math.round((planPrice + addonsTotal) * 0.13);
  const total = planPrice + addonsTotal + tax;

  return (
    <section style={{ padding: '40px 0 80px', background: 'var(--ink-50)', minHeight: '90vh' }}>
      <div className="container" style={{ maxWidth: 1100 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24, flexWrap: 'wrap', gap: 16 }}>
          <div>
            <div className="eyebrow">Quote builder</div>
            <h1 className="h-2" style={{ marginTop: 4 }}>Get your motor insurance quote</h1>
          </div>
          <button className="btn btn-ghost btn-sm" onClick={() => navigate('home')}>
            <I.X size={14} /> Cancel
          </button>
        </div>

        {/* Stepper */}
        <div className="card" style={{ padding: '20px 24px', marginBottom: 24, background: 'white' }}>
          <div className="stepper">
            {steps.map((label, i) => (
              <React.Fragment key={i}>
                <div className={`stepper-dot ${i === step ? 'active' : i < step ? 'done' : ''}`}>
                  <span className="num">{i < step ? <I.Check size={14} /> : i + 1}</span>
                  <span style={{
                    fontSize: 13, fontWeight: 600,
                    color: i === step ? 'var(--navy-800)' : i < step ? 'var(--blue-700)' : 'var(--ink-400)',
                    display: 'none',
                  }} className="step-label">{label}</span>
                </div>
                {i < steps.length - 1 && <div className="stepper-line" />}
              </React.Fragment>
            ))}
          </div>
          <div style={{ marginTop: 12, fontSize: 13, color: 'var(--ink-500)' }}>
            Step {step + 1} of {steps.length} — <strong style={{ color: 'var(--navy-800)' }}>{steps[step]}</strong>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: 24 }} className="quote-grid">
          {/* Main step content */}
          <div className="card" style={{ padding: 32, background: 'white', minHeight: 480 }}>
            {step === 0 && <Step0 data={data} setField={setField} />}
            {step === 1 && <Step1 data={data} setField={setField} />}
            {step === 2 && <Step2 data={data} setField={setField} />}
            {step === 3 && <Step3 data={data} setField={setField} />}
            {step === 4 && <Step4 data={data} setField={setField} />}
            {step === 5 && <Step5 data={data} total={total} navigate={navigate} />}

            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 32, paddingTop: 20, borderTop: '1px solid var(--ink-200)' }}>
              <button className="btn btn-ghost" onClick={back} disabled={step === 0} style={{ opacity: step === 0 ? 0.4 : 1 }}>
                <I.ChevronLeft size={14} /> Back
              </button>
              {step < steps.length - 1 ? (
                <button className="btn btn-accent" onClick={next}>Continue <I.ArrowRight size={14} /></button>
              ) : (
                <button className="btn btn-accent btn-lg" onClick={() => alert('Demo: payment gateway would open here')}>
                  Pay PKR {total.toLocaleString()} <I.ArrowRight size={14} />
                </button>
              )}
            </div>
          </div>

          {/* Sidebar — running summary */}
          <div>
            <div className="card" style={{ padding: 24, background: 'white', position: 'sticky', top: 100 }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink-700)', marginBottom: 14 }}>Your quote so far</div>
              <Row label="Product" value="Motor" />
              <Row label="Vehicle" value={`${data.vehicle.make} ${data.vehicle.year}`} />
              <Row label="City" value={data.vehicle.city} />
              <Row label="Plan" value={data.plan === 'comp' ? 'Comprehensive Plus' : data.plan === 'thirdparty' ? 'Third Party' : 'Standard'} />

              <div style={{ borderTop: '1px solid var(--ink-200)', paddingTop: 14, marginTop: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
                <Line label="Base premium" value={`PKR ${planPrice.toLocaleString()}`} />
                <Line label={`Add-ons (${data.addons.length})`} value={`PKR ${addonsTotal.toLocaleString()}`} />
                <Line label="Govt. tax (13%)" value={`PKR ${tax.toLocaleString()}`} small />
              </div>

              <div style={{ borderTop: '1px dashed var(--ink-200)', paddingTop: 16, marginTop: 14, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <span style={{ fontSize: 13, color: 'var(--ink-500)' }}>Total annual</span>
                <span><span style={{ fontSize: 11, color: 'var(--ink-500)', fontWeight: 600, marginRight: 4 }}>PKR</span><span className="serif" style={{ fontSize: 26, color: 'var(--navy-800)' }}>{total.toLocaleString()}</span></span>
              </div>
              <div style={{ marginTop: 8, fontSize: 12, color: 'var(--success)', fontWeight: 600 }}>
                or 12 monthly installments of PKR {Math.round(total / 12).toLocaleString()}
              </div>

              <div style={{ marginTop: 20, padding: 14, background: 'var(--blue-50)', borderRadius: 10, fontSize: 12, color: 'var(--blue-700)', display: 'flex', gap: 10 }}>
                <I.Sparkles size={16} style={{ flexShrink: 0, marginTop: 1 }} />
                <span>Save 8% by paying annually instead of monthly.</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 920px) { .quote-grid { grid-template-columns: 1fr !important; } }
        @media (min-width: 921px) { .step-label { display: inline !important; } }
      `}</style>
    </section>
  );
}

function Row({ label, value }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontSize: 13 }}>
      <span style={{ color: 'var(--ink-500)' }}>{label}</span>
      <span style={{ fontWeight: 600 }}>{value}</span>
    </div>
  );
}
function Line({ label, value, small }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: small ? 12 : 14 }}>
      <span style={{ color: 'var(--ink-500)' }}>{label}</span>
      <span style={{ fontWeight: 600 }}>{value}</span>
    </div>
  );
}

function Step0({ data, setField }) {
  const opts = [
    { id: 'motor', i: I.Car, l: 'Motor / Auto', d: 'Cars, bikes, commercial' },
    { id: 'home', i: I.Home, l: 'Home', d: 'Building & contents' },
    { id: 'travel', i: I.Plane, l: 'Travel', d: 'Trip cover, schengen' },
    { id: 'health', i: I.Heart, l: 'Health', d: 'Individual / family' },
  ];
  return (
    <>
      <h2 style={{ fontSize: 24, fontWeight: 700, marginBottom: 8 }}>What would you like to insure?</h2>
      <p style={{ color: 'var(--ink-500)', marginBottom: 24 }}>Pick a category to get started. You can always add more policies later from your dashboard.</p>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12 }}>
        {opts.map(o => {
          const sel = data.product === o.id;
          return (
            <button key={o.id} onClick={() => setField('product', o.id)} style={{
              padding: 24, border: sel ? '2px solid var(--blue-600)' : '1px solid var(--ink-200)',
              borderRadius: 12, background: sel ? 'var(--blue-50)' : 'white',
              display: 'flex', alignItems: 'center', gap: 16, textAlign: 'left',
              transition: 'all 0.15s ease',
            }}>
              <span style={{ width: 48, height: 48, borderRadius: 10, background: sel ? 'var(--blue-600)' : 'var(--ink-100)', color: sel ? 'white' : 'var(--ink-700)', display: 'grid', placeItems: 'center' }}>
                <o.i size={22} />
              </span>
              <div>
                <div style={{ fontSize: 16, fontWeight: 700 }}>{o.l}</div>
                <div style={{ fontSize: 13, color: 'var(--ink-500)' }}>{o.d}</div>
              </div>
              {sel && <I.CheckCircle size={20} style={{ marginLeft: 'auto', color: 'var(--blue-600)' }} />}
            </button>
          );
        })}
      </div>
    </>
  );
}

function Step1({ data, setField }) {
  return (
    <>
      <h2 style={{ fontSize: 24, fontWeight: 700, marginBottom: 8 }}>Tell us about your vehicle</h2>
      <p style={{ color: 'var(--ink-500)', marginBottom: 24 }}>This helps us calculate your premium accurately.</p>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <Field label="Make">
          <select className="field-select" value={data.vehicle.make} onChange={e => setField('vehicle.make', e.target.value)}>
            <option>Toyota</option><option>Honda</option><option>Suzuki</option><option>Hyundai</option><option>Kia</option><option>MG</option><option>BMW</option><option>Mercedes-Benz</option>
          </select>
        </Field>
        <Field label="Model">
          <input className="field-input" value={data.vehicle.model} onChange={e => setField('vehicle.model', e.target.value)} />
        </Field>
        <Field label="Year">
          <select className="field-select" value={data.vehicle.year} onChange={e => setField('vehicle.year', e.target.value)}>
            {Array.from({ length: 12 }, (_, i) => 2026 - i).map(y => <option key={y}>{y}</option>)}
          </select>
        </Field>
        <Field label="Registration city">
          <select className="field-select" value={data.vehicle.city} onChange={e => setField('vehicle.city', e.target.value)}>
            <option>Karachi</option><option>Lahore</option><option>Islamabad</option><option>Rawalpindi</option><option>Faisalabad</option><option>Peshawar</option><option>Multan</option>
          </select>
        </Field>
        <div style={{ gridColumn: 'span 2' }}>
          <Field label="Estimated market value (PKR)">
            <input className="field-input" type="number" value={data.vehicle.value} onChange={e => setField('vehicle.value', +e.target.value)} />
            <div style={{ marginTop: 8, fontSize: 12, color: 'var(--ink-500)' }}>
              💡 Based on PakWheels.com, a {data.vehicle.year} {data.vehicle.make} {data.vehicle.model} is currently valued at <strong>PKR {(data.vehicle.value).toLocaleString()}</strong>.
            </div>
          </Field>
        </div>
      </div>
    </>
  );
}

function Step2({ data, setField }) {
  const plans = [
    { id: 'thirdparty', name: 'Third Party', price: 2500, features: ['Mandatory legal cover', 'Up to PKR 20L liability'] },
    { id: 'standard', name: 'Standard', price: 18500, features: ['Accidental damage', 'Theft & fire', '120+ workshops'], popular: true },
    { id: 'comp', name: 'Comprehensive Plus', price: 28900, features: ['Everything in Standard', 'Zero depreciation', 'Roadside 24/7'] },
  ];
  return (
    <>
      <h2 style={{ fontSize: 24, fontWeight: 700, marginBottom: 8 }}>Choose your plan</h2>
      <p style={{ color: 'var(--ink-500)', marginBottom: 24 }}>You can switch plans any time before purchasing.</p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {plans.map(p => {
          const sel = data.plan === p.id;
          return (
            <button key={p.id} onClick={() => setField('plan', p.id)} style={{
              padding: 20, border: sel ? '2px solid var(--blue-600)' : '1px solid var(--ink-200)',
              borderRadius: 12, background: sel ? 'var(--blue-50)' : 'white',
              display: 'flex', alignItems: 'center', gap: 16, textAlign: 'left',
            }}>
              <span style={{
                width: 22, height: 22, borderRadius: '50%',
                border: sel ? '6px solid var(--blue-600)' : '2px solid var(--ink-300)',
                background: 'white', flexShrink: 0,
              }} />
              <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <span style={{ fontSize: 17, fontWeight: 700 }}>{p.name}</span>
                  {p.popular && <span className="badge badge-blue">POPULAR</span>}
                </div>
                <div style={{ fontSize: 13, color: 'var(--ink-500)', marginTop: 4 }}>
                  {p.features.join(' · ')}
                </div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div className="serif" style={{ fontSize: 24, color: 'var(--navy-800)' }}>{p.price.toLocaleString()}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-500)' }}>PKR / year</div>
              </div>
            </button>
          );
        })}
      </div>
    </>
  );
}

function Step3({ data, setField }) {
  const addons = [
    { id: 'roadside', i: I.Wrench, l: 'Roadside assistance', d: '24/7 towing & emergency help', p: 1800 },
    { id: 'accident', i: I.User, l: 'Personal accident cover', d: 'Up to PKR 10L for driver & passengers', p: 1200 },
    { id: 'depreciation', i: I.Sparkles, l: 'Zero depreciation', d: 'No deduction on parts during claim', p: 3400 },
    { id: 'replacement', i: I.Car, l: 'Replacement vehicle', d: 'Rental car for 14 days during repair', p: 2100 },
  ];
  const toggle = (id) => {
    const a = data.addons.includes(id) ? data.addons.filter(x => x !== id) : [...data.addons, id];
    setField('addons', a);
  };
  return (
    <>
      <h2 style={{ fontSize: 24, fontWeight: 700, marginBottom: 8 }}>Anything to add?</h2>
      <p style={{ color: 'var(--ink-500)', marginBottom: 24 }}>Optional extras to tailor your cover.</p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {addons.map(a => {
          const sel = data.addons.includes(a.id);
          return (
            <button key={a.id} onClick={() => toggle(a.id)} style={{
              padding: 18, border: sel ? '2px solid var(--blue-600)' : '1px solid var(--ink-200)',
              borderRadius: 10, background: sel ? 'var(--blue-50)' : 'white',
              display: 'flex', alignItems: 'center', gap: 14, textAlign: 'left',
            }}>
              <span style={{
                width: 22, height: 22, borderRadius: 6, flexShrink: 0,
                background: sel ? 'var(--blue-600)' : 'white',
                border: sel ? 0 : '2px solid var(--ink-300)',
                display: 'grid', placeItems: 'center', color: 'white',
              }}>{sel && <I.Check size={14} />}</span>
              <span style={{ width: 38, height: 38, borderRadius: 8, background: 'var(--ink-100)', color: 'var(--navy-800)', display: 'grid', placeItems: 'center' }}>
                <a.i size={18} />
              </span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 15, fontWeight: 700 }}>{a.l}</div>
                <div style={{ fontSize: 13, color: 'var(--ink-500)' }}>{a.d}</div>
              </div>
              <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--blue-700)' }}>+PKR {a.p.toLocaleString()}</div>
            </button>
          );
        })}
      </div>
    </>
  );
}

function Step4({ data, setField }) {
  return (
    <>
      <h2 style={{ fontSize: 24, fontWeight: 700, marginBottom: 8 }}>Your details</h2>
      <p style={{ color: 'var(--ink-500)', marginBottom: 24 }}>We use this to issue the policy and contact you about claims.</p>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <div style={{ gridColumn: 'span 2' }}>
          <Field label="Full name (as on CNIC)">
            <input className="field-input" placeholder="e.g. Ahmed Faraz Khan" value={data.driver.name} onChange={e => setField('driver.name', e.target.value)} />
          </Field>
        </div>
        <Field label="CNIC">
          <input className="field-input" placeholder="35202-XXXXXXX-X" value={data.driver.cnic} onChange={e => setField('driver.cnic', e.target.value)} />
        </Field>
        <Field label="Date of birth">
          <input type="date" className="field-input" value={data.driver.dob} onChange={e => setField('driver.dob', e.target.value)} />
        </Field>
        <Field label="Mobile number">
          <input className="field-input" placeholder="+92 3XX-XXXXXXX" value={data.driver.mobile} onChange={e => setField('driver.mobile', e.target.value)} />
        </Field>
        <Field label="Email">
          <input className="field-input" type="email" placeholder="you@example.com" value={data.driver.email} onChange={e => setField('driver.email', e.target.value)} />
        </Field>
        <Field label="Driving experience">
          <select className="field-select" value={data.driver.license} onChange={e => setField('driver.license', e.target.value)}>
            <option>Less than 1 year</option><option>1-3 years</option><option>3-5 years</option><option>5+ years</option>
          </select>
        </Field>
        <Field label="Cover start date">
          <input type="date" className="field-input" value={data.coverStart} onChange={e => setField('coverStart', e.target.value)} />
        </Field>
      </div>
    </>
  );
}

function Step5({ data, total, navigate }) {
  const [pay, setPay] = React.useState('card');
  const methods = [
    { id: 'card', l: 'Debit / Credit Card', d: 'Visa, Mastercard, UnionPay' },
    { id: 'jazz', l: 'JazzCash', d: 'Mobile wallet payment' },
    { id: 'easy', l: 'Easypaisa', d: 'Mobile wallet payment' },
    { id: 'bank', l: 'Bank transfer', d: 'IBFT to IGI account' },
    { id: 'install', l: 'Monthly installments', d: '12 monthly payments' },
  ];
  return (
    <>
      <h2 style={{ fontSize: 24, fontWeight: 700, marginBottom: 8 }}>Review & pay</h2>
      <p style={{ color: 'var(--ink-500)', marginBottom: 24 }}>Almost there. Review your details, choose how to pay.</p>

      <div className="card" style={{ padding: 20, background: 'var(--ink-50)', border: 0, marginBottom: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
          <div style={{ fontWeight: 700 }}>Policy summary</div>
          <button style={{ fontSize: 13, color: 'var(--blue-700)', fontWeight: 600 }}>Edit</button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, fontSize: 13 }}>
          <Row label="Vehicle" value={`${data.vehicle.make} ${data.vehicle.model} ${data.vehicle.year}`} />
          <Row label="Sum insured" value={`PKR ${data.vehicle.value.toLocaleString()}`} />
          <Row label="City" value={data.vehicle.city} />
          <Row label="Plan" value={data.plan === 'comp' ? 'Comprehensive Plus' : data.plan === 'thirdparty' ? 'Third Party' : 'Standard'} />
          <Row label="Add-ons" value={`${data.addons.length} selected`} />
          <Row label="Cover starts" value={data.coverStart} />
        </div>
      </div>

      <div style={{ marginBottom: 16, fontWeight: 700 }}>Payment method</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {methods.map(m => {
          const sel = pay === m.id;
          return (
            <button key={m.id} onClick={() => setPay(m.id)} style={{
              padding: 14, border: sel ? '2px solid var(--blue-600)' : '1px solid var(--ink-200)',
              borderRadius: 10, background: sel ? 'var(--blue-50)' : 'white',
              display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left',
            }}>
              <span style={{
                width: 18, height: 18, borderRadius: '50%',
                border: sel ? '5px solid var(--blue-600)' : '2px solid var(--ink-300)',
                background: 'white', flexShrink: 0,
              }} />
              <I.CreditCard size={18} style={{ color: 'var(--ink-500)' }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>{m.l}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-500)' }}>{m.d}</div>
              </div>
            </button>
          );
        })}
      </div>

      <div style={{ marginTop: 24, padding: 14, background: 'var(--navy-50)', borderRadius: 10, fontSize: 12, color: 'var(--ink-700)', display: 'flex', gap: 10 }}>
        <I.Lock size={16} style={{ flexShrink: 0, marginTop: 1, color: 'var(--navy-800)' }} />
        <span>By proceeding, you agree to IGI's <a href="#" style={{ color: 'var(--blue-700)', fontWeight: 600 }}>policy terms</a> and authorize debit of PKR {total.toLocaleString()}.</span>
      </div>
    </>
  );
}

function Field({ label, children }) {
  return (
    <div>
      <label className="field-label">{label}</label>
      {children}
    </div>
  );
}

window.QuoteFlow = QuoteFlow;
