// InstantDevis — Signature Tactile (Canvas) + sceau documentaire (snapshot + SHA-256)
// Utilisé depuis le détail devis pour recueillir la signature client

function AfSignature({ t, devisId, clientName, onSave, onCancel }) {
  const canvasRef  = React.useRef(null);
  const [drawing, setDrawing]   = React.useState(false);
  const [hasDrawn, setHasDrawn] = React.useState(false);
  const [saved, setSaved]       = React.useState(false);
  const [busy, setBusy]         = React.useState(false);
  const [errMsg, setErrMsg]     = React.useState('');
  const [syncInfo, setSyncInfo] = React.useState('');
  const [locked, setLocked]     = React.useState(
    () => !!(devisId && typeof AF_STORE !== 'undefined' && AF_STORE.isDevisReadOnlyById(devisId))
  );
  const lastPos = React.useRef({ x: 0, y: 0 });

  React.useEffect(() => {
    if (!devisId || typeof AF_STORE === 'undefined') {
      setLocked(false);
      return;
    }
    const refresh = () => setLocked(AF_STORE.isDevisReadOnlyById(devisId));
    refresh();
    return AF_STORE.subscribe(refresh);
  }, [devisId]);

  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.strokeStyle = '#0B3D5C';
    ctx.lineWidth = 2.5;
    ctx.lineCap   = 'round';
    ctx.lineJoin  = 'round';
  }, []);

  const getPos = (e) => {
    const canvas = canvasRef.current;
    const rect   = canvas.getBoundingClientRect();
    const scaleX = canvas.width  / rect.width;
    const scaleY = canvas.height / rect.height;
    const src    = e.touches ? e.touches[0] : e;
    return {
      x: (src.clientX - rect.left) * scaleX,
      y: (src.clientY - rect.top)  * scaleY,
    };
  };

  const startDraw = (e) => {
    e.preventDefault();
    if (locked) return;
    const pos = getPos(e);
    const ctx = canvasRef.current.getContext('2d');
    ctx.beginPath();
    ctx.moveTo(pos.x, pos.y);
    lastPos.current = pos;
    setDrawing(true);
    setHasDrawn(true);
  };

  const draw = (e) => {
    e.preventDefault();
    if (locked || !drawing) return;
    const pos = getPos(e);
    const ctx = canvasRef.current.getContext('2d');
    ctx.lineTo(pos.x, pos.y);
    ctx.stroke();
    lastPos.current = pos;
  };

  const endDraw = (e) => {
    e.preventDefault();
    setDrawing(false);
  };

  const clear = () => {
    if (locked) return;
    const canvas = canvasRef.current;
    const ctx    = canvas.getContext('2d');
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.strokeStyle = '#0B3D5C';
    ctx.lineWidth = 2.5;
    ctx.lineCap   = 'round';
    ctx.lineJoin  = 'round';
    setHasDrawn(false);
  };

  const buildConsentText = () => {
    const who = clientName ? String(clientName).trim() : 'le client';
    return (
      'Bon pour accord — Lu et approuvé. En signant, ' + who +
      ' accepte le devis ' + String(devisId || '') +
      ' et autorise le démarrage des travaux conformément aux conditions décrites sur le devis InstantDevis.'
    );
  };

  const handleSave = async () => {
    if (!devisId || !canvasRef.current || busy) return;
    if (typeof AF_STORE !== 'undefined' && AF_STORE.isDevisReadOnlyById(devisId)) {
      setErrMsg('Ce devis est déjà signé ou payé : nouvelle signature impossible.');
      setLocked(true);
      return;
    }
    setBusy(true);
    setErrMsg('');
    setSyncInfo('');
    const raw = typeof AF_STORE !== 'undefined' && AF_STORE.getDevisById
      ? AF_STORE.getDevisById(devisId)
      : null;
    if (!raw) {
      setErrMsg('Devis introuvable.');
      setBusy(false);
      return;
    }
    const signedAt = new Date().toISOString();
    const dataUrl = canvasRef.current.toDataURL('image/png');
    const prof = typeof AF_PROFILE_STORE !== 'undefined' ? AF_PROFILE_STORE.get() : {};
    const consentText = buildConsentText();
    const signerName = clientName ? String(clientName).trim() : '';
    let signatureImageHash;
    let signedSnapshot;
    let signedDocumentHash;
    try {
      signatureImageHash = await AF_DEVIS.sha256HexOfString(dataUrl);
      signedSnapshot = AF_DEVIS.buildSignedSnapshot(raw, prof, {
        signedAt,
        signerName,
        consentText,
        signatureImageHash,
      });
      const hashPayload = AF_DEVIS.buildDocumentHashPayloadV2(devisId, {
        consentText,
        signedAt,
        signerName,
        signatureImageHash,
        snapshot: signedSnapshot,
      });
      const canonical = AF_DEVIS.canonicalStringify(hashPayload);
      signedDocumentHash = await AF_DEVIS.sha256HexOfString(canonical);
    } catch (e) {
      console.error(e);
      setErrMsg(e && e.message ? String(e.message) : 'Calcul du sceau documentaire impossible.');
      setBusy(false);
      return;
    }
    if (typeof AF_SIGN_STORE !== 'undefined') {
      AF_SIGN_STORE.save(devisId, dataUrl);
    }
    const res = await AF_STORE.applySignatureSeal(devisId, {
      signedAt,
      signerName,
      signatureDataUrl: dataUrl,
      signedSnapshot,
      signedDocumentHash,
      consentText,
    });
    if (!res || !res.ok) {
      setErrMsg('Sceau refusé : ' + (res && res.userMessage ? res.userMessage : (res && res.reason ? res.reason : 'erreur')));
      setBusy(false);
      return;
    }
    const dAfter = typeof AF_STORE.getDevisById === 'function' ? AF_STORE.getDevisById(devisId) : null;
    const p = dAfter && typeof AF_STORE.localSyncPresentation === 'function' ? AF_STORE.localSyncPresentation(dAfter) : null;
    if (p && p.state === 'error' && p.detail) {
      setSyncInfo('Signature enregistrée sur cet appareil. Synchronisation cloud : ' + p.detail);
    } else if (p && p.state === 'local_only' && p.detail) {
      setSyncInfo('Signature enregistrée. ' + p.detail);
    } else {
      setSyncInfo('');
    }
    setSaved(true);
    setBusy(false);
    setTimeout(() => onSave({ dataUrl, signedDocumentHash, signedSnapshot, signedAt, consentText }), 800);
  };

  const today = new Date().toLocaleDateString('fr-FR', { day: '2-digit', month: 'long', year: 'numeric' });

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: t.bg }}>
      <AfScreenHeader title="Signature client" subtitle={`Devis ${devisId}`} t={t} back onBack={onCancel} />

      <div style={{ flex: 1, overflowY: 'auto', padding: '14px 16px 20px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div style={{
          padding: '12px 14px', borderRadius: 10,
          background: 'rgba(11,61,92,0.06)', border: `1px solid rgba(11,61,92,0.2)`,
        }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: t.text, marginBottom: 4 }}>
            Bon pour accord — Lu et approuvé
          </div>
          <div style={{ fontSize: 11, color: t.textMuted, lineHeight: 1.6 }}>
            {buildConsentText()}
          </div>
          <div style={{ fontSize: 11, fontWeight: 700, color: t.primary, marginTop: 6 }}>
            Signé le {today}
          </div>
        </div>

        {errMsg && (
          <div style={{ padding: '10px 12px', borderRadius: 8, background: 'rgba(185,28,28,0.1)', border: '1px solid rgba(185,28,28,0.35)', fontSize: 12, fontWeight: 600, color: '#B91C1C' }}>
            {errMsg}
          </div>
        )}

        {syncInfo && (
          <div style={{ padding: '10px 12px', borderRadius: 8, background: 'rgba(234, 179, 8, 0.14)', border: '1px solid rgba(180, 83, 9, 0.4)', fontSize: 12, fontWeight: 600, color: '#92400E', lineHeight: 1.45 }}>
            {syncInfo}
          </div>
        )}

        {locked && (
          <div style={{ padding: '10px 12px', borderRadius: 8, background: 'rgba(5,150,105,0.1)', border: '1px solid rgba(5,150,105,0.35)', fontSize: 12, fontWeight: 600, color: '#047857' }}>
            Devis signé ou payé — accès en lecture seule. Aucune nouvelle signature n’est autorisée.
          </div>
        )}

        <div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
            <label style={{ fontSize: 11, fontWeight: 700, color: t.textMuted, textTransform: 'uppercase', letterSpacing: 0.6 }}>
              Signature du client
            </label>
            {hasDrawn && !locked && (
              <button onClick={clear} style={{
                fontSize: 11, fontWeight: 700, color: t.safety,
                background: 'none', border: 'none', cursor: 'pointer',
                display: 'flex', alignItems: 'center', gap: 4,
              }}>
                <lucide.RotateCcw size={12} /> Effacer
              </button>
            )}
          </div>
          <div style={{
            borderRadius: 12,
            border: `2px solid ${drawing ? t.safety : hasDrawn ? t.primary : t.border}`,
            overflow: 'hidden', position: 'relative',
            transition: 'border-color 0.2s',
            boxShadow: drawing ? `0 0 0 3px rgba(255,107,0,0.15)` : 'none',
          }}>
            <canvas
              ref={canvasRef}
              id="signature-canvas"
              width={600}
              height={200}
              onMouseDown={startDraw}
              onMouseMove={draw}
              onMouseUp={endDraw}
              onMouseLeave={endDraw}
              onTouchStart={startDraw}
              onTouchMove={draw}
              onTouchEnd={endDraw}
              style={{
                display: 'block',
                width: '100%', height: 160,
                cursor: locked ? 'not-allowed' : 'crosshair',
                touchAction: 'none',
                background: '#fff',
                pointerEvents: locked ? 'none' : 'auto',
                opacity: locked ? 0.45 : 1,
              }}
            />
            {!hasDrawn && !locked && (
              <div style={{
                position: 'absolute', inset: 0,
                display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                gap: 8, pointerEvents: 'none',
              }}>
                <lucide.PenTool size={28} color={t.border} />
                <div style={{ fontSize: 13, color: t.border, fontWeight: 600 }}>
                  Signer ici avec le doigt
                </div>
              </div>
            )}
          </div>
          <div style={{
            marginTop: 8, display: 'flex', alignItems: 'center', gap: 8,
            fontSize: 11, color: t.textMuted,
          }}>
            <div style={{ flex: 1, height: 1, background: t.border }} />
            <span>Signature</span>
            <div style={{ flex: 1, height: 1, background: t.border }} />
          </div>
        </div>

        <div style={{
          background: t.bgElevated, borderRadius: 10, border: `1px solid ${t.border}`,
          padding: '12px 14px', display: 'flex', justifyContent: 'space-between',
        }}>
          <div style={{ fontSize: 12, color: t.textMuted }}>
            <div style={{ fontWeight: 700, color: t.text }}>{clientName || 'Client'}</div>
            <div style={{ marginTop: 2 }}>Signataire</div>
          </div>
          <div style={{ textAlign: 'right', fontSize: 12, color: t.textMuted }}>
            <div style={{ fontWeight: 700, color: t.text }}>{today}</div>
            <div style={{ marginTop: 2 }}>Date de signature</div>
          </div>
        </div>

        <div style={{ fontSize: 10, color: t.textMuted, lineHeight: 1.5 }}>
          Un instantané du devis (lignes, montants, consentement, signataire, identité artisan) et une empreinte SHA-256 de la charge utile canonique, ainsi qu’une empreinte de l’image de signature, seront enregistrés sur le devis pour preuve d’intégrité.
        </div>
      </div>

      <div style={{
        padding: '12px 16px', background: t.bg, borderTop: `1px solid ${t.border}`,
        display: 'flex', gap: 8,
      }}>
        <button onClick={onCancel} style={{
          width: 52, height: 56, borderRadius: 10, background: t.bgElevated,
          border: `1.5px solid ${t.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
        }}>
          <lucide.X size={20} color={t.textMuted} />
        </button>
        <button
          id="btn-validate-signature"
          onClick={handleSave}
          disabled={!hasDrawn || saved || busy || locked}
          style={{
            flex: 1, height: 56, borderRadius: 10, border: 'none', cursor: (hasDrawn && !busy && !locked) ? 'pointer' : 'not-allowed',
            background: saved ? '#10B981' : (hasDrawn && !busy && !locked) ? t.safety : t.bgSunken,
            fontSize: 15, fontWeight: 800,
            color: saved ? '#fff' : (hasDrawn && !busy && !locked) ? '#0D1520' : t.textMuted,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            boxShadow: hasDrawn && !saved && !busy && !locked ? '0 4px 16px rgba(255,107,0,0.4)' : 'none',
            transition: 'all 0.2s',
          }}
        >
          {saved
            ? <><lucide.CheckCircle2 size={20} /> Signature enregistrée !</>
            : (locked
              ? <><lucide.Lock size={20} /> Verrouillé</>
              : (busy
                ? <><lucide.Loader size={20} style={{ animation: 'af-pulse 0.8s infinite' }} /> Sceau en cours…</>
                : <><lucide.Check size={20} /> Valider la signature</>))}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { AfSignature });
