// Testing Ads — modales & overlays

const { Avatar, StatusPill, Btn, Thumb, PromoCode, Card } = window.WF;

// ——— Modale générique avec scrim + sheet centrée ———
function Modal({ open, onClose, children, width = 520, padding = 24 }) {
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => e.key === 'Escape' && onClose?.();
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 2000,
        background: 'rgba(17,20,30,0.42)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 16,
        animation: 'overlayIn 160ms ease-out forwards',
      }}
    >
      <div onClick={(e) => e.stopPropagation()} style={{
        background: 'var(--paper)', borderRadius: 14,
        boxShadow: '0 20px 60px rgba(0,0,0,0.20)',
        width: '100%', maxWidth: width, maxHeight: '90vh', overflow: 'auto',
        padding,
        animation: 'sheetIn 200ms cubic-bezier(.2,.8,.2,1) forwards',
      }}>{children}</div>
    </div>
  );
}

// ——— Modale Kill — confirme + raison + commentaire ———
function KillModal({ open, video, onClose, onConfirm }) {
  const [reason, setReason] = React.useState(null);
  const [comment, setComment] = React.useState('');
  React.useEffect(() => { if (open) { setReason(null); setComment(''); } }, [open]);
  if (!open || !video) return null;
  const inf = window.TA_INFLUENCERS[video.inf];
  const k = video.kpi || {};

  return (
    <Modal open={open} onClose={onClose} width={540}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
        <div style={{
          width: 36, height: 36, borderRadius: 8,
          background: 'var(--st-red-bg)', color: 'var(--st-red-tx)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18,
        }}>❌</div>
        <div style={{ flex: 1 }}>
          <h2 style={{ margin: 0, font: '700 18px var(--font-sans)', letterSpacing: -0.3 }}>Killer cette ad ?</h2>
          <div style={{ font: '500 12.5px var(--font-sans)', color: 'var(--ink-3)' }}>La campagne Meta sera arrêtée immédiatement.</div>
        </div>
      </div>

      {/* Récap ad */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: 12, marginTop: 14, marginBottom: 16,
        background: 'var(--paper-2)', borderRadius: 10,
      }}>
        <Avatar name={inf.name} size={32} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ font: '600 13.5px var(--font-sans)' }}>{inf.handle}</div>
          <div style={{ font: '500 11px var(--font-mono)', color: 'var(--ink-3)' }}>camp #{video.metaCampaign} · J{video.daysLive}</div>
        </div>
        <div style={{ display: 'flex', gap: 12, font: '500 11.5px var(--font-mono)', color: 'var(--ink-3)' }}>
          <span>CTR <b style={{ color: 'var(--ink)' }}>{k.ctr}</b></span>
          <span>CPA <b style={{ color: 'var(--ink)' }}>{k.cpa}</b></span>
          <span>Spend <b style={{ color: 'var(--ink)' }}>{k.spend}</b></span>
        </div>
      </div>

      {/* Raisons */}
      <div style={{ font: '600 12px var(--font-sans)', color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 1, marginBottom: 8 }}>
        Pourquoi ? <span style={{ color: '#b91c1c' }}>*</span>
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 14 }}>
        {window.TA_KILL_REASONS.map(r => {
          const a = reason === r.id;
          return (
            <button key={r.id} onClick={() => setReason(r.id)} style={{
              padding: '6px 12px', borderRadius: 999,
              background: a ? '#111' : 'var(--paper)',
              color: a ? '#fff' : 'var(--ink)',
              border: a ? '1px solid #111' : '1px solid var(--border-2)',
              font: '600 12px var(--font-sans)', cursor: 'pointer',
            }}>{r.label}</button>
          );
        })}
      </div>

      {/* Commentaire */}
      <div style={{ font: '600 12px var(--font-sans)', color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 1, marginBottom: 6 }}>
        Note (optionnel)
      </div>
      <textarea
        value={comment}
        onChange={(e) => setComment(e.target.value)}
        placeholder="Détail à retenir pour les prochaines ads…"
        style={{
          width: '100%', minHeight: 64, padding: 10,
          border: '1px solid var(--border-2)', borderRadius: 8,
          font: '500 13px var(--font-sans)', resize: 'vertical',
          boxSizing: 'border-box', outline: 'none', background: 'var(--paper)',
        }}
      />

      {/* Actions */}
      <div style={{ display: 'flex', gap: 8, marginTop: 18, justifyContent: 'flex-end' }}>
        <Btn variant="ghost" onClick={onClose}>Annuler</Btn>
        <Btn
          variant="danger"
          style={{ background: '#b91c1c', color: '#fff', borderColor: '#b91c1c', opacity: reason ? 1 : 0.4, pointerEvents: reason ? 'auto' : 'none' }}
          onClick={() => onConfirm?.({ reason, comment })}
        >❌ Killer définitivement</Btn>
      </div>
    </Modal>
  );
}

// ——— Modale Push Meta — flow rapide ———
function PushMetaModal({ open, video, mode = 'push', onClose, onConfirm }) {
  // mode = 'push' (montée → testing) ou 'scale' (testing → scaled, with bigger budget)
  const [audId, setAudId] = React.useState(null);
  const [budget, setBudget] = React.useState(mode === 'scale' ? 100 : 20);
  const [step, setStep] = React.useState(1);
  const [pushed, setPushed] = React.useState(false);

  React.useEffect(() => {
    if (open) {
      setStep(1); setPushed(false);
      setAudId(window.TA_META_AUDIENCES.find(a => a.isDefault).id);
      setBudget(mode === 'scale' ? 100 : 20);
    }
  }, [open, mode]);

  if (!open || !video) return null;
  const inf = window.TA_INFLUENCERS[video.inf];
  const aud = window.TA_META_AUDIENCES.find(a => a.id === audId);
  const title = mode === 'scale' ? 'Scaler la campagne' : 'Pousser en testing ads';

  return (
    <Modal open={open} onClose={onClose} width={620} padding={0}>
      {/* Header */}
      <div style={{
        padding: '18px 24px', borderBottom: '1px solid var(--border)',
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <div style={{
          width: 36, height: 36, borderRadius: 8,
          background: mode === 'scale' ? 'var(--st-grn-bg)' : 'var(--primary-soft)',
          color: mode === 'scale' ? 'var(--st-grn-tx)' : 'var(--primary)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18,
        }}>{mode === 'scale' ? '🚀' : '📡'}</div>
        <div style={{ flex: 1 }}>
          <h2 style={{ margin: 0, font: '700 18px var(--font-sans)', letterSpacing: -0.3 }}>{title}</h2>
          <div style={{ font: '500 12.5px var(--font-sans)', color: 'var(--ink-3)' }}>
            {mode === 'scale'
              ? 'Augmente le budget quotidien et conserve l\'audience gagnante.'
              : 'Configure la campagne Meta avant de lancer.'}
          </div>
        </div>
        <button onClick={onClose} style={{ background: 'transparent', border: 0, color: 'var(--ink-3)', cursor: 'pointer', font: '500 18px var(--font-sans)' }}>✕</button>
      </div>

      {pushed ? (
        // — État succès —
        <div style={{ padding: 32, textAlign: 'center' }}>
          <div style={{
            width: 64, height: 64, margin: '0 auto 14px', borderRadius: '50%',
            background: 'var(--st-grn-bg)', color: 'var(--st-grn-tx)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 30,
          }}>✓</div>
          <h3 style={{ margin: 0, font: '700 18px var(--font-sans)' }}>
            {mode === 'scale' ? 'Budget augmenté à ' + budget + '€/j' : 'Campagne lancée'}
          </h3>
          <div style={{ font: '500 13px var(--font-sans)', color: 'var(--ink-3)', marginTop: 4 }}>
            ID Meta · <b style={{ color: 'var(--ink)' }}>{video.metaCampaign || '6543' + Math.floor(Math.random()*1000)}</b> · audience <b style={{ color: 'var(--ink)' }}>{aud?.name}</b>
          </div>
          <div style={{ display: 'flex', gap: 8, justifyContent: 'center', marginTop: 18 }}>
            <Btn variant="ghost">Ouvrir dans Meta Ads Manager ↗</Btn>
            <Btn variant="dark" onClick={onClose}>OK, retour au pipeline</Btn>
          </div>
        </div>
      ) : (
        <>
          {/* Body */}
          <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 18 }}>
            {/* Créa preview */}
            <div style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: 12, background: 'var(--paper-2)', borderRadius: 10,
            }}>
              <div style={{ width: 48, height: 64, flex: 'none', borderRadius: 6, overflow: 'hidden' }}>
                <Thumb ratio={64/48} />
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ font: '600 13.5px var(--font-sans)' }}>{inf.handle} <span style={{ font: '500 11px var(--font-sans)', color: 'var(--ink-3)' }}>· {inf.name}</span></div>
                <div style={{ font: '500 11.5px var(--font-mono)', color: 'var(--ink-3)' }}>
                  {mode === 'scale' ? `camp #${video.metaCampaign} · J${video.daysLive} · CTR ${video.kpi?.ctr}` : `créa finale · ${video.finalFile || 'final.mp4'}`}
                </div>
              </div>
              <PromoCode code={inf.code} />
            </div>

            {/* Audience picker */}
            <div>
              <div style={{ font: '600 12px var(--font-sans)', color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 1, marginBottom: 8 }}>
                Audience
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {window.TA_META_AUDIENCES.map(a => {
                  const sel = a.id === audId;
                  return (
                    <label key={a.id} style={{
                      display: 'flex', alignItems: 'center', gap: 10,
                      padding: '10px 12px', borderRadius: 8,
                      background: sel ? 'var(--primary-soft)' : 'var(--paper)',
                      border: sel ? '1px solid #c9d6ff' : '1px solid var(--border)',
                      cursor: 'pointer',
                    }}>
                      <input
                        type="radio" name="aud" value={a.id}
                        checked={sel} onChange={() => setAudId(a.id)}
                        style={{ accentColor: 'var(--primary)' }}
                      />
                      <div style={{ flex: 1 }}>
                        <div style={{ font: '600 13px var(--font-sans)' }}>{a.name}</div>
                        <div style={{ font: '500 11px var(--font-mono)', color: 'var(--ink-3)' }}>~{a.size} personnes</div>
                      </div>
                      {a.isDefault && <StatusPill variant="gray" size="sm">par défaut</StatusPill>}
                    </label>
                  );
                })}
              </div>
            </div>

            {/* Budget */}
            <div>
              <div style={{ display: 'flex', alignItems: 'baseline', marginBottom: 8 }}>
                <span style={{ font: '600 12px var(--font-sans)', color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 1 }}>
                  Budget quotidien
                </span>
                {mode === 'scale' && video.kpi?.spend && (
                  <span style={{ marginLeft: 8, font: '500 11px var(--font-sans)', color: 'var(--ink-3)' }}>actuel · {video.kpi.spend}/j</span>
                )}
                <span style={{ marginLeft: 'auto', font: '700 22px var(--font-sans)', color: 'var(--ink)' }}>{budget}€</span>
              </div>
              <input
                type="range" min={10} max={mode === 'scale' ? 500 : 80} step={5}
                value={budget} onChange={(e) => setBudget(+e.target.value)}
                style={{ width: '100%', accentColor: 'var(--primary)' }}
              />
              <div style={{ display: 'flex', justifyContent: 'space-between', font: '500 10.5px var(--font-mono)', color: 'var(--ink-3)', marginTop: 3 }}>
                <span>10€</span>
                <span style={{ color: 'var(--ink-2)' }}>~ {Math.round(budget * 28)} impressions estimées / jour</span>
                <span>{mode === 'scale' ? '500€' : '80€'}</span>
              </div>
            </div>

            {/* Durée de test */}
            {mode === 'push' && (
              <div style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: 10, background: 'var(--paper-2)', borderRadius: 8,
                font: '500 12.5px var(--font-sans)', color: 'var(--ink-2)',
              }}>
                <span>⏱</span>
                <span>Test sur <b style={{ color: 'var(--ink)' }}>3 jours</b>, verdict automatique si CPA &gt; 30€ après J2.</span>
                <span style={{ marginLeft: 'auto', color: 'var(--primary)', cursor: 'pointer' }}>modifier</span>
              </div>
            )}
          </div>

          {/* Footer */}
          <div style={{
            padding: '14px 24px', borderTop: '1px solid var(--border)',
            display: 'flex', alignItems: 'center', gap: 10,
            background: 'var(--paper-2)', borderRadius: '0 0 14px 14px',
          }}>
            <div style={{ font: '500 12px var(--font-sans)', color: 'var(--ink-3)', flex: 1 }}>
              budget × 3 jours = <b style={{ color: 'var(--ink)' }}>{budget * 3}€</b> estimé
            </div>
            <Btn variant="ghost" onClick={onClose}>Annuler</Btn>
            <Btn variant={mode === 'scale' ? 'success' : 'primary'} onClick={() => setPushed(true)}>
              {mode === 'scale' ? '🚀 Confirmer le scale' : '📡 Lancer la campagne'}
            </Btn>
          </div>
        </>
      )}
    </Modal>
  );
}

window.TA_MODALS = { Modal, KillModal, PushMetaModal };
