/* Powermieter — Vertrag digital abschließen (fokussierter Signatur-Screen / Overlay) */
const { useState: useSgS, useRef: useSgR, useEffect: useSgE } = React;

function SignaturePad({ onInk }) {
  const ref = useSgR(null);
  const drawing = useSgR(false);
  const last = useSgR(null);
  const inked = useSgR(false);

  useSgE(() => {
    const c = ref.current; if (!c) return;
    const dpr = window.devicePixelRatio || 1;
    const rect = c.getBoundingClientRect();
    c.width = rect.width * dpr; c.height = rect.height * dpr;
    const ctx = c.getContext('2d');
    ctx.scale(dpr, dpr);
    ctx.lineWidth = 2.4; ctx.lineCap = 'round'; ctx.lineJoin = 'round';
    ctx.strokeStyle = getComputedStyle(c).getPropertyValue('--accent').trim() || '#0E7C86';
  }, []);

  const pos = e => {
    const r = ref.current.getBoundingClientRect();
    const p = e.touches ? e.touches[0] : e;
    return { x: p.clientX - r.left, y: p.clientY - r.top };
  };
  const start = e => { e.preventDefault(); drawing.current = true; last.current = pos(e); };
  const move = e => {
    if (!drawing.current) return; e.preventDefault();
    const ctx = ref.current.getContext('2d');
    const p = pos(e);
    ctx.beginPath(); ctx.moveTo(last.current.x, last.current.y); ctx.lineTo(p.x, p.y); ctx.stroke();
    last.current = p;
    if (!inked.current) { inked.current = true; onInk(true); }
  };
  const end = () => { drawing.current = false; };
  const clear = () => {
    const c = ref.current; const ctx = c.getContext('2d');
    ctx.clearRect(0, 0, c.width, c.height); inked.current = false; onInk(false);
  };

  return (
    <div className="pm-sg-pad-wrap">
      <canvas ref={ref} className="pm-sg-canvas"
        onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end}
        onTouchStart={start} onTouchMove={move} onTouchEnd={end} />
      <span className="pm-sg-baseline" />
      <button className="pm-sg-clear" onClick={clear} type="button"><I.refresh size={13} /> Neu</button>
    </div>
  );
}

function SigningScreen({ form, model = 'mieterstrom', onClose, onDone }) {
  const mdl = VERTRAGSMODELLE[model] || VERTRAGSMODELLE.mieterstrom;
  const name = [form.vorname, form.nachname].filter(Boolean).join(' ') || 'Max Mustermann';
  const adr = [form.strasse + ' ' + (form.hausnr || ''), [form.plz, form.ort].filter(Boolean).join(' ')].filter(s => s.trim()).join(', ') || 'Musterstraße 12, 10115 Berlin';
  const today = new Date().toLocaleDateString('de-DE', { day: '2-digit', month: 'long', year: 'numeric' });

  const [mode, setMode] = useSgS('draw');
  const [hasInk, setHasInk] = useSgS(false);
  const [typed, setTyped] = useSgS('');
  const [place, setPlace] = useSgS(form.ort || 'Berlin');
  const [confirm, setConfirm] = useSgS(false);
  const [phase, setPhase] = useSgS('sign'); // sign → signing → done

  const docName = model === 'ggv' ? 'Teilnahme- & Verteilvereinbarung' : 'Teilnahme- & Stromliefervertrag';
  const docs = (ROLE_CONTRACTS[mieterSetFor(model)] || ROLE_CONTRACTS.mieter_mieterstrom).items;
  const signedOk = (mode === 'draw' ? hasInk : typed.trim().length > 1) && confirm;

  const submit = () => {
    if (!signedOk) return;
    setPhase('signing');
    setTimeout(() => setPhase('done'), 1700);
  };

  return (
    <div className="pm-sg-scrim">
      <div className="pm-sg">
        <header className="pm-sg-top">
          <div className="pm-sg-top-id">
            <span className="pm-sg-logo"><img src="assets/ph360-mark.png" alt="PowerHouse 360" style={{ height: 26, width: 'auto', display: 'block' }} /></span>
            <div>
              <div className="pm-sg-ey">Vertrag digital abschließen</div>
              <div className="pm-sg-title">{mdl.label} <span className="pm-sg-legal">{mdl.legal}</span></div>
            </div>
          </div>
          <button className="pm-iconbtn" onClick={onClose} aria-label="Schließen"><I.x size={18} /></button>
        </header>

        {phase !== 'done' ? (
          <div className="pm-sg-body thin-scroll">
            {/* Document preview */}
            <div className="pm-sg-doc">
              <div className="pm-sg-doc-page">
                <div className="pm-sg-doc-head">
                  <div className="pm-sg-doc-brand"><img src="assets/ph360-mark.png" alt="" style={{ height: 18, width: 'auto', display: 'block' }} /> PowerHouse 360</div>
                  <span className="pm-sg-doc-tag mono">PM-TN-{model.slice(0, 3).toUpperCase()} · v2.1</span>
                </div>
                <h2 className="pm-sg-doc-h">{docName}</h2>
                <p className="pm-sg-doc-lead">zwischen <strong>{LEGAL_ENTITY.name}</strong> (Betreiber) und dem nachstehenden Teilnehmer für die Versorgung im Objekt {OBJEKT.name}.</p>
                <div className="pm-sg-doc-fields">
                  <div className="pm-sg-df"><span>Teilnehmer</span><b>{name}</b></div>
                  <div className="pm-sg-df"><span>Anschrift</span><b>{adr}</b></div>
                  <div className="pm-sg-df"><span>Modell</span><b>{mdl.label}</b></div>
                  <div className="pm-sg-df"><span>Tarif</span><b>Powermieter Lokalstrom · 28,9 ct/kWh</b></div>
                  <div className="pm-sg-df"><span>Laufzeit</span><b>12 Monate · 1 Monat Kündigungsfrist</b></div>
                  <div className="pm-sg-df"><span>Lieferbeginn</span><b>Schnellstmöglich</b></div>
                </div>
                <p className="pm-sg-doc-body">Mit der Unterzeichnung bestätigt der Teilnehmer die Geltung der beigefügten Vertragsdokumente und Preisinformationen. Das gesetzliche Widerrufsrecht von 14 Tagen bleibt unberührt.</p>
                <div className="pm-sg-doc-incl">
                  {docs.slice(0, 5).map((d, i) => <span key={i} className="pm-sg-doc-chip"><I.doc size={11} /> {d.name}</span>)}
                </div>
              </div>
            </div>

            {/* Signing panel */}
            <div className="pm-sg-panel">
              <h3 className="pm-sg-panel-h">Ihre Unterschrift</h3>
              <Segmented value={mode} onChange={setMode} options={[
                { value: 'draw', label: 'Zeichnen', icon: <I.signature /> },
                { value: 'type', label: 'Tippen', icon: <I.user /> },
              ]} />

              {mode === 'draw'
                ? <div style={{ marginTop: 14 }}><SignaturePad onInk={setHasInk} /><p className="pm-sg-hint">Mit Maus oder Finger im Feld unterschreiben.</p></div>
                : <div style={{ marginTop: 14 }}>
                    <div className="pm-sigpad">
                      <input className="pm-sigpad-input" placeholder="Vollständigen Namen eingeben …" value={typed} onChange={e => setTyped(e.target.value)} />
                      <span className="pm-sigpad-line" />
                      <span className="pm-sigpad-hint">{name}</span>
                    </div>
                    <p className="pm-sg-hint">Die getippte Eingabe gilt als digitale Unterschrift.</p>
                  </div>}

              <div className="pm-sg-meta">
                <div className="pm-sg-meta-i"><span>Ort</span><input className="pm-sg-place" value={place} onChange={e => setPlace(e.target.value)} /></div>
                <div className="pm-sg-meta-i"><span>Datum</span><b>{today}</b></div>
              </div>

              <label className="pm-sg-confirm">
                <Checkbox checked={confirm} onChange={setConfirm}>Ich schließe den <strong>{docName}</strong> rechtsverbindlich ab und habe die Widerrufsbelehrung erhalten.</Checkbox>
              </label>

              <Button block size="lg" disabled={!signedOk || phase === 'signing'} icon={phase === 'signing' ? null : <I.lock size={17} />} onClick={submit}>
                {phase === 'signing' ? 'Wird abgeschlossen …' : 'Jetzt verbindlich abschließen'}
              </Button>
              <div className="pm-sg-trust"><I.shield size={14} /> Verschlüsselte Übertragung · revisionssicher protokolliert (contract_events)</div>
            </div>
          </div>
        ) : (
          <div className="pm-sg-done">
            <div className="pm-sg-done-ring"><I.check size={42} /></div>
            <h2 className="pm-sg-done-h">Vertrag digital abgeschlossen</h2>
            <p className="pm-sg-done-s">Ihr {docName} wurde unterzeichnet und an <strong>{form.email || 'Ihre E-Mail-Adresse'}</strong> gesendet. Eine Kopie liegt in Ihrem Powermieter-Portal.</p>
            <div className="pm-sg-receipt">
              <div className="pm-sg-rrow"><span>Dokument</span><b>{docName}</b></div>
              <div className="pm-sg-rrow"><span>Unterzeichner</span><b>{name}</b></div>
              <div className="pm-sg-rrow"><span>Signatur</span><b>{place}, {today}</b></div>
              <div className="pm-sg-rrow"><span>Status</span><b className="pm-sg-rstatus"><span className="pm-sbadge-dot" style={{ background: 'var(--positive-500)' }} /> Unterzeichnet</b></div>
            </div>
            <Button block size="lg" icon={<I.arrowR />} onClick={onDone}>Weiter zur Aktivierung</Button>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { SigningScreen });
