/* QuoteFlow Prototype · Customer journey (choose → configure → estimate → submit → confirm).
   On submit it writes a real lead to window.QFStore, which the admin app reads. */
function CustomerApp({ onGoAdmin }) {
  const { Button, Card, Badge, Switch, Input, Stepper, StatusBadge } = window.QuoteFlowDesignSystem_41788d;
  const C = window.QF_CATALOG;
  const [step, setStep] = React.useState('choose');     // choose | configure | estimate | done
  const [system, setSystem] = React.useState(null);
  const [cfg, setCfg] = React.useState({ panels: 7, battery: true, ev: false, bird: true });
  const [form, setForm] = React.useState({ name: '', email: '', phone: '', postcode: '' });
  const [submitted, setSubmitted] = React.useState(null);
  const stepIdx = { choose: 0, configure: 1, estimate: 2, done: 2 }[step];

  // ---- live pricing from the shared catalogue ----
  const panel = C.get(C.configurator.solar.panel);
  const opt = C.get;
  const output = Math.round(cfg.panels * panel.watts);
  const low = C.model.baseInstall
    + cfg.panels * panel.fit
    + (cfg.battery ? opt('GIV-BAT-9.5').fit : 0)
    + (cfg.ev ? opt('ZAPPI-2-7TW').fit : 0)
    + (cfg.bird ? opt('MESH-GUARD').fit : 0);
  const high = Math.round(low * (1 + C.model.rangeUplift));
  const annualSaving = Math.round(output * C.model.perKwhSaving);

  const SYSTEMS = [
    { name: 'Solar & Battery Storage', cat: 'solar', label: 'Solar & Battery', badge: 'Most popular',
      desc: 'Generate your own clean electricity, cut grid dependence, and store solar for evening use.' },
    { name: 'Standalone Battery Storage', cat: 'battery', label: 'Battery Storage',
      desc: 'Retrofit premium battery banks onto existing solar or load-shift cheap off-peak electricity.' },
    { name: 'EV Smart Chargers', cat: 'ev', label: 'EV Charger',
      desc: 'Install a fast, smart chargepoint that can divert excess daytime solar to your car.' },
    { name: 'Air Source Heat Pumps', cat: 'heat', label: 'Heat Pump', soon: true,
      desc: 'Transition away from fossil fuels with an efficient air-to-water heat pump.' },
  ];

  function submit() {
    var lead = window.QFStore.addLead({
      name: form.name || 'New enquiry', email: form.email, phone: form.phone, postcode: form.postcode,
      loc: form.postcode ? form.postcode.split(' ')[0] : '—',
      system: system.label, cat: system.cat,
      value: Math.round((low + high) / 2), low: low, high: high,
      config: Object.assign({}, cfg),
    });
    setSubmitted(lead);
    setStep('done');
    window.scrollTo(0, 0);
  }

  // ---------- shared header ----------
  const Header = () => (
    <header style={{ background: 'var(--surface-card)', borderBottom: '1px solid var(--border-default)' }}>
      <div style={{ maxWidth: 1180, margin: '0 auto', padding: '14px 28px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
          <span style={{ width: 34, height: 34, borderRadius: 'var(--radius-md)', background: 'var(--green-700)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="leaf" size={18} color="#fff" />
          </span>
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18, color: 'var(--text-strong)' }}>Greenline Energy</span>
        </div>
        <span style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 13, color: 'var(--text-muted)' }}>
          <Icon name="phone" size={15} /> 01305 123 456
        </span>
      </div>
    </header>
  );

  // ---------- step: choose ----------
  const Choose = () => (
    <div style={{ maxWidth: 1000, margin: '0 auto' }}>
      <div style={{ textAlign: 'center', maxWidth: 600, margin: '0 auto 30px' }}>
        <h1 style={{ fontSize: 38, letterSpacing: '-0.02em' }}>Choose your system upgrade</h1>
        <p style={{ marginTop: 12, fontSize: 16, color: 'var(--text-muted)', lineHeight: 1.55 }}>Select a technology to generate your personalised instant quote.</p>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 18 }}>
        {SYSTEMS.map((s, i) => (
          <div key={i} onClick={() => { if (!s.soon) { setSystem(s); setStep('configure'); window.scrollTo(0, 0); } }}
            style={{ cursor: s.soon ? 'default' : 'pointer', opacity: s.soon ? 0.7 : 1 }}>
            <Card hover={!s.soon} dashed={s.soon} padding={22} style={{ display: 'flex', gap: 16, minHeight: 132 }}>
              <CatTile cat={s.cat} size={52} />
              <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 700, color: 'var(--text-strong)' }}>{s.name}</h3>
                  {s.badge && <Badge tone="primary">{s.badge}</Badge>}
                  {s.soon && <Badge tone="neutral">Coming soon</Badge>}
                </div>
                <p style={{ marginTop: 7, fontSize: 13.5, lineHeight: 1.5, color: 'var(--text-muted)' }}>{s.desc}</p>
                {!s.soon && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, marginTop: 10, fontSize: 13.5, fontWeight: 700, color: 'var(--text-strong)' }}>Get instant quote <Icon name="arrow-right" size={15} /></span>}
              </div>
            </Card>
          </div>
        ))}
      </div>
    </div>
  );

  // ---------- step: configure ----------
  const Row = ({ label, sub, children }) => (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, padding: '16px 0', borderBottom: '1px solid var(--slate-100)' }}>
      <div><div style={{ fontSize: 15, fontWeight: 600, color: 'var(--text-strong)' }}>{label}</div>
        {sub && <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 2 }}>{sub}</div>}</div>
      {children}
    </div>
  );
  const Configure = () => (
    <div style={{ maxWidth: 1060, margin: '0 auto' }}>
      <button onClick={() => { setStep('choose'); window.scrollTo(0, 0); }} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'var(--font-sans)', fontSize: 13.5, color: 'var(--text-muted)', marginBottom: 14 }}>
        <Icon name="arrow-left" size={15} /> Back to systems
      </button>
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 330px', gap: 26, alignItems: 'start' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <CatTile cat={system.cat} />
            <div><h1 style={{ fontSize: 25 }}>{system.name}</h1><p style={{ fontSize: 14, color: 'var(--text-muted)', marginTop: 2 }}>Tune your system — the estimate updates live.</p></div>
          </div>
          <Card padding={24}>
            <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, marginBottom: 4 }}>Hardware package</h3>
            <Row label="Number of panels" sub={panel.mfr + ' ' + panel.name + ' · ' + output.toLocaleString('en-GB') + ' kWh/yr'}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                <input className="qf-range" type="range" min="4" max="14" value={cfg.panels} onChange={e => setCfg(Object.assign({}, cfg, { panels: +e.target.value }))} aria-label="Panels" style={{ width: 170 }} />
                <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, color: 'var(--text-strong)', width: 26, textAlign: 'right' }}>{cfg.panels}</span>
              </div>
            </Row>
            <Row label="Add battery storage" sub={opt('GIV-BAT-9.5').mfr + ' ' + opt('GIV-BAT-9.5').name}><Switch checked={cfg.battery} onChange={v => setCfg(Object.assign({}, cfg, { battery: v }))} /></Row>
            <Row label="Add EV charger" sub={opt('ZAPPI-2-7TW').mfr + ' ' + opt('ZAPPI-2-7TW').name}><Switch checked={cfg.ev} onChange={v => setCfg(Object.assign({}, cfg, { ev: v }))} /></Row>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, padding: '16px 0 0' }}>
              <div><div style={{ fontSize: 15, fontWeight: 600, color: 'var(--text-strong)' }}>Bird &amp; squirrel protection</div><div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 2 }}>Mesh guard around the array</div></div>
              <Switch checked={cfg.bird} onChange={v => setCfg(Object.assign({}, cfg, { bird: v }))} />
            </div>
          </Card>
        </div>
        {/* sticky summary */}
        <div style={{ position: 'sticky', top: 24, background: 'var(--surface-card)', borderRadius: 'var(--radius-lg)', border: '1px solid var(--border-default)', boxShadow: 'var(--shadow-md)', overflow: 'hidden' }}>
          <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--border-default)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16 }}>Your estimate</span><Badge tone="primary">Live</Badge>
          </div>
          <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 11 }}>
            {[['Panels', cfg.panels + ' × ' + panel.watts + 'W'], ['Battery', cfg.battery ? '9.5kWh hybrid' : '—'], ['EV charger', cfg.ev ? '7kW smart' : '—'], ['Est. output', output.toLocaleString('en-GB') + ' kWh/yr']].map(r => (
              <div key={r[0]} style={{ display: 'flex', justifyContent: 'space-between', gap: 12, fontSize: 13.5 }}><span style={{ color: 'var(--text-muted)' }}>{r[0]}</span><span style={{ color: 'var(--text-strong)', fontWeight: 600, whiteSpace: 'nowrap' }}>{r[1]}</span></div>
            ))}
            <div style={{ borderTop: '1px solid var(--border-default)', marginTop: 3, paddingTop: 12 }}>
              <div style={{ fontSize: 12, color: 'var(--text-faint)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em' }}>Estimated range</div>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 24, color: 'var(--text-strong)', marginTop: 4 }}>{gbp(low)} – {gbp(high)}</div>
            </div>
            <Button variant="primary" fullWidth iconRight={<Icon name="arrow-right" size={16} />} onClick={() => { setStep('estimate'); window.scrollTo(0, 0); }}>See full estimate</Button>
          </div>
        </div>
      </div>
    </div>
  );

  // ---------- step: estimate ----------
  const items = [
    { label: 'Solar PV installation', sub: cfg.panels + ' × ' + panel.name + ', inverter & mounting', amount: C.model.baseInstall + cfg.panels * panel.fit },
  ].concat(cfg.battery ? [{ label: opt('GIV-BAT-9.5').name, sub: 'Hybrid battery with monitoring', amount: opt('GIV-BAT-9.5').fit }] : [])
   .concat(cfg.ev ? [{ label: opt('ZAPPI-2-7TW').name, sub: 'Untethered smart charger', amount: opt('ZAPPI-2-7TW').fit }] : [])
   .concat(cfg.bird ? [{ label: 'Bird & squirrel protection', sub: 'Mesh guard around the array', amount: opt('MESH-GUARD').fit }] : []);
  const formValid = form.name && form.email && form.postcode;

  const Estimate = () => (
    <div style={{ maxWidth: 1060, margin: '0 auto' }}>
      <button onClick={() => { setStep('configure'); window.scrollTo(0, 0); }} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'var(--font-sans)', fontSize: 13.5, color: 'var(--text-muted)', marginBottom: 14 }}>
        <Icon name="arrow-left" size={15} /> Back to system design
      </button>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20 }}>
        <CatTile cat={system.cat} />
        <div><h1 style={{ fontSize: 26 }}>Your personalised estimate</h1><p style={{ fontSize: 14, color: 'var(--text-muted)', marginTop: 2 }}>{system.name} · by Greenline Energy</p></div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 350px', gap: 26, alignItems: 'start' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <Card padding={0}>
            <div style={{ padding: '16px 24px', borderBottom: '1px solid var(--border-default)' }}><h2 style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 700 }}>What's included</h2></div>
            <div style={{ padding: '4px 24px' }}>
              {items.map((it, i) => (
                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, padding: '14px 0', borderBottom: i < items.length - 1 ? '1px solid var(--slate-100)' : 'none' }}>
                  <div style={{ display: 'flex', gap: 11 }}><Icon name="check" size={17} color="var(--accent-deep)" style={{ marginTop: 2, flex: 'none' }} /><div><div style={{ fontSize: 14.5, fontWeight: 600, color: 'var(--text-strong)' }}>{it.label}</div><div style={{ fontSize: 12.5, color: 'var(--text-muted)', marginTop: 1 }}>{it.sub}</div></div></div>
                  <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15.5, color: 'var(--text-strong)', whiteSpace: 'nowrap' }}>{gbp(it.amount)}</span>
                </div>
              ))}
            </div>
            <div style={{ padding: '14px 24px', background: 'var(--surface-sunken)', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <span style={{ fontSize: 13, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.04em', color: 'var(--text-muted)' }}>Estimated total</span>
              <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22, color: 'var(--text-strong)' }}>{gbp(low)} – {gbp(high)}</span>
            </div>
          </Card>
          <Card padding={20} style={{ display: 'flex', gap: 20 }}>
            {[['piggy-bank', gbp(annualSaving) + '/yr', 'Est. bill saving'], ['trending-up', gbp(annualSaving * 25), '25-year saving'], ['leaf', (output * 0.207 / 1000).toFixed(1) + 't', 'CO₂ saved / yr']].map((s, i) => (
              <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 5 }}>
                <Icon name={s[0]} size={19} color="var(--accent-deep)" />
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 19, color: 'var(--text-strong)' }}>{s[1]}</div>
                <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{s[2]}</div>
              </div>
            ))}
          </Card>
        </div>
        {/* capture */}
        <div style={{ position: 'sticky', top: 24, background: 'var(--surface-card)', borderRadius: 'var(--radius-lg)', border: '1px solid var(--border-default)', boxShadow: 'var(--shadow-md)', overflow: 'hidden' }}>
          <div style={{ background: 'var(--indigo-900)', padding: 20, color: 'var(--cream)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
              <span style={{ fontSize: 12, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', color: 'var(--text-on-dark-muted)' }}>Estimated total</span>
              <StatusBadge status="No obligation" />
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 26 }}>{gbp(low)} – {gbp(high)}</div>
          </div>
          <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 12 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-strong)' }}>Book your free survey</div>
            <Input label="Full name" placeholder="Sarah Mitchell" value={form.name} onChange={e => setForm(Object.assign({}, form, { name: e.target.value }))} />
            <Input label="Email" type="email" placeholder="you@email.co.uk" value={form.email} onChange={e => setForm(Object.assign({}, form, { email: e.target.value }))} />
            <Input label="Phone" placeholder="07700 900123" value={form.phone} onChange={e => setForm(Object.assign({}, form, { phone: e.target.value }))} />
            <Input label="Postcode" placeholder="DT4 8QR" value={form.postcode} onChange={e => setForm(Object.assign({}, form, { postcode: e.target.value }))} />
            <Button variant="primary" fullWidth disabled={!formValid} iconLeft={<Icon name="calendar-check" size={16} />} onClick={submit}>Submit &amp; book survey</Button>
            <p style={{ fontSize: 11.5, color: 'var(--text-faint)', lineHeight: 1.5, margin: 0 }}>Submitting sends your quote to Greenline Energy — it appears instantly in their installer dashboard.</p>
          </div>
        </div>
      </div>
    </div>
  );

  // ---------- step: done ----------
  const Done = () => (
    <div style={{ maxWidth: 560, margin: '24px auto 0', textAlign: 'center' }}>
      <Card padding={40} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16 }}>
        <span style={{ width: 72, height: 72, borderRadius: '50%', background: 'var(--green-50)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="check" size={38} color="var(--accent-deep)" stroke={2.4} />
        </span>
        <h1 style={{ fontSize: 28 }}>Quote sent to Greenline Energy</h1>
        <p style={{ fontSize: 15, color: 'var(--text-muted)', lineHeight: 1.55 }}>
          Thanks {submitted.name.split(' ')[0]}! Your {submitted.system} quote of <b style={{ color: 'var(--text-strong)' }}>{gbp(submitted.low)}–{gbp(submitted.high)}</b> has been saved. The team will be in touch to book your free survey.
        </p>
        <div style={{ width: '100%', background: 'var(--surface-sunken)', borderRadius: 'var(--radius-md)', padding: 16, display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left' }}>
          <Icon name="git-branch" size={20} color="var(--primary)" />
          <div style={{ fontSize: 13, color: 'var(--text-body)' }}>This lead is now live in the installer's pipeline as a <StatusBadge status="New lead" />.</div>
        </div>
        <div style={{ display: 'flex', gap: 10, marginTop: 4 }}>
          <Button variant="secondary" onClick={() => { setSystem(null); setForm({ name: '', email: '', phone: '', postcode: '' }); setStep('choose'); window.scrollTo(0, 0); }}>Start another quote</Button>
          <Button variant="primary" iconRight={<Icon name="arrow-right" size={16} />} onClick={onGoAdmin}>View it in admin →</Button>
        </div>
      </Card>
    </div>
  );

  return (
    <div style={{ minHeight: '100%', background: 'var(--bg-app)' }}>
      <Header />
      <div style={{ padding: '26px 24px 60px' }}>
        {step !== 'done' && (
          <div style={{ maxWidth: 1060, margin: '0 auto 28px' }}>
            <Stepper steps={['Select technology', 'System design', 'Estimate']} current={stepIdx} />
          </div>
        )}
        {step === 'choose' && <Choose />}
        {step === 'configure' && <Configure />}
        {step === 'estimate' && <Estimate />}
        {step === 'done' && <Done />}
      </div>
    </div>
  );
}
window.CustomerApp = CustomerApp;
