/* Powermieter — Onboarding flow.
   Order: Wohnung → Daten + Zähler → Konditionen + Einwilligungen → SEPA-Mandat
   (GoCardless, off-site) → Vertrag prüfen + unterschreiben → Erfolg.
   "Erst SEPA, dann Vertrag." Built-in signature (SES); GoCardless best-effort. */

const { useState, useEffect, useRef, useCallback } = React;
const JSON_HEADERS = { 'Content-Type': 'application/json' };
const adresseOf = (b) => `${b.strasse} ${b.hausnr}, ${b.plz} ${b.ort}`;
const TODAY = (() => { try { return new Date().toISOString().slice(0, 10); } catch (e) { return ''; } })();

/* ---------- Screen 1 · Interesse / unit selection ---------------- */
function Screen1({ mode, building, unit, setUnit, onNext }) {
  if (mode === 'rep') {
    return (
      <div className="pm-page pm-anim">
        <div className="pm-eyebrow">{building.name} · Mieterstrom</div>
        <h1 className="pm-h1">Wohnung wählen</h1>
        <p className="pm-lead">Wähle die Wohneinheit des Mieters und reiche das Tablet weiter. Jeder unterschriebene Vertrag aktiviert eine weitere Wohnung an der bereits laufenden Anlage.</p>
        <div className="pm-unit-grid">
          {building.units.map((u) => (
            <button key={u.we} className={`pm-unit ${u.signed ? 'is-signed' : ''}`}
              onClick={() => { if (!u.signed) { setUnit(u); onNext(); } }}>
              <div className="pm-unit-we">{u.we}</div>
              <div className="pm-unit-meta">{u.etage} · {u.klingel}</div>
              <div className={`pm-unit-state ${u.signed ? 'done' : 'open'}`}>
                {u.signed ? <><I.checkSm size={13} /> abgeschlossen</> : <><I.bolt size={13} /> offen</>}
              </div>
            </button>
          ))}
        </div>
      </div>
    );
  }
  const saving = estSaving(unit ? unit.verbrauch : 2500);
  return (
    <div className="pm-page pm-anim">
      <div className="pm-eyebrow">{building.name}</div>
      <h1 className="pm-h1">Ihr Strom kommt jetzt vom eigenen Dach</h1>
      <p className="pm-lead">Auf {building.strasse} {building.hausnr} läuft bereits eine Solaranlage. Als Mieter:in sichern Sie sich günstigen Strom direkt vom Dach – ohne Umzug, ohne Technikwechsel, in wenigen Minuten beauftragt.</p>
      <div className="pm-kpis">
        <div className="pm-kpi"><div className="pm-kpi-num">~{saving} €</div><div className="pm-kpi-lbl">Ersparnis pro Jahr</div></div>
        <div className="pm-kpi"><div className="pm-kpi-num">{TARIFF.arbeitspreis.replace(' ct/kWh','')}</div><div className="pm-kpi-lbl">ct/kWh statt {TARIFF.vergleich.replace(' ct/kWh','')}</div></div>
        <div className="pm-kpi"><div className="pm-kpi-num">0 €</div><div className="pm-kpi-lbl">Wechselkosten</div></div>
      </div>
      <div className="pm-card"><div className="pm-card-pad">
        <div className="pm-card-head"><I.home size={20} style={{color:'var(--accent)'}} /><div><div className="pm-card-title">Welche Wohnung ist Ihre?</div><div className="pm-card-sub">Damit füllen wir Ihren Vertrag automatisch vor.</div></div></div>
        <div style={{marginTop:14}}>
          <Select label="Ihre Wohneinheit" name="we" value={unit ? unit.we : ''}
            onChange={(_, v) => setUnit(getUnit(building, v))}
            options={building.units.map((u) => ({ value: u.we, label: `${u.we} · ${u.etage} · ${u.klingel}` }))} />
        </div>
      </div></div>
      <div className="pm-trustrow">
        <span className="pm-trust"><I.shield size={16}/> Geprüfter Mieterstrom-Anbieter</span>
        <span className="pm-trust"><I.lock size={16}/> 14 Tage Widerrufsrecht</span>
        <span className="pm-trust"><I.check size={16}/> Monatlich kündbar</span>
      </div>
    </div>
  );
}

/* ---------- Screen 2 · Daten + Zähler ---------------------------- */
function Screen2({ form, set, errors, building, unit }) {
  return (
    <div className="pm-page pm-anim">
      <div className="pm-eyebrow">Schritt 2 · Daten</div>
      <h1 className="pm-h1">Ihre Daten &amp; Zählerstand</h1>
      <p className="pm-lead">Adresse, Wohnung und Tarif sind hinterlegt. Wir brauchen nur Ihre Kontaktdaten und den aktuellen Zählerstand.</p>
      <div className="pm-card"><div className="pm-card-pad">
        <span className="pm-prefill-tag"><I.check size={15}/> Bereits für Sie ausgefüllt</span>
        <div className="pm-prefill"><dl style={{margin:0}}>
          <div className="pm-prefill-row"><dt>Adresse</dt><dd>{adresseOf(building)}</dd></div>
          <div className="pm-prefill-row"><dt>Wohneinheit</dt><dd>{unit.we} · {unit.etage}</dd></div>
          <div className="pm-prefill-row"><dt>Klingelschild</dt><dd>{unit.klingel}</dd></div>
        </dl></div>
      </div></div>
      <div className="pm-card"><div className="pm-card-pad">
        <div className="pm-grid">
          <Field label="Vorname" name="vorname" value={form.vorname} onChange={set} error={errors.vorname} autoComplete="given-name" />
          <Field label="Nachname" name="nachname" value={form.nachname} onChange={set} error={errors.nachname} autoComplete="family-name" />
          <Field label="E-Mail" name="email" type="email" value={form.email} onChange={set} error={errors.email} inputMode="email" autoComplete="email" col2 hint="Hierhin senden wir Bestätigung &amp; Vertrag." />
          <Field label="Telefon" name="telefon" type="tel" value={form.telefon} onChange={set} error={errors.telefon} inputMode="tel" autoComplete="tel" col2 />
        </div>
      </div></div>
      <div className="pm-card"><div className="pm-card-pad">
        <div className="pm-card-head"><I.gauge size={20} style={{color:'var(--accent)'}} /><div><div className="pm-card-title">Aktueller Zählerstand</div><div className="pm-card-sub">Bitte am Zähler ablesen und fotografieren.</div></div></div>
        <div className="pm-grid" style={{marginTop:14}}>
          <Field label="Zählernummer" name="zaehlernr" value={form.zaehlernr} onChange={set} error={errors.zaehlernr} hint="vorausgefüllt – bitte am Zähler prüfen" />
          <Field label="Zählerstand (kWh)" name="zaehlerstand" value={form.zaehlerstand} onChange={set} error={errors.zaehlerstand} inputMode="numeric" placeholder="z. B. 014230" />
          <Field label="Ablesedatum" name="ablesedatum" type="date" value={form.ablesedatum} onChange={set} col2 />
        </div>
        <div style={{marginTop:16}}>
          <span className="pm-label" style={{display:'block',marginBottom:8}}>Foto vom Zählerstand</span>
          <PhotoCapture value={form.zaehlerFoto} onChange={(d) => set('zaehlerFoto', d)} error={errors.zaehlerFoto} />
        </div>
      </div></div>
    </div>
  );
}

/* ---------- Screen 3 · Konditionen + Einwilligungen → SEPA ------- */
function ScreenSepa({ form, set, errors, building, unit, onShowContract }) {
  return (
    <div className="pm-page pm-anim">
      <div className="pm-eyebrow">Schritt 3 · SEPA-Lastschriftmandat</div>
      <h1 className="pm-h1">Konditionen &amp; Zahlung</h1>
      <p className="pm-lead">Konditionen prüfen, zustimmen, dann auf der sicheren Bankseite das SEPA-Mandat erteilen. Danach unterschreiben Sie den Vertrag.</p>

      <div className="pm-card"><div className="pm-card-pad">
        <div className="pm-card-head"><I.doc size={20} style={{color:'var(--accent)'}} /><div className="pm-card-title">{TARIFF.name}</div></div>
        <div className="pm-prefill" style={{marginTop:12}}><dl style={{margin:0}}>
          <div className="pm-prefill-row"><dt>Arbeitspreis</dt><dd>{TARIFF.arbeitspreis}</dd></div>
          <div className="pm-prefill-row"><dt>Grundpreis</dt><dd>{TARIFF.grundpreis}</dd></div>
          <div className="pm-prefill-row"><dt>Lieferbeginn</dt><dd>{building.lieferbeginn}</dd></div>
          <div className="pm-prefill-row"><dt>Laufzeit</dt><dd>{TARIFF.laufzeit}</dd></div>
          <div className="pm-prefill-row"><dt>Zählerstand</dt><dd>{form.zaehlerstand ? `${form.zaehlerstand} kWh` : '—'}</dd></div>
        </dl></div>
        <div style={{marginTop:14}}><Button kind="ghost" onClick={onShowContract}><I.doc size={16}/> Vollständigen Vertrag öffnen</Button></div>
      </div></div>

      <div className="pm-card"><div className="pm-card-pad">
        <div className="pm-card-head"><I.meter size={20} style={{color:'var(--accent)'}} /><div><div className="pm-card-title">Bisheriger Stromvertrag</div><div className="pm-card-sub">Optional – wir kümmern uns um die Kündigung.</div></div></div>
        <div className="pm-grid" style={{marginTop:14}}>
          <Field label="Aktueller Anbieter" name="anbieter" value={form.anbieter} onChange={set} optional placeholder="z. B. Stadtwerke" />
          <Field label="Kundennummer" name="kundennr" value={form.kundennr} onChange={set} optional />
        </div>
      </div></div>

      <div className="pm-card"><div className="pm-card-pad">
        <div className="pm-card-head"><I.lock size={20} style={{color:'var(--accent)'}} /><div className="pm-card-title">Einwilligungen</div></div>
        <Consent name="v_agb" checked={form.v_agb} onChange={set} error={errors.v_agb}>
          Ich akzeptiere die <a className="pm-link" href="#agb" onClick={(e)=>e.preventDefault()}>AGB</a> und das <a className="pm-link" href="#preisblatt" onClick={(e)=>e.preventDefault()}>Preisblatt</a> des Mieterstromvertrags.
        </Consent>
        <Consent name="v_widerruf" checked={form.v_widerruf} onChange={set} error={errors.v_widerruf}>
          Ich habe die <a className="pm-link" href="#widerruf" onClick={(e)=>e.preventDefault()}>Widerrufsbelehrung</a> gelesen ({TARIFF.widerrufstage} Tage Widerrufsrecht).
        </Consent>
        <Consent name="dsgvo" checked={form.dsgvo} onChange={set} error={errors.dsgvo}>
          Ich willige in die Verarbeitung meiner Daten gemäß <a className="pm-link" href="#datenschutz" onClick={(e)=>e.preventDefault()}>Datenschutzerklärung</a> ein.
        </Consent>
        <Consent name="v_sepa" checked={form.v_sepa} onChange={set} error={errors.v_sepa}>
          Ich ermächtige Powermieter, Zahlungen per <b>SEPA-Lastschrift</b> einzuziehen.
        </Consent>
      </div></div>

      <Note>Im nächsten Schritt richten Sie auf der sicheren Bankseite (GoCardless) Ihr SEPA-Mandat ein. Danach unterschreiben Sie den Vertrag rechtsgültig.</Note>
    </div>
  );
}

/* ---------- Screen 4 · Vertrag prüfen + unterschreiben (nach SEPA) */
function ScreenSign({ form, set, errors, building, unit, mandate, mandatePending, demo, onShowContract }) {
  const mandateOk = mandate && (mandate.authorised || ['active','submitted','pending_submission'].includes(mandate.mandate_status));
  return (
    <div className="pm-page pm-anim">
      <div className="pm-eyebrow">Schritt 4 · Vertrag</div>
      <h1 className="pm-h1">Vertrag prüfen &amp; unterschreiben</h1>
      <p className="pm-lead">Letzter Schritt: Vertrag öffnen, prüfen und rechtsgültig unterschreiben.</p>

      <div className="pm-card"><div className="pm-card-pad">
        <div style={{display:'flex',alignItems:'center',gap:10}}>
          {(mandateOk && !demo) ? <I.check size={20} style={{color:'var(--positive)'}}/> : <I.euro size={20} style={{color:'var(--accent)'}}/>}
          <div><div className="pm-card-title">{demo ? 'SEPA-Mandat (Demo)' : (mandateOk ? 'SEPA-Mandat erteilt' : mandatePending ? 'SEPA-Mandat folgt' : 'SEPA-Mandat in Prüfung')}</div>
          <div className="pm-card-sub">{mandatePending && !demo ? 'Wir richten das Lastschriftmandat separat mit Ihnen ein.' : 'Zahlung per SEPA-Lastschrift eingerichtet.'}</div></div>
        </div>
        <hr className="pm-divider" />
        <div className="pm-prefill"><dl style={{margin:0}}>
          <div className="pm-prefill-row"><dt>Vertrag</dt><dd>{TARIFF.name}</dd></div>
          <div className="pm-prefill-row"><dt>Wohneinheit</dt><dd>{unit.we} · {building.strasse} {building.hausnr}</dd></div>
          <div className="pm-prefill-row"><dt>Arbeitspreis</dt><dd>{TARIFF.arbeitspreis}</dd></div>
          <div className="pm-prefill-row"><dt>Lieferbeginn</dt><dd>{building.lieferbeginn}</dd></div>
        </dl></div>
        <div style={{marginTop:14}}><Button kind="ghost" onClick={onShowContract}><I.doc size={16}/> Vollständigen Vertrag öffnen</Button></div>
      </div></div>

      <div className="pm-card"><div className="pm-card-pad">
        <div className="pm-card-head"><I.pen size={20} style={{color:'var(--accent)'}} /><div><div className="pm-card-title">Unterschrift</div><div className="pm-card-sub">{form.vorname} {form.nachname} · {unit.we}, {adresseOf(building)}</div></div></div>
        <div style={{marginTop:14}}><SignaturePad onChange={(d) => set('signature', d)} error={errors.signature} /></div>
      </div></div>
    </div>
  );
}

/* ---------- Success ---------------------------------------------- */
function Screen4({ form, building, unit, mandate, mandatePending, demo, mode, onRestart }) {
  const mandateOk = mandate && (mandate.authorised || ['active','submitted','pending_submission'].includes(mandate.mandate_status));
  return (
    <div className="pm-page">
      <div className="pm-success pm-anim">
        <div className="pm-success-ring"><I.check size={44} sw={2.4} /></div>
        <h1 className="pm-h1">Vertrag abgeschlossen 🎉</h1>
        <p className="pm-lead" style={{margin:'0 auto 6px'}}>
          {form.vorname ? `${form.vorname}, Ihre` : 'Ihre'} Wohnung <b>{unit ? unit.we : ''}</b>{building ? ` in ${building.strasse} ${building.hausnr}` : ''} ist registriert.
        </p>
        <div style={{display:'flex',gap:8,flexWrap:'wrap',justifyContent:'center',marginTop:10}}>
          <span className="pm-badge"><I.euro size={15}/> {demo ? 'SEPA (Demo)' : mandatePending ? 'SEPA-Mandat folgt' : (mandateOk ? 'SEPA-Mandat erteilt' : 'SEPA-Mandat in Prüfung')}</span>
          <span className="pm-badge" style={{background:'var(--accent-tint)',color:'var(--accent)',borderColor:'var(--accent-tint-border)'}}><I.pen size={15}/> Vertrag unterschrieben</span>
        </div>
        <div className="pm-success-steps">
          <div className="pm-success-step"><span className="pm-num">1</span><div><b>SEPA-Lastschriftmandat</b> {mandatePending ? '– wir richten es gemeinsam mit Ihnen ein.' : (mandateOk ? 'erteilt.' : 'wird bei Ihrer Bank aktiviert.')}</div></div>
          <div className="pm-success-step"><span className="pm-num">2</span><div><b>Vertrag &amp; Unterschrift</b> erfasst – Bestätigung mit Vertrag kommt per E-Mail an {form.email || 'Ihre Adresse'}.</div></div>
          <div className="pm-success-step"><span className="pm-num">3</span><div><b>Lieferbeginn {building ? building.lieferbeginn : ''}</b> – ab dann fließt Solarstrom vom Dach. Wir kündigen Ihren alten Vertrag{form.anbieter ? ` bei ${form.anbieter}` : ''}.</div></div>
        </div>
        {mode === 'rep' && <div style={{marginTop:28}}><Button kind="primary" lg onClick={onRestart}>Nächster Mieter <I.arrow size={18}/></Button></div>}
      </div>
    </div>
  );
}

/* ---------- Contract preview modal (popup-blocked fallback) ------ */
function ContractModal({ html, onClose }) {
  return (
    <div className="pm-modal-overlay" onClick={onClose}>
      <div className="pm-modal" onClick={(e) => e.stopPropagation()}>
        <div className="pm-modal-head">
          <span><I.doc size={17} style={{ verticalAlign: '-3px', marginRight: 6, color: 'var(--accent)' }} />Vertragsvorschau</span>
          <button className="pm-modal-x" onClick={onClose} aria-label="Schließen">×</button>
        </div>
        {html ? <iframe className="pm-modal-frame" srcDoc={html} title="Vertrag" />
              : <div className="pm-modal-loading"><span className="pm-spin" /> Vertrag wird geladen…</div>}
      </div>
    </div>
  );
}

/* ---------- Root controller -------------------------------------- */
const EMPTY = { vorname:'', nachname:'', email:'', telefon:'', zaehlernr:'', zaehlerstand:'', ablesedatum:'', zaehlerFoto:'', anbieter:'', kundennr:'', dsgvo:false, v_agb:false, v_widerruf:false, v_sepa:false, signature:'' };

function App() {
  const qs = new URLSearchParams(location.search);
  const ret = qs.get('step');                                   // sepa_ok | sepa_abbruch | null
  const retOid = qs.get('oid') || (typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('pm_oid') : null);
  let ctx = null;
  try { ctx = retOid ? JSON.parse(sessionStorage.getItem('pm_ctx_' + retOid) || 'null') : null; } catch (e) {}

  const mode = qs.get('mode') === 'rep' ? 'rep' : 'self';
  const building0 = ctx ? getBuilding(ctx.buildingId) : getBuilding(qs.get('b'));
  const unit0 = ctx ? getUnit(building0, ctx.we) : (qs.get('we') ? getUnit(building0, qs.get('we')) : null);
  const resuming = ret === 'sepa_ok' && ctx;

  const [step, setStep] = useState(resuming ? 4 : 1);
  const [done, setDone] = useState(false);
  const [maxReached, setMaxReached] = useState(resuming ? 4 : 1);
  const [unit, setUnit] = useState(unit0);
  const [building] = useState(building0);
  const [form, setForm] = useState(ctx ? { ...EMPTY, ...ctx.form, signature: '' } : { ...EMPTY, ablesedatum: TODAY });
  const [errors, setErrors] = useState({});
  const [busy, setBusy] = useState(false);
  const [submitErr, setSubmitErr] = useState(ret === 'sepa_abbruch' ? 'SEPA-Mandat abgebrochen. Bitte erneut starten.' : '');
  const [mandate, setMandate] = useState(null);
  const [mandatePending, setMandatePending] = useState(false);
  const [demo, setDemo] = useState(false);
  const [contractOpen, setContractOpen] = useState(false);
  const [contractHtml, setContractHtml] = useState(null);

  useEffect(() => { if (unit && !form.zaehlernr) setForm((f) => ({ ...f, zaehlernr: unit.zaehler })); }, [unit]);

  // On return from GoCardless: read mandate status (form is restored from ctx; user now signs).
  useEffect(() => {
    if (!resuming) return;
    (async () => {
      const tq = (ctx && ctx.status_token) ? `&t=${encodeURIComponent(ctx.status_token)}` : '';
      try { const s = await fetch(`./api/gocardless-status.php?oid=${encodeURIComponent(retOid)}${tq}`).then(r => r.json()); setMandate(s); } catch (e) {}
      try { history.replaceState(null, '', location.pathname); } catch (e) {}   // keep pm_oid in storage for finalize
    })();
  }, []);

  const set = useCallback((name, value) => {
    setForm((f) => ({ ...f, [name]: value }));
    setErrors((e) => (e[name] ? { ...e, [name]: undefined } : e));
  }, []);
  const go = (n) => { setStep(n); setMaxReached((m) => Math.max(m, n)); window.scrollTo({ top: 0, behavior: 'smooth' }); };

  const validate = (n) => {
    const e = {};
    if (n === 1 && !unit) e.we = 'Bitte Wohnung wählen';
    if (n === 2) {
      if (!form.vorname.trim()) e.vorname = 'Pflichtfeld';
      if (!form.nachname.trim()) e.nachname = 'Pflichtfeld';
      if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) e.email = 'Gültige E-Mail nötig';
      if (form.telefon.replace(/\D/g,'').length < 6) e.telefon = 'Gültige Nummer nötig';
      if (!(form.zaehlernr || (unit && unit.zaehler))) e.zaehlernr = 'Pflichtfeld';
      if (!/\d/.test(form.zaehlerstand || '')) e.zaehlerstand = 'Zählerstand eingeben';
      if (!form.zaehlerFoto) e.zaehlerFoto = 'Bitte ein Foto des Zählerstands aufnehmen';
    }
    if (n === 3) {
      if (!form.v_agb) e.v_agb = 'Erforderlich';
      if (!form.v_widerruf) e.v_widerruf = 'Erforderlich';
      if (!form.dsgvo) e.dsgvo = 'Erforderlich';
      if (!form.v_sepa) e.v_sepa = 'Erforderlich';
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const payload = (oid) => {
    const { signature, zaehlerFoto, ...formLite } = form;
    return {
      onboarding_id: oid || null,
      building: { id: building.id, name: building.name, adresse: adresseOf(building), lieferbeginn: building.lieferbeginn },
      unit: { we: unit.we, etage: unit.etage, klingel: unit.klingel, zaehler: unit.zaehler },
      meter: { nummer: form.zaehlernr || (unit && unit.zaehler), stand: form.zaehlerstand, ablesedatum: form.ablesedatum, foto: zaehlerFoto },
      signature, tariff: TARIFF, form: formLite, mode, ts: new Date().toISOString(),
    };
  };

  const openContract = async () => {
    const w = window.open('', '_blank');
    if (w) { try { w.document.write('<!doctype html><meta charset="utf-8"><title>Mieterstrom-Vertrag</title><body style="margin:0;font-family:system-ui,sans-serif;padding:40px;color:#5b6b80">Vertrag wird geladen…</body>'); } catch (e) {} }
    const showDoc = (html) => { if (w) { try { w.document.open(); w.document.write(html); w.document.close(); return; } catch (e) {} } setContractHtml(html); setContractOpen(true); };
    if (location.protocol === 'file:') { showDoc('<!doctype html><meta charset="utf-8"><body style="font-family:system-ui,sans-serif;padding:40px;color:#5b6b80">Die Vertragsvorschau wird im Live-Betrieb vom Server gerendert.</body>'); return; }
    try { showDoc(await fetch('./api/contract-preview.php', { method:'POST', headers:JSON_HEADERS, body: JSON.stringify(payload()) }).then(r => r.text())); }
    catch (e) { showDoc('<!doctype html><meta charset="utf-8"><body style="font-family:system-ui,sans-serif;padding:40px">Vorschau nicht verfügbar.</body>'); }
  };

  // Step 3 → set up SEPA mandate first (GoCardless), then go to the signing step.
  const startSepa = async () => {
    if (!validate(3)) { window.scrollTo({ top: 0, behavior: 'smooth' }); return; }
    setBusy(true); setSubmitErr('');
    const toSign = (pending) => { setMandatePending(pending); setBusy(false); go(4); };
    if (location.protocol === 'file:') { setDemo(true); toSign(true); return; }
    try {
      const gc = await fetch('./api/gocardless-create.php', { method:'POST', headers:JSON_HEADERS, body: JSON.stringify({
        form: { vorname: form.vorname, nachname: form.nachname, email: form.email }, building: { adresse: adresseOf(building) },
      }) }).then(r => r.json()).catch(() => null);
      if (gc && gc.ok && gc.authorisation_url) {
        const oid = gc.onboarding_id;
        sessionStorage.setItem('pm_oid', oid);
        sessionStorage.setItem('pm_ctx_' + oid, JSON.stringify({ buildingId: building.id, we: unit.we, form, status_token: gc.status_token }));
        window.location.href = gc.authorisation_url;       // off-site → GoCardless SEPA page
        return;
      }
      toSign(true);   // GoCardless unavailable → finish the contract, set mandate up separately
    } catch (e) { toSign(true); }
  };

  // Step 4 → contract is signed; finalize (create record + signed contract + email).
  const finalizeContract = async () => {
    if (!form.signature) { setErrors({ signature: 'Bitte unterschreiben' }); window.scrollTo({ top: 0, behavior: 'smooth' }); return; }
    setBusy(true); setSubmitErr('');
    if (location.protocol === 'file:') { await new Promise((r) => setTimeout(r, 500)); setDemo(true); setBusy(false); setDone(true); window.scrollTo({ top: 0 }); return; }
    let oid = null; try { oid = sessionStorage.getItem('pm_oid'); } catch (e) {}
    try {
      const res = await fetch('./api/submit.php', { method:'POST', headers:JSON_HEADERS, body: JSON.stringify(payload(oid)) }).then(r => r.json());
      if (!res.ok) throw new Error(res.error || 'Abschluss fehlgeschlagen');
      try { Object.keys(sessionStorage).filter(k => k.startsWith('pm_')).forEach(k => sessionStorage.removeItem(k)); } catch (e) {}
      setBusy(false); setDone(true); window.scrollTo({ top: 0 });
    } catch (e) { setSubmitErr('Abschluss fehlgeschlagen: ' + e.message); setBusy(false); }
  };

  const next = () => { if (!validate(step)) { window.scrollTo({ top: 0, behavior: 'smooth' }); return; } if (step < 3) go(step + 1); };

  const restart = () => {
    try { Object.keys(sessionStorage).filter(k => k.startsWith('pm_')).forEach(k => sessionStorage.removeItem(k)); } catch (e) {}
    history.replaceState(null, '', location.pathname + (mode === 'rep' ? `?mode=rep&b=${building.id}` : `?b=${building.id}`));
    setForm({ ...EMPTY, ablesedatum: TODAY }); setUnit(null); setErrors({}); setMandate(null); setDemo(false); setMandatePending(false);
    setSubmitErr(''); setDone(false); setStep(1); setMaxReached(1); window.scrollTo({ top: 0 });
  };

  const toggleTheme = () => {
    const cur = document.documentElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'light';
    const nx = cur === 'dark' ? 'light' : 'dark';
    document.documentElement.setAttribute('data-theme', nx);
    try { localStorage.setItem('pm_theme', JSON.stringify(nx)); } catch (e) {}
  };

  const showCta = ((step === 1 && mode === 'self') || step === 2 || step === 3 || (step === 4 && !done));
  const primary = step === 3 ? startSepa : step === 4 ? finalizeContract : next;

  return (
    <div className="pm-embed">
      {mode === 'rep' && <div className="pm-repbar"><span className="pm-repbar-tag">Vertriebsmodus</span><span>{building.name}{unit ? ` · ${unit.we}` : ''}</span></div>}

      <header className="pm-topbar">
        <Logo size={34} />
        <div className="pm-topbar-help">
          <I.shield size={17} style={{ color: 'var(--positive)' }} />
          <span className="pm-hide-sm">Geprüfter Mieterstrom-Anbieter</span>
          <span className="pm-sep pm-hide-sm" />
          <a className="pm-link pm-hide-sm" href="mailto:hilfe@powermieter.de">hilfe@powermieter.de</a>
          <button className="pm-theme-toggle" onClick={toggleTheme} aria-label="Theme wechseln"><I.moon size={16} /></button>
        </div>
      </header>

      {!done && (
        <div className="pm-stepbar"><div className="pm-stepbar-inner">
          <ProcessNav current={step} maxReached={maxReached} onJump={(n) => step < 4 && n < step && go(n)} />
        </div></div>
      )}

      <div className="pm-stage">
        {step === 1 && <Screen1 mode={mode} building={building} unit={unit} setUnit={setUnit} onNext={() => go(2)} />}
        {step === 2 && <Screen2 form={form} set={set} errors={errors} building={building} unit={unit} />}
        {step === 3 && <ScreenSepa form={form} set={set} errors={errors} building={building} unit={unit} onShowContract={openContract} />}
        {step === 4 && !done && <ScreenSign form={form} set={set} errors={errors} building={building} unit={unit} mandate={mandate} mandatePending={mandatePending} demo={demo} onShowContract={openContract} />}
        {step === 4 && done && <Screen4 form={form} building={building} unit={unit} mandate={mandate} mandatePending={mandatePending} demo={demo} mode={mode} onRestart={restart} />}
      </div>

      {showCta && (
        <div className="pm-bottomcta">
          <div>
            {(step === 2 || step === 3) ? <Button kind="ghost" onClick={() => go(step - 1)}><I.back size={17}/> Zurück</Button>
                      : <span className="pm-cta-meta"><I.lock size={14} style={{verticalAlign:'-2px'}}/> Sichere Datenübertragung</span>}
            {submitErr && <div className="pm-err" style={{marginTop:4}}>{submitErr}</div>}
          </div>
          <Button kind="primary" lg busy={busy} disabled={busy || (step === 1 && !unit)} onClick={primary}>
            {step === 3 ? <><I.euro size={18}/>Weiter zum SEPA-Mandat</> : step === 4 ? <><I.pen size={18}/>Kostenpflichtig abschließen</> : <>Weiter<I.arrow size={18}/></>}
          </Button>
        </div>
      )}

      {contractOpen && <ContractModal html={contractHtml} onClose={() => setContractOpen(false)} />}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
