// portal-esign.jsx — Legally-binding signing flow for the documents inbox.
// Steps: consent (ESIGN disclosure) → review → adopt signature (typed/drawn)
// → sealed certificate. Uses window.RFPsign; persists by docId.

function ESignModal({ open, doc, onClose, onComplete }) {
  const { me } = usePortal();
  const [step, setStep] = useState('consent'); // consent | review | sign | done
  const [consented, setConsented] = useState(false);
  const [method, setMethod] = useState('typed');
  const [typed, setTyped] = useState('');
  const [env, setEnv] = useState(null);
  const canvasRef = useRef(null);
  const drawing = useRef(false);
  const hasDrawn = useRef(false);

  useEffect(() => {
    if (open && doc) {
      setStep('consent'); setConsented(false); setMethod('typed'); setTyped(me.name); hasDrawn.current = false;
      const e = RFPsign.createEnvelope({ docId: doc.id, title: doc.title, body: doc.body || `${doc.title} — issued by ${doc.from}`, signer: { id: me.id, name: me.name, email: me.email } });
      setEnv(e);
    }
  }, [open, doc]);

  if (!open || !doc || !env) return null;

  // Canvas drawing
  const pos = (e) => {
    const r = canvasRef.current.getBoundingClientRect();
    const t = e.touches ? e.touches[0] : e;
    return { x: t.clientX - r.left, y: t.clientY - r.top };
  };
  const start = (e) => { drawing.current = true; const c = canvasRef.current.getContext('2d'); const p = pos(e); c.beginPath(); c.moveTo(p.x, p.y); };
  const move = (e) => { if (!drawing.current) return; e.preventDefault(); const c = canvasRef.current.getContext('2d'); const p = pos(e); c.lineTo(p.x, p.y); c.strokeStyle = '#0F172A'; c.lineWidth = 2.5; c.lineCap = 'round'; c.stroke(); hasDrawn.current = true; };
  const end = () => { drawing.current = false; };
  const clearCanvas = () => { const c = canvasRef.current; c.getContext('2d').clearRect(0, 0, c.width, c.height); hasDrawn.current = false; };

  const doConsent = () => {
    RFPsign.recordConsent(env);
    setEnv({ ...env });
    setStep('review');
  };

  const doSign = () => {
    let value;
    if (method === 'typed') { if (!typed.trim()) return; value = typed; }
    else { if (!hasDrawn.current) return; value = canvasRef.current.toDataURL('image/png'); }
    const session = (window.RFP && RFP.session()) || {};
    RFPsign.applySignature(env, { method, value, sessionToken: session.token });
    RFPsign.persist(env);
    setEnv({ ...env });
    setStep('done');
  };

  const finish = () => { onComplete && onComplete(env); onClose(); };

  const steps = [['consent', 'Consent'], ['review', 'Review'], ['sign', 'Sign'], ['done', 'Certificate']];
  const stepIdx = steps.findIndex(s => s[0] === step);

  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, background: 'rgba(15,23,42,0.55)' }}>
      <div className="anim-up" style={{ width: 600, maxHeight: '92%', background: 'var(--paper)', borderRadius: 16, boxShadow: 'var(--shadow-lg)', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        {/* Header + stepper */}
        <div style={{ padding: '16px 22px', borderBottom: '1px solid var(--line)', background: 'var(--panel)' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
            <div style={{ fontWeight: 700, fontSize: 15.5 }}>Sign · {doc.title}</div>
            <button onClick={onClose} style={{ width: 30, height: 30, borderRadius: 15, border: 'none', background: 'var(--panel-3)', cursor: 'pointer' }}><IconClose size={15} /></button>
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            {steps.map((s, i) => (
              <div key={s[0]} style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 6 }}>
                <div style={{ width: 20, height: 20, borderRadius: 10, fontSize: 10.5, fontWeight: 700, display: 'grid', placeItems: 'center', background: i < stepIdx ? 'var(--good)' : i === stepIdx ? 'var(--accent)' : 'var(--panel-3)', color: i <= stepIdx ? '#fff' : 'var(--muted)' }}>{i < stepIdx ? '✓' : i + 1}</div>
                <span style={{ fontSize: 11.5, fontWeight: i === stepIdx ? 600 : 500, color: i === stepIdx ? 'var(--text)' : 'var(--muted)' }}>{s[1]}</span>
              </div>
            ))}
          </div>
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: 22 }}>
          {step === 'consent' && (
            <>
              <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 8 }}>Electronic record & signature disclosure</div>
              <div style={{ fontSize: 13, color: 'var(--text-2)', lineHeight: 1.6, background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 10, padding: '14px 16px', maxHeight: 220, overflowY: 'auto' }}>
                <p style={{ marginTop: 0 }}>By selecting <b>I agree</b>, you consent to use electronic records and signatures for this document under the U.S. ESIGN Act (15 U.S.C. ch. 96) and the Uniform Electronic Transactions Act (UETA).</p>
                <p>You confirm that you can access and retain this document, that your electronic signature is the legal equivalent of your handwritten signature, and that it is attributable to you as the signed-in user <b>{me.name}</b> ({me.email}).</p>
                <p style={{ marginBottom: 0 }}>You may request a paper copy or withdraw consent before signing by contacting HR. After signing, a certificate of completion with a tamper-evident document hash will be issued.</p>
              </div>
              <label style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 14, cursor: 'pointer' }}>
                <input type="checkbox" checked={consented} onChange={e => setConsented(e.target.checked)} style={{ width: 17, height: 17 }} />
                <span style={{ fontSize: 13.5, fontWeight: 500 }}>I agree to use electronic records and signatures.</span>
              </label>
            </>
          )}

          {step === 'review' && (
            <>
              <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 8 }}>Review document</div>
              <div style={{ background: '#fff', border: '1px solid var(--line)', borderRadius: 10, padding: '20px 22px', boxShadow: 'var(--shadow-sm)' }}>
                <div style={{ fontWeight: 700, fontSize: 16, marginBottom: 4 }}>{doc.title}</div>
                <div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 14 }}>From {doc.from} · {P_date(doc.sent)}</div>
                <div style={{ fontSize: 13.5, lineHeight: 1.7, color: 'var(--text-2)' }}>
                  {doc.body || `This document (${doc.title}) requires your acknowledgement and signature. By signing you confirm you have read, understood, and agree to its contents as a condition of your continued assignment with RailFlagsPro.`}
                </div>
                <div style={{ marginTop: 16, paddingTop: 12, borderTop: '1px dashed var(--line-strong)', fontSize: 11, color: 'var(--muted)', fontFamily: 'var(--font-mono)' }}>
                  Document hash: {env.contentHash}
                </div>
              </div>
            </>
          )}

          {step === 'sign' && (
            <>
              <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 10 }}>Adopt your signature</div>
              <div style={{ display: 'flex', gap: 6, background: 'var(--panel-2)', border: '1px solid var(--line)', borderRadius: 10, padding: 3, marginBottom: 14 }}>
                {[['typed', 'Type it'], ['drawn', 'Draw it']].map(([m, label]) => (
                  <button key={m} onClick={() => setMethod(m)} style={{ flex: 1, padding: '7px 10px', border: 'none', borderRadius: 7, cursor: 'pointer', background: method === m ? 'var(--panel)' : 'transparent', boxShadow: method === m ? 'var(--shadow-sm)' : 'none', fontWeight: method === m ? 600 : 500, fontSize: 12.5, color: method === m ? 'var(--text)' : 'var(--muted)' }}>{label}</button>
                ))}
              </div>
              {method === 'typed' ? (
                <>
                  <input value={typed} onChange={e => setTyped(e.target.value)} style={{ ...pInputStyle, fontSize: 15 }} placeholder="Type your full legal name" />
                  <div style={{ marginTop: 12, background: '#fff', border: '1px solid var(--line)', borderRadius: 10, padding: '20px', textAlign: 'center' }}>
                    <div style={{ fontFamily: 'cursive', fontSize: 34, color: '#0F172A', lineHeight: 1 }}>{typed || 'Your name'}</div>
                    <div style={{ fontSize: 10.5, color: 'var(--muted)', marginTop: 8, fontFamily: 'var(--font-mono)' }}>Adopted signature · {me.name}</div>
                  </div>
                </>
              ) : (
                <>
                  <canvas ref={canvasRef} width={540} height={170}
                    onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end}
                    onTouchStart={start} onTouchMove={move} onTouchEnd={end}
                    style={{ width: '100%', height: 170, background: '#fff', border: '1px solid var(--line-strong)', borderRadius: 10, cursor: 'crosshair', touchAction: 'none' }} />
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8 }}>
                    <span style={{ fontSize: 11.5, color: 'var(--muted)' }}>Draw your signature above</span>
                    <button onClick={clearCanvas} style={{ background: 'none', border: 'none', color: 'var(--accent-deep)', fontWeight: 600, fontSize: 12.5, cursor: 'pointer' }}>Clear</button>
                  </div>
                </>
              )}
              <div style={{ marginTop: 14, background: 'var(--info-soft)', color: 'var(--info)', borderRadius: 8, padding: '9px 12px', fontSize: 12, lineHeight: 1.5 }}>
                Signing binds your identity ({me.name}), a timestamp, and the document hash into a sealed certificate.
              </div>
            </>
          )}

          {step === 'done' && env.certificate && (
            <>
              <div style={{ textAlign: 'center', padding: '8px 0 16px' }}>
                <div style={{ width: 56, height: 56, borderRadius: 28, background: 'var(--good-soft)', color: 'var(--good)', display: 'grid', placeItems: 'center', margin: '0 auto 12px' }}><IconCheckCircle size={30} /></div>
                <div style={{ fontSize: 18, fontWeight: 700 }}>Signed & sealed</div>
                <div style={{ fontSize: 13, color: 'var(--muted)', marginTop: 2 }}>Certificate of completion issued</div>
              </div>
              <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 10, overflow: 'hidden' }}>
                {[
                  ['Certificate ID', env.certificate.certId],
                  ['Signer', env.signer.name],
                  ['Signed at', new Date(env.signature.signedAt).toLocaleString('en-US')],
                  ['Document hash', env.contentHash],
                  ['Method', env.signature.method],
                ].map(([k, v], i) => (
                  <div key={k} style={{ display: 'flex', justifyContent: 'space-between', gap: 12, padding: '10px 14px', borderTop: i === 0 ? 'none' : '1px solid var(--line)' }}>
                    <span style={{ fontSize: 12.5, color: 'var(--muted)' }}>{k}</span>
                    <span className="mono" style={{ fontSize: 12, fontWeight: 600, textAlign: 'right', wordBreak: 'break-all' }}>{v}</span>
                  </div>
                ))}
              </div>
            </>
          )}
        </div>

        {/* Footer */}
        <div style={{ padding: '14px 22px', borderTop: '1px solid var(--line)', background: 'var(--panel)', display: 'flex', justifyContent: 'space-between', gap: 10 }}>
          <Button variant="secondary" onClick={onClose}>{step === 'done' ? 'Close' : 'Cancel'}</Button>
          <div style={{ display: 'flex', gap: 10 }}>
            {step === 'consent' && <Button variant="primary" disabled={!consented} onClick={doConsent}>Agree & continue</Button>}
            {step === 'review' && <Button variant="primary" iconRight={<IconArrowRight size={14} />} onClick={() => setStep('sign')}>Continue to sign</Button>}
            {step === 'sign' && <Button variant="primary" icon={<IconSignature size={14} />} onClick={doSign}>Sign document</Button>}
            {step === 'done' && (
              <>
                <Button variant="secondary" icon={<IconDownload size={14} />} onClick={() => downloadBlob(`certificate-${env.certificate.certId}.txt`, RFPsign.certificateText(env), 'text/plain')}>Certificate</Button>
                <Button variant="primary" icon={<IconCheck size={14} />} onClick={finish}>Done</Button>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ESignModal });
