// Clients_Fiche.jsx — Modal "fiche détaillée" d'un client : stage, prochaine
// action (rappel daté), PDF Loi 25, notes. Extrait de BrokerTab_Clients.jsx.
//
// Conventions : NO import/export, React global, unique hook aliases (suffix Fi).

// ── Loi25PdfButton — bouton de generation PDF Loi 25 brande (PR 4.3 Vague 4) ──
//
// Appelle POST /api/v1/broker/clients/{id}/loi25_pdf via window.vestora.brokerApi.
// Propose ensuite un telechargement direct + lien mailto pour envoi par email.
function Loi25PdfButton({ clientId, clientName, showToast }) {
  const { useState: useL } = React;
  const [generating, setGenerating] = useL(false);
  const [pdfResult, setPdfResult] = useL(null);
  const [error, setError] = useL('');

  async function handleGenerate() {
    const api = window.vestora && window.vestora.brokerApi;
    if (!api || typeof api.generateLoi25Pdf !== 'function') {
      setError('Module API indisponible (generateLoi25Pdf).');
      return;
    }
    setGenerating(true);
    setError('');
    setPdfResult(null);
    try {
      const r = await api.generateLoi25Pdf(clientId);
      if (!r.ok) {
        setError((r.error && r.error.message) || 'Erreur lors de la generation.');
        if (showToast) showToast('Echec generation PDF Loi 25', 'error');
      } else {
        setPdfResult(r.data);
        if (showToast) showToast('PDF Loi 25 genere !', 'success');
      }
    } catch (e) {
      setError('Erreur inattendue: ' + (e && e.message ? e.message : String(e)));
    } finally {
      setGenerating(false);
    }
  }

  function handleEmailClient() {
    if (!pdfResult) return;
    const subject = encodeURIComponent('Formulaire de consentement Loi 25 — Vestora');
    const body = encodeURIComponent(
      'Bonjour,\n\nVeuillez trouver ci-joint votre formulaire de consentement Loi 25 pour nos services immobiliers.\n\n'
      + (pdfResult.pdf_url ? 'Lien de telechargement (valide 30 jours) : ' + pdfResult.pdf_url + '\n\n' : '')
      + 'Merci de le signer et de nous le retourner.\n\nCordialement,'
    );
    window.open('mailto:?subject=' + subject + '&body=' + body);
  }

  return (
    <div style={{ borderTop: '1px solid #e5e7eb', paddingTop: 14, marginBottom: 14 }}>
      <h4 style={{ margin: '0 0 10px', fontSize: 14, fontWeight: 700, color: '#111827' }}>
        Document Loi 25
      </h4>

      {!pdfResult ? (
        <>
          <p style={{ margin: '0 0 10px', fontSize: 12, color: '#64748b' }}>
            Generez un PDF de consentement Loi 25 brande avec vos coordonnees courtier
            et les informations du client <strong>{clientName}</strong>.
          </p>
          {error && (
            <div style={{ color: '#dc2626', fontSize: 12, marginBottom: 8 }}>{error}</div>
          )}
          <button
            onClick={handleGenerate}
            disabled={generating}
            style={{
              padding: '7px 14px', borderRadius: 8, fontSize: 12, fontWeight: 600,
              background: generating ? '#e2e8f0' : '#0f172a',
              color: generating ? '#64748b' : '#fff',
              border: 'none', cursor: generating ? 'wait' : 'pointer',
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}
          >
            <span dangerouslySetInnerHTML={{ __html: window.vestoraIcons.document({ size: 16 }) }} aria-hidden="true"></span>
            {generating ? 'Generation en cours…' : 'Generer PDF Loi 25 brande'}
          </button>
        </>
      ) : (
        <div style={{ background: '#f0fdf4', border: '1px solid #86efac', borderRadius: 8, padding: '10px 12px' }}>
          <div style={{ fontSize: 13, color: '#166534', fontWeight: 600, marginBottom: 8 }}>
            PDF Loi 25 genere le {pdfResult.generated_on || ''}
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {pdfResult.pdf_url && (
              <a
                href={pdfResult.pdf_url}
                target="_blank"
                rel="noopener noreferrer"
                style={{
                  padding: '6px 12px', borderRadius: 7, fontSize: 12, fontWeight: 600,
                  background: '#166534', color: '#fff', textDecoration: 'none',
                  display: 'inline-flex', alignItems: 'center', gap: 5,
                }}
              >
                <span dangerouslySetInnerHTML={{ __html: window.vestoraIcons.download({ size: 14 }) }} aria-hidden="true"></span> Telecharger le PDF
              </a>
            )}
            <button
              onClick={handleEmailClient}
              style={{
                padding: '6px 12px', borderRadius: 7, fontSize: 12,
                background: 'transparent', border: '1px solid #86efac',
                color: '#166534', cursor: 'pointer',
                display: 'inline-flex', alignItems: 'center', gap: 5,
              }}
            >
              <span dangerouslySetInnerHTML={{ __html: window.vestoraIcons.envelope({ size: 14 }) }} aria-hidden="true"></span> Envoyer par email
            </button>
            <button
              onClick={() => { setPdfResult(null); setError(''); }}
              style={{
                padding: '6px 12px', borderRadius: 7, fontSize: 12,
                background: 'transparent', border: '1px solid #d1d5db',
                color: '#64748b', cursor: 'pointer',
              }}
            >
              Regenerer
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function ClientsFiche({
  detailClient,
  setDetailClient,
  detailNotes,
  detailLoading,
  newNoteBody,
  setNewNoteBody,
  savingNote,
  onClose,
  onChangeStage,
  onAddNote,
  onRemoveNote,
  onSaveNextAction,
  showToast,
}) {
  const u = window.vestoraBrokerClients || {};
  const STAGE_COLS = u.STAGE_COLS || [];
  const getStageMeta = u.getStageMeta || (() => STAGE_COLS[0]);
  const clientSummary = u.clientSummary || (() => '');
  const formatRelativeDate = u.formatRelativeDate || (() => '');
  const nextActionStatus = u.nextActionStatus || (() => null);
  const btnPrimary = (u.styles && u.styles.btnPrimary) || {};

  if (!detailClient) return null;
  const stageMeta = getStageMeta(detailClient.stage);

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0,
        background: 'rgba(0,0,0,0.45)',
        zIndex: 1000,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 20,
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: '#fff',
          borderRadius: 12,
          maxWidth: 560,
          width: '100%',
          maxHeight: '85vh',
          overflowY: 'auto',
          padding: '20px 22px',
          boxShadow: '0 10px 40px rgba(0,0,0,0.25)',
        }}
      >
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 14 }}>
          <div>
            <h3 style={{ margin: 0, fontSize: 17, fontWeight: 700, color: '#111827' }}>
              {detailClient.name}
            </h3>
            <div style={{ fontSize: 12, color: '#6b7280', marginTop: 4 }}>
              {clientSummary(detailClient)}
            </div>
          </div>
          <button
            onClick={onClose}
            style={{ background: 'none', border: 'none', fontSize: 22, color: '#9ca3af', cursor: 'pointer', lineHeight: 1 }}
            aria-label="Fermer"
          >×</button>
        </div>

        <div style={{ marginBottom: 16, display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 13, color: '#374151' }}>Stage :</span>
          <span style={{
            background: stageMeta.bg, color: stageMeta.color,
            padding: '3px 10px', borderRadius: 12, fontSize: 12, fontWeight: 600,
            border: '1px solid ' + stageMeta.color + '40',
          }}>{stageMeta.label}</span>
          <select
            value={detailClient.stage || 'prospect'}
            onChange={(e) => {
              onChangeStage(detailClient.id, e.target.value);
              setDetailClient({ ...detailClient, stage: e.target.value });
            }}
            style={{
              fontSize: 12, padding: '3px 6px', borderRadius: 6,
              border: '1px solid #d1d5db', background: '#fff', cursor: 'pointer',
            }}
          >
            {STAGE_COLS.map((s) => (
              <option key={s.key} value={s.key}>{s.label}</option>
            ))}
          </select>
        </div>

        {/* Vague 4 PR 4.2 — Prochaine action (rappel datee) */}
        <div style={{ borderTop: '1px solid #e5e7eb', paddingTop: 14, marginBottom: 14 }}>
          <h4 style={{ margin: '0 0 10px', fontSize: 14, fontWeight: 700, color: '#111827' }}>
            Prochaine action
          </h4>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center', marginBottom: 8 }}>
            <input
              type="datetime-local"
              value={detailClient.nextActionAt
                ? new Date(detailClient.nextActionAt).toISOString().slice(0, 16)
                : ''}
              onChange={(e) => {
                const ts = e.target.value ? new Date(e.target.value).getTime() : null;
                setDetailClient({ ...detailClient, nextActionAt: ts });
              }}
              style={{
                fontSize: 13, padding: '6px 8px', borderRadius: 6,
                border: '1px solid #d1d5db', flex: '1 1 180px',
              }}
            />
            <input
              type="text"
              placeholder="Note (ex: appel, visite)"
              value={detailClient.nextActionNote || ''}
              onChange={(e) => setDetailClient({ ...detailClient, nextActionNote: e.target.value })}
              style={{
                fontSize: 13, padding: '6px 8px', borderRadius: 6,
                border: '1px solid #d1d5db', flex: '2 1 200px',
              }}
            />
          </div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 8 }}>
            {[
              { label: '+1j', days: 1 },
              { label: '+7j', days: 7 },
              { label: '+30j', days: 30 },
            ].map((preset) => (
              <button
                key={preset.label}
                type="button"
                onClick={() => {
                  const ts = Date.now() + preset.days * 24 * 3600 * 1000;
                  setDetailClient({ ...detailClient, nextActionAt: ts });
                }}
                style={{
                  fontSize: 11, padding: '4px 10px', borderRadius: 12,
                  border: '1px solid #d1d5db', background: '#f9fafb',
                  color: '#374151', cursor: 'pointer',
                }}
              >{preset.label}</button>
            ))}
            <button
              type="button"
              onClick={() => setDetailClient({ ...detailClient, nextActionAt: null, nextActionNote: '' })}
              style={{
                fontSize: 11, padding: '4px 10px', borderRadius: 12,
                border: '1px solid #fecaca', background: '#fff5f5',
                color: '#b91c1c', cursor: 'pointer',
              }}
            >Effacer</button>
            <button
              type="button"
              onClick={() => onSaveNextAction(
                detailClient, detailClient.nextActionAt, detailClient.nextActionNote,
              )}
              style={{ ...btnPrimary, padding: '4px 12px', fontSize: 12 }}
            >Enregistrer</button>
          </div>
          {(() => {
            const st = nextActionStatus(detailClient);
            if (!st) return null;
            return (
              <span style={{
                display: 'inline-block', padding: '2px 8px', borderRadius: 10,
                fontSize: 11, fontWeight: 600,
                background: st.bg, color: st.color,
              }}>{st.label}</span>
            );
          })()}
        </div>

        {/* ── PDF Loi 25 brande (PR 4.3 Vague 4) ── */}
        <Loi25PdfButton clientId={detailClient.id} clientName={detailClient.name} showToast={showToast} />

        <div style={{ borderTop: '1px solid #e5e7eb', paddingTop: 14 }}>
          <h4 style={{ margin: '0 0 10px', fontSize: 14, fontWeight: 700, color: '#111827' }}>
            Notes ({detailNotes.length})
          </h4>

          <div style={{ display: 'flex', gap: 8, marginBottom: 14 }}>
            <textarea
              value={newNoteBody}
              onChange={(e) => setNewNoteBody(e.target.value)}
              placeholder="Ajouter une note…"
              rows={2}
              style={{
                flex: 1, padding: '8px 10px', borderRadius: 8,
                border: '1.5px solid #d1d5db', fontSize: 13,
                fontFamily: 'inherit', resize: 'vertical',
              }}
            />
            <button
              onClick={onAddNote}
              disabled={savingNote || !newNoteBody.trim()}
              style={{
                ...btnPrimary,
                padding: '6px 14px', fontSize: 12,
                opacity: savingNote || !newNoteBody.trim() ? 0.5 : 1,
                cursor: savingNote || !newNoteBody.trim() ? 'not-allowed' : 'pointer',
              }}
            >Ajouter</button>
          </div>

          {detailLoading ? (
            <div style={{ color: '#9ca3af', fontSize: 13, textAlign: 'center', padding: 20 }}>
              Chargement…
            </div>
          ) : detailNotes.length === 0 ? (
            <div style={{ color: '#9ca3af', fontSize: 13, textAlign: 'center', padding: 20 }}>
              Aucune note pour le moment.
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {detailNotes.map((n) => (
                <div key={n.id} style={{
                  background: '#f9fafb', border: '1px solid #e5e7eb',
                  borderRadius: 8, padding: '10px 12px',
                }}>
                  <div style={{ fontSize: 13, color: '#111827', whiteSpace: 'pre-wrap', marginBottom: 4 }}>
                    {n.body}
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <span style={{ fontSize: 11, color: '#9ca3af' }}>
                      {formatRelativeDate(n.createdAt) || ''}
                    </span>
                    <button
                      onClick={() => onRemoveNote(n.id)}
                      style={{ background: 'none', border: 'none', color: '#ef4444', fontSize: 11, cursor: 'pointer' }}
                    >Supprimer</button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

if (typeof window !== 'undefined') {
  window.ClientsFiche = ClientsFiche;
  window.Loi25PdfButton = Loi25PdfButton;
}
