// InstantDevis — Composant bouton "Envoyer le devis" (Worker optionnel + PDF + mailto)
// Utilisable partout dans l'app via <AfSendButton devis={...} artisanName="..." t={t} />

function AfSendButton({ devis, artisanName, t, size = 'lg', full = true }) {
  const [state, setState] = React.useState('idle'); // idle | input | sending | success | fallback | error
  const [toEmail, setToEmail] = React.useState('');
  const [result, setResult] = React.useState(null);
  const [showModal, setShowModal] = React.useState(false);

  const jspdfReady = typeof window.jspdf !== 'undefined';

  const integ = (typeof AF_INTEGRATION !== 'undefined' && AF_INTEGRATION) ? AF_INTEGRATION : null;
  const pMail = typeof AF_PROFILE_STORE !== 'undefined' ? AF_PROFILE_STORE.get() : {};
  const hasWorkerForMail = !!(integ && (String(integ.workersBase || '').trim() || String(integ.mailWorkerBase || '').trim()))
    || !!(pMail && String(pMail.workersBaseUrl || '').trim());

  const docOut = (typeof AF_DEVIS !== 'undefined' && AF_DEVIS.documentOutput) ? AF_DEVIS.documentOutput(devis) : null;
  const recapTTC = docOut ? docOut.totalTTC : (Number(devis.totalTTC != null ? devis.totalTTC : devis.amount) || 0);
  const _sendAcomptePct = typeof AF_PROFILE_STORE !== 'undefined' ? (AF_PROFILE_STORE.get().acomptePercent ?? 30) : 30;
  const recapAc = docOut ? docOut.acompte : (devis.acompte != null ? Number(devis.acompte) : Math.round(recapTTC * (_sendAcomptePct / 100) * 100) / 100);

  const handleOpenModal = () => {
    setShowModal(true);
    setState('input');
  };

  const handleDownloadOnly = () => {
    if (!jspdfReady) return;
    try {
      AF_PDF.download(devis, artisanName);
    } catch (e) {
      console.error('[InstantDevis] PDF download:', e);
    }
  };

  const handleSend = async () => {
    const emailTrimmed = toEmail.trim();
    if (!emailTrimmed || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailTrimmed)) {
      setToEmail(emailTrimmed);
      const inp = document.querySelector('input[type="email"]');
      if (inp) { inp.style.borderColor = '#B91C1C'; inp.focus(); }
      return;
    }
    setState('sending');
    try {
      const res = await AF_MAILER.send(devis, emailTrimmed, artisanName);
      setResult(res);
      if (res.success) {
        setState(res.method === 'worker' ? 'success' : 'fallback');
      } else if (res.method === 'error') {
        setState('error');
      } else {
        setState('fallback');
      }
    } catch (e) {
      setResult({ message: e.message });
      setState('error');
    }
  };

  const handleClose = () => {
    setShowModal(false);
    setState('idle');
    setResult(null);
    setToEmail('');
  };

  const btnBg = size === 'xl'
    ? `linear-gradient(135deg, ${t.safety} 0%, #ff8c00 100%)`
    : t.safety;

  return (
    <>
      {/* ── Bouton principal ── */}
      <div style={{ display: 'flex', gap: 8, width: full ? '100%' : 'auto' }}>
        <button
          id="btn-envoyer-devis"
          onClick={handleOpenModal}
          style={{
            flex: 1,
            height: size === 'xl' ? 68 : size === 'lg' ? 58 : 48,
            borderRadius: size === 'xl' ? 14 : 10,
            background: btnBg,
            border: 'none', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
            fontSize: size === 'xl' ? 17 : 15, fontWeight: 800, color: '#0D1520',
            boxShadow: '0 6px 20px rgba(255,107,0,0.4)',
            transition: 'transform 0.1s, box-shadow 0.1s',
            position: 'relative', overflow: 'hidden',
          }}
          onMouseDown={e => { e.currentTarget.style.transform = 'scale(0.97)'; }}
          onMouseUp={e => { e.currentTarget.style.transform = 'scale(1)'; }}
          onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)'; }}
        >
          {size === 'xl' && (
            <div style={{
              position: 'absolute', inset: 0, opacity: 0.07,
              backgroundImage: 'repeating-linear-gradient(-45deg, #fff 0, #fff 2px, transparent 2px, transparent 10px)',
            }}/>
          )}
          <lucide.Share2 size={size === 'xl' ? 24 : 20} strokeWidth={2.5} />
          Envoyer le devis
        </button>

        {/* Bouton PDF uniquement */}
        {jspdfReady && (
          <button
            onClick={handleDownloadOnly}
            title="Télécharger le PDF"
            style={{
              width: size === 'xl' ? 68 : 58, height: size === 'xl' ? 68 : 58,
              borderRadius: size === 'xl' ? 14 : 10,
              background: t.bgElevated, border: `1.5px solid ${t.border}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              cursor: 'pointer', flexShrink: 0,
              transition: 'transform 0.1s',
            }}
            onMouseDown={e => { e.currentTarget.style.transform = 'scale(0.97)'; }}
            onMouseUp={e => { e.currentTarget.style.transform = 'scale(1)'; }}
            onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)'; }}
          >
            <lucide.Download size={20} color={t.primary} />
          </button>
        )}
      </div>

      {/* ── Modal d'envoi ── */}
      {showModal && (
        <div style={{
          position: 'fixed', inset: 0, zIndex: 500,
          background: 'rgba(0,0,0,0.55)',
          display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
          backdropFilter: 'blur(4px)',
          animation: 'af-slide-up 0.2s both',
        }} onClick={e => { if (e.target === e.currentTarget) handleClose(); }}>
          <div style={{
            width: '100%', maxWidth: 440,
            background: t.bgElevated,
            borderRadius: '20px 20px 0 0',
            border: `1px solid ${t.borderStrong}`,
            boxShadow: '0 -20px 60px rgba(0,0,0,0.3)',
            overflow: 'hidden',
          }}>
            {/* Handle */}
            <div style={{ display: 'flex', justifyContent: 'center', padding: '12px 0 6px' }}>
              <div style={{ width: 40, height: 4, borderRadius: 2, background: t.border }} />
            </div>

            {/* Header modal */}
            <div style={{
              padding: '4px 20px 14px',
              borderBottom: `1px solid ${t.border}`,
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            }}>
              <div>
                <div style={{ fontSize: 16, fontWeight: 800, color: t.text }}>
                  Envoyer le devis
                </div>
                <div style={{ fontSize: 12, color: t.textMuted, marginTop: 2 }}>
                  {devis.id} — {devis.title}
                </div>
              </div>
              <button onClick={handleClose} style={{
                width: 36, height: 36, borderRadius: 8,
                background: t.bgSunken, border: `1px solid ${t.border}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
              }}>
                <lucide.X size={16} color={t.textMuted} />
              </button>
            </div>

            <div style={{ padding: '16px 20px 24px' }}>

              {/* ── ÉTAT : Saisie email ── */}
              {state === 'input' && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                  {/* Récap devis */}
                  <div style={{
                    background: t.bg, borderRadius: 10, border: `1px solid ${t.border}`,
                    padding: '12px 14px', display: 'flex', justifyContent: 'space-between',
                  }}>
                    <div>
                      <div style={{ fontSize: 13, fontWeight: 700, color: t.text }}>{devis.clientName}</div>
                      <div style={{ fontSize: 11, color: t.textMuted, marginTop: 2 }}>{devis.title}</div>
                    </div>
                    <div style={{ textAlign: 'right' }}>
                      <div className="af-mono" style={{ fontSize: 16, fontWeight: 800, color: t.text }}>
                        {recapTTC.toFixed(2)} €
                      </div>
                      <div style={{ fontSize: 10, color: t.safety, fontWeight: 700 }}>
                        Acompte: {recapAc.toFixed(2)} €
                      </div>
                    </div>
                  </div>

                  {/* Email client */}
                  <div>
                    <label style={{ fontSize: 11, fontWeight: 700, color: t.textMuted, textTransform: 'uppercase', letterSpacing: 0.6, display: 'block', marginBottom: 6 }}>
                      Email du client
                    </label>
                    <input
                      type="email"
                      value={toEmail}
                      onChange={e => setToEmail(e.target.value)}
                      placeholder="client@email.com"
                      style={{
                        width: '100%', padding: '12px 14px', borderRadius: 8,
                        background: t.bg, border: `1.5px solid ${t.border}`,
                        fontSize: 15, fontWeight: 500, color: t.text, outline: 'none',
                      }}
                      onFocus={e => e.target.style.borderColor = t.safety}
                      onBlur={e => e.target.style.borderColor = t.border}
                      onKeyDown={e => e.key === 'Enter' && handleSend()}
                    />
                  </div>

                  {/* Info mode d'envoi */}
                  <div style={{
                    display: 'flex', gap: 8, alignItems: 'flex-start',
                    padding: '10px 12px', borderRadius: 8,
                    background: hasWorkerForMail
                      ? 'rgba(16,185,129,0.08)'
                      : 'rgba(255,107,0,0.08)',
                    border: `1px solid ${hasWorkerForMail ? 'rgba(16,185,129,0.3)' : 'rgba(255,107,0,0.3)'}`,
                  }}>
                    {hasWorkerForMail
                      ? <lucide.CheckCircle2 size={14} color="#10B981" style={{ flexShrink: 0, marginTop: 1 }} />
                      : <lucide.AlertTriangle size={14} color={t.safety} style={{ flexShrink: 0, marginTop: 1 }} />
                    }
                    <div style={{ fontSize: 11, color: t.textMuted, lineHeight: 1.5 }}>
                      {hasWorkerForMail
                        ? <><strong style={{ color: '#10B981' }}>Worker mail configuré</strong> (tokens : <code>workersBase</code> ou <code>mailWorkerBase</code>) — envoi côté serveur.</>
                        : <><strong style={{ color: t.safety }}>Aucun Worker mail</strong> — le PDF est téléchargé et votre client mail s’ouvre (pièce jointe manuelle).</>
                      }
                    </div>
                  </div>

                  {/* Bouton envoyer */}
                  <button
                    onClick={handleSend}
                    style={{
                      width: '100%', height: 56, borderRadius: 12,
                      background: `linear-gradient(135deg, ${t.safety} 0%, #ff8c00 100%)`,
                      border: 'none', cursor: 'pointer',
                      fontSize: 16, fontWeight: 800, color: '#0D1520',
                      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                      boxShadow: '0 4px 16px rgba(255,107,0,0.4)',
                    }}
                  >
                    <lucide.Share2 size={20} />
                    Envoyer le devis
                  </button>

                  {/* Téléchargement seul */}
                  {jspdfReady && (
                    <button onClick={handleDownloadOnly} style={{
                      width: '100%', height: 44, borderRadius: 10,
                      background: 'none', border: `1.5px solid ${t.border}`,
                      cursor: 'pointer', fontSize: 13, fontWeight: 600, color: t.textMuted,
                      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                    }}>
                      <lucide.Download size={15} />
                      Télécharger le PDF uniquement
                    </button>
                  )}
                </div>
              )}

              {/* ── ÉTAT : Envoi en cours ── */}
              {state === 'sending' && (
                <div style={{
                  display: 'flex', flexDirection: 'column', alignItems: 'center',
                  gap: 14, padding: '20px 0',
                }}>
                  <div style={{
                    width: 60, height: 60, borderRadius: '50%',
                    background: 'rgba(255,107,0,0.1)',
                    border: `2px solid rgba(255,107,0,0.4)`,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    <lucide.Share2 size={26} color={t.safety} style={{ animation: 'af-pulse 0.8s infinite' }} />
                  </div>
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ fontSize: 15, fontWeight: 800, color: t.text }}>Envoi en cours…</div>
                    <div style={{ fontSize: 12, color: t.textMuted, marginTop: 4 }}>
                      Génération PDF + envoi
                    </div>
                  </div>
                </div>
              )}

              {state === 'success' && (
                <div style={{
                  display: 'flex', flexDirection: 'column', alignItems: 'center',
                  gap: 14, padding: '10px 0',
                }}>
                  <div style={{
                    width: 64, height: 64, borderRadius: '50%',
                    background: 'rgba(16,185,129,0.12)',
                    border: `2px solid rgba(16,185,129,0.5)`,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    <lucide.CheckCircle2 size={32} color="#10B981" />
                  </div>
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ fontSize: 17, fontWeight: 800, color: '#10B981' }}>
                      Devis envoyé
                    </div>
                    <div style={{ fontSize: 12, color: t.textMuted, marginTop: 6, lineHeight: 1.5 }}>
                      {result?.message}
                    </div>
                  </div>
                  <button onClick={handleClose} style={{
                    width: '100%', height: 50, borderRadius: 10,
                    background: '#10B981', border: 'none', cursor: 'pointer',
                    fontSize: 14, fontWeight: 800, color: '#fff',
                  }}>
                    Parfait !
                  </button>
                </div>
              )}

              {/* ── ÉTAT : Fallback (PDF téléchargé + mailto ouvert) ── */}
              {state === 'fallback' && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  <div style={{
                    padding: '14px', borderRadius: 10,
                    background: 'rgba(255,107,0,0.08)',
                    border: `1.5px solid rgba(255,107,0,0.35)`,
                  }}>
                    <div style={{ fontSize: 14, fontWeight: 800, color: t.safety, marginBottom: 6 }}>
                      📥 PDF téléchargé · ✉️ Mail ouvert
                    </div>
                    <div style={{ fontSize: 12, color: t.textMuted, lineHeight: 1.6 }}>
                      {result?.message}
                    </div>
                    {result?.workerHint && (
                      <div style={{
                        marginTop: 10, padding: '10px 12px', borderRadius: 8,
                        background: 'rgba(234, 179, 8, 0.1)', border: '1px solid rgba(234, 179, 8, 0.35)',
                        fontSize: 11, color: t.text, lineHeight: 1.5,
                      }}>
                        <strong>Envoi automatique (Worker) :</strong> {result.workerHint}
                      </div>
                    )}
                  </div>
                  <div style={{ fontSize: 11, color: t.textMuted, lineHeight: 1.6, padding: '0 2px' }}>
                    <strong>Prochaines étapes :</strong><br/>
                    1. Joignez le PDF téléchargé à l'email<br/>
                    2. Vérifiez le corps du message pré-rempli<br/>
                    3. Cliquez Envoyer dans votre application mail
                  </div>
                  <div style={{
                    padding: '10px 12px', borderRadius: 8,
                    background: 'rgba(59,130,246,0.08)',
                    border: '1px solid rgba(59,130,246,0.25)',
                    fontSize: 11, color: '#3B82F6', lineHeight: 1.5,
                  }}>
                    💡 <strong>Envoi automatique</strong> : déployez le Worker (<code>cloudflare/</code>) et définissez <code>AF_INTEGRATION.workersBase</code> ou <code>mailWorkerBase</code> dans <code>tokens.jsx</code>.
                  </div>
                  <button onClick={handleClose} style={{
                    width: '100%', height: 48, borderRadius: 10,
                    background: t.bgSunken, border: `1.5px solid ${t.border}`,
                    cursor: 'pointer', fontSize: 14, fontWeight: 700, color: t.text,
                  }}>
                    Fermer
                  </button>
                </div>
              )}

              {/* ── ÉTAT : Erreur ── */}
              {state === 'error' && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  <div style={{ textAlign: 'center', padding: '10px 0' }}>
                    <div style={{ fontSize: 15, fontWeight: 800, color: t.danger }}>
                      Erreur inattendue
                    </div>
                    <div style={{ fontSize: 12, color: t.textMuted, marginTop: 6 }}>
                      {result?.message}
                    </div>
                  </div>
                  <button onClick={() => setState('input')} style={{
                    width: '100%', height: 48, borderRadius: 10,
                    background: t.safety, border: 'none',
                    cursor: 'pointer', fontSize: 14, fontWeight: 700, color: '#0D1520',
                  }}>
                    Réessayer
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </>
  );
}

Object.assign(window, { AfSendButton });
