function Proforma({ sectorId, sectors, selections, onBack, onEdit, accent, settings }) {
  const sector = (sectors || []).find(s => s.id === sectorId) || (sectors || [])[0] || { id: 'burger', label: 'Packaging' };
  const [products, setProducts] = React.useState(null);
  const [submitted, setSubmitted] = React.useState(null);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);
  const isMobile = useMedia('(max-width: 900px)');
  const [form, setForm] = React.useState({
    company: '', contact: '', phone: '', country: 'United Kingdom', method: 'WhatsApp', notes: '',
  });

  React.useEffect(() => {
    api.get('/api/products?sector=' + encodeURIComponent(sector.id)).then(setProducts);
  }, [sector.id]);

  const getUnit = (p, qty) => {
    const tiers = [...(p.pricing || [])].sort((a,b) => a.qty - b.qty);
    let unit = tiers[0]?.unit ?? 0;
    for (const t of tiers) if (qty >= t.qty) unit = t.unit;
    return unit;
  };

  const rows = React.useMemo(() => {
    if (!products) return [];
    return Object.entries(selections).map(([pid, v]) => {
      const p = products.find(x => x.id === pid);
      if (!p) return null;
      const variant = p.variants.find(x => x.id === v.variantId);
      const unit = getUnit(p, v.qty);
      return { product: p, variant, qty: v.qty, unit, subtotal: unit * v.qty };
    }).filter(Boolean);
  }, [products, selections]);

  const total = rows.reduce((s, r) => s + r.subtotal, 0);
  const units = rows.reduce((s, r) => s + r.qty, 0);
  const today = new Date().toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' });

  const submit = async (e) => {
    e?.preventDefault();
    if (!form.company || !form.contact || !form.phone || submitting) return;
    setSubmitting(true);
    setError(null);
    try {
      const result = await api.post('/api/leads', {
        ...form,
        sector: sector.id,
        selections,
      });
      if (result.error) throw new Error(result.error);
      setSubmitted(result);
    } catch (err) {
      setError(err.message || 'Something went wrong, try again.');
    } finally {
      setSubmitting(false);
    }
  };

  if (submitted) return <SuccessScreen ref_={submitted.id} form={form} onBack={onBack} accent={accent} settings={settings} />;
  if (!products) return <PageLoading />;

  const ref = 'LPK-draft';

  return (
    <div style={{ minHeight: '100vh' }}>
      <TopBar
        step={2}
        onLogo={onBack}
        stepLabels={['Sector', 'Build', 'Review', 'Contact']}
        right={<>
          <button onClick={onEdit} style={{
            background: 'transparent', border: 0, color: 'var(--muted)',
            fontSize: 12.5, display: 'inline-flex', alignItems: 'center', gap: 6, cursor: 'pointer',
          }}>
            <svg width="10" height="10" viewBox="0 0 16 16" fill="none"><path d="M13 8 L3 8 M7 4 L3 8 L7 12" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"/></svg>
            <span className="hide-mobile">Edit set</span>
          </button>
        </>}
      />

      <div className="two-col-13" style={{ minHeight: 'calc(100vh - 73px)' }}>
        <section className="pad-lg" style={{
          padding: isMobile ? '28px 20px' : '56px 56px 72px',
          borderRight: isMobile ? 'none' : '.5px solid var(--line)',
          borderBottom: isMobile ? '.5px solid var(--line)' : 'none',
        }}>
          <div className="fade-up">
            <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 16 }}>
              Proforma Estimate · {sector.label}
            </div>
            <h1 className="responsive-h1" style={{
              fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 56,
              fontWeight: 400, margin: '0 0 8px 0', letterSpacing: '-0.02em', lineHeight: 1,
            }}>
              Your set, tallied.
            </h1>
            <p style={{ fontSize: 15, color: 'var(--ink-2)', maxWidth: 520, marginTop: 16, lineHeight: 1.5 }}>
              Prices are indicative based on current tiered rates. A member of our team will confirm final pricing, samples, and production scheduling once you confirm this plan.
            </p>
          </div>

          <div className="grid-4-mobile-2" style={{
            marginTop: 32, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 20,
            paddingTop: 24, paddingBottom: 24, borderTop: '.5px solid var(--line)', borderBottom: '.5px solid var(--line)',
          }}>
            <Metric label="Reference" value={ref} />
            <Metric label="Issued" value={today} />
            <Metric label="Sector" value={sector.label.split(' ')[0]} />
            <Metric label="Lead time" value={settings.lead_time_days || '12–18 days'} />
          </div>

          <div style={{ marginTop: 28, overflow: 'auto' }} className="scroll-x-mobile">
            <div className="mono" style={{
              display: 'grid', gridTemplateColumns: '44px 1fr 90px 100px 100px',
              gap: 14, padding: '0 0 10px', fontSize: 10, letterSpacing: '0.08em',
              textTransform: 'uppercase', color: 'var(--muted)', minWidth: 520,
              borderBottom: '.5px solid var(--line)',
            }}>
              <span>#</span><span>Item</span><span style={{textAlign:'right'}}>Unit</span><span style={{textAlign:'right'}}>Qty</span><span style={{textAlign:'right'}}>Subtotal</span>
            </div>
            {rows.map((r, i) => (
              <div key={r.product.id} className="fade-up" style={{
                display: 'grid', gridTemplateColumns: '44px 1fr 90px 100px 100px',
                gap: 14, padding: '16px 0', alignItems: 'center', minWidth: 520,
                borderBottom: '.5px solid var(--line)', animationDelay: `${0.05 * i}s`,
              }}>
                <div style={{ width: 44, height: 44, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--bg-2)', borderRadius: 8, overflow: 'hidden' }}>
                  <ProductImage product={r.product} size={44} />
                </div>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: '-0.01em' }}>{r.product.name}</div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--muted)', marginTop: 2 }}>
                    {r.variant?.size} · {r.variant?.dims}
                  </div>
                </div>
                <div className="mono" style={{ textAlign: 'right', fontSize: 13 }}>£{r.unit.toFixed(3)}</div>
                <div className="mono" style={{ textAlign: 'right', fontSize: 13 }}>{r.qty.toLocaleString('en-GB')}</div>
                <div className="mono" style={{ textAlign: 'right', fontSize: 14, fontWeight: 500 }}>
                  £{r.subtotal.toLocaleString('en-GB', { maximumFractionDigits: 0 })}
                </div>
              </div>
            ))}
          </div>

          <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 24 }}>
            <div style={{ width: '100%', maxWidth: 360, display: 'flex', flexDirection: 'column', gap: 10 }}>
              <TotalRow label="Items" value={`${rows.length}`} />
              <TotalRow label="Total units" value={units.toLocaleString('en-GB')} />
              <TotalRow label="Subtotal" value={`£${total.toLocaleString('en-GB', { maximumFractionDigits: 0 })}`} />
              <TotalRow label="VAT" value="On application" muted />
              <div style={{
                marginTop: 8, paddingTop: 16, borderTop: '1px solid var(--ink)',
                display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
              }}>
                <span style={{ fontSize: 13, fontWeight: 500 }}>Estimate</span>
                <span style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 34, letterSpacing: '-0.02em' }}>
                  £{total.toLocaleString('en-GB', { maximumFractionDigits: 0 })}
                </span>
              </div>
            </div>
          </div>

          {settings.company_name && (
            <div className="mono" style={{
              marginTop: 32, padding: '14px 18px', background: 'var(--paper)',
              borderRadius: 10, border: '.5px solid var(--line)',
              fontSize: 11, color: 'var(--muted)', lineHeight: 1.6,
            }}>
              ISSUED BY · {settings.company_name}
              {settings.address_line1 && <><br/>{settings.address_line1}{settings.address_line2 ? `, ${settings.address_line2}` : ''}</>}
              {settings.address_city && <>, {settings.address_city} {settings.address_postcode}</>}
              {settings.address_country && <>, {settings.address_country}</>}
              {settings.vat_number && <><br/>VAT {settings.vat_number}</>}
            </div>
          )}
        </section>

        <section className="pad-lg" style={{ padding: isMobile ? '28px 20px 120px' : '56px 48px 72px', background: 'var(--paper)' }}>
          <div style={{ position: isMobile ? 'static' : 'sticky', top: 90 }}>
            <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 12 }}>
              Step 03 · Confirm & Send
            </div>
            <h2 className="responsive-h2" style={{
              fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 36,
              fontWeight: 400, margin: '0 0 12px 0', letterSpacing: '-0.02em', lineHeight: 1.05,
            }}>
              Where should we send the quote?
            </h2>
            <p style={{ fontSize: 13.5, color: 'var(--muted)', maxWidth: 380, lineHeight: 1.5, marginTop: 8 }}>
              A specialist will review your set and reach out within 24 hours. No payment, no commitment.
            </p>

            <form onSubmit={submit} style={{ marginTop: 28, display: 'flex', flexDirection: 'column', gap: 14 }}>
              <Field label="Company name" value={form.company} onChange={(v) => setForm({...form, company: v})} placeholder="e.g. The Shack Burgers Ltd" />
              <Field label="Contact person" value={form.contact} onChange={(v) => setForm({...form, contact: v})} placeholder="Full name" />
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                <Field label="Phone number" value={form.phone} onChange={(v) => setForm({...form, phone: v})} placeholder="+44 …" />
                <Field
                  label="Country"
                  value={form.country}
                  onChange={(v) => setForm({...form, country: v})}
                  select
                  options={['United Kingdom', 'Ireland', 'France', 'Germany', 'Spain', 'Netherlands', 'Türkiye', 'Other']}
                />
              </div>

              <div>
                <div className="mono" style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 8 }}>
                  Preferred contact method
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                  {[
                    { v: 'WhatsApp',  hint: 'WhatsApp Business · reply 2hr' },
                    { v: 'Phone Call', hint: settings.whatsapp_hours || 'Weekday · 9–18 GMT' },
                  ].map(opt => {
                    const active = form.method === opt.v;
                    return (
                      <button
                        type="button"
                        key={opt.v}
                        onClick={() => setForm({...form, method: opt.v})}
                        style={{
                          padding: '14px', borderRadius: 10,
                          background: active ? 'var(--ink)' : '#fff',
                          color: active ? 'var(--paper)' : 'var(--ink)',
                          border: active ? 'none' : '.5px solid var(--line-2)',
                          textAlign: 'left', display: 'flex', flexDirection: 'column', gap: 4,
                          fontSize: 13, fontWeight: 500, cursor: 'pointer',
                        }}
                      >
                        <span>{opt.v}</span>
                        <span className="mono" style={{ fontSize: 10, opacity: 0.6 }}>
                          {opt.hint}
                        </span>
                      </button>
                    );
                  })}
                </div>
              </div>

              <Field label="Notes (optional)" value={form.notes} onChange={(v) => setForm({...form, notes: v})} placeholder="Artwork, timeline, special requirements…" textarea />

              {error && (
                <div style={{ padding: '10px 14px', background: 'rgba(212,83,42,.1)', border: '.5px solid rgba(212,83,42,.35)', borderRadius: 8, fontSize: 12.5, color: 'var(--accent)' }}>
                  {error}
                </div>
              )}

              <Button
                variant="primary" size="lg" full type="submit"
                disabled={!form.company || !form.contact || !form.phone || submitting}
                iconRight={submitting ? <Spinner size={14}/> : <ArrowRight size={14}/>}
                onClick={submit}
              >
                {submitting ? 'Sending…' : 'Confirm & send my packaging plan'}
              </Button>

              <div className="mono" style={{ fontSize: 10.5, color: 'var(--muted)', textAlign: 'center', marginTop: 4, lineHeight: 1.5 }}>
                By sending, you agree to be contacted by {settings.company_name || 'Lupipak'} about this quote.<br/>
                We'll never share your details. GDPR · UK-GDPR compliant.
              </div>
            </form>
          </div>
        </section>
      </div>
    </div>
  );
}

function Field({ label, value, onChange, placeholder, select, options, textarea }) {
  const base = {
    width: '100%', padding: '12px 14px',
    fontFamily: 'inherit',
    background: '#fff', border: '.5px solid var(--line-2)',
    borderRadius: 10, outline: 'none',
  };
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span className="mono" style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)' }}>
        {label}
      </span>
      {textarea ? (
        <textarea rows={3} value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder}
          style={{ ...base, resize: 'vertical', minHeight: 72 }}
        />
      ) : select ? (
        <select value={value} onChange={(e) => onChange(e.target.value)} style={base}>
          {options.map(o => <option key={o}>{o}</option>)}
        </select>
      ) : (
        <input type="text" value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} style={base} />
      )}
    </label>
  );
}

function TotalRow({ label, value, muted }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
      <span className="mono" style={{ color: 'var(--muted)', fontSize: 11, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{label}</span>
      <span className="mono" style={{ color: muted ? 'var(--muted)' : 'var(--ink)' }}>{value}</span>
    </div>
  );
}

function SuccessScreen({ ref_, form, onBack, accent, settings }) {
  return (
    <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      <TopBar onLogo={onBack} right={<span className="mono" style={{ fontSize: 11 }}>Ref · {ref_}</span>} />
      <main className="pad-lg" style={{
        flex: 1, display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center', padding: 40, textAlign: 'center',
      }}>
        <div className="fade-up" style={{
          width: 72, height: 72, borderRadius: '50%',
          background: accent, color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          marginBottom: 32,
        }}>
          <Check size={28} />
        </div>
        <div className="mono fade-up" style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 14, animationDelay: '.06s' }}>
          Plan sent · {ref_}
        </div>
        <h1 className="fade-up responsive-h1" style={{
          fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 64,
          fontWeight: 400, margin: 0, letterSpacing: '-0.02em', animationDelay: '.12s',
        }}>
          Thank you, {form.contact.split(' ')[0] || 'friend'}.
        </h1>
        <p className="fade-up" style={{ fontSize: 17, color: 'var(--ink-2)', marginTop: 20, maxWidth: 520, lineHeight: 1.5, animationDelay: '.18s' }}>
          We've received your packaging plan. A specialist from our {form.country} desk will reach out via <strong style={{ fontWeight: 500 }}>{form.method}</strong> within 24 hours, usually much sooner.
        </p>
        <div className="fade-up grid-4-mobile-2" style={{
          display: 'flex', gap: 32, marginTop: 40, padding: '20px 28px',
          background: 'var(--paper)', borderRadius: 16, border: '.5px solid var(--line-2)',
          animationDelay: '.24s', flexWrap: 'wrap', justifyContent: 'center',
        }}>
          <Metric label="Expected reply" value="< 24 hours" />
          <Metric label="Next" value="Samples & quote" />
          <Metric label="Then" value="Artwork & production" />
        </div>
        <div style={{ display: 'flex', gap: 10, marginTop: 40, flexWrap: 'wrap', justifyContent: 'center' }}>
          <Button variant="primary"
            onClick={() => window.open(`/api/leads/${ref_}/proforma.pdf?ref=${encodeURIComponent(ref_)}`, '_blank')}
            icon={<svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M8 2 V11 M5 8 L8 11 L11 8 M3 13 H13" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/></svg>}
          >
            Download proforma PDF
          </Button>
          <Button variant="ghost" onClick={onBack}>Back to homepage</Button>
        </div>
      </main>
    </div>
  );
}

Object.assign(window, { Proforma });
