// Testing Ads — Pipeline kanban (interactif)

const { Avatar, StatusPill, FilterPill, Btn, Thumb, PromoCode, Card } = window.WF;
const { KillModal, PushMetaModal } = window.TA_MODALS;
const { TA_FORMAT, TA_STATUS_META } = window;

// ——— En-tête de colonne ———
function ColHeader({ status, count, owner, accent }) {
  const s = TA_STATUS_META[status];
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '0 4px 10px' }}>
      <span style={{ fontSize: 14 }}>{s.emoji}</span>
      <span style={{ font: '700 13px var(--font-sans)', color: 'var(--ink)' }}>{s.label}</span>
      <span style={{
        font: '600 11px var(--font-mono)', color: 'var(--ink-3)',
        background: 'var(--paper-2)', padding: '1px 6px', borderRadius: 999,
      }}>{count}</span>
      {owner && <span style={{ marginLeft: 'auto', font: '500 11px var(--font-sans)', color: 'var(--ink-3)' }}>{owner}</span>}
    </div>
  );
}

// ——— Carte vidéo (visuelle, V.B) ———
function VideoCard({ video, onOpen, onAction, onScale, onKill, dispatch, isDragging, setDragId, dragId }) {
  const inf = window.TA_INFLUENCERS[video.inf];
  const stale = TA_FORMAT.isStale(video, 4);
  const ageLabel = TA_FORMAT.ageShort(video.receivedHours);

  // Action contextuelle selon statut
  const renderAction = () => {
    if (video.status === 'toEdit') {
      return (
        <div style={{ display: 'flex', gap: 5 }}>
          <Btn size="sm" variant="dark" style={{ flex: 1 }} onClick={(e) => { e.stopPropagation(); onAction('take', video); }}>Je prends</Btn>
          <Btn size="sm" variant="ghost" onClick={(e) => { e.stopPropagation(); onAction('downloadKit', video); }} title="Kit zip">↓</Btn>
        </div>
      );
    }
    if (video.status === 'editing') {
      return (
        <Btn size="sm" variant="primary" style={{ width: '100%' }} onClick={(e) => { e.stopPropagation(); onAction('upload', video); }}>
          ↑ Déposer le final
        </Btn>
      );
    }
    if (video.status === 'edited') {
      return (
        <Btn size="sm" variant="success" style={{ width: '100%' }} onClick={(e) => { e.stopPropagation(); onAction('push', video); }}>
          📡 Pousser en testing
        </Btn>
      );
    }
    if (video.status === 'testing') {
      return (
        <div style={{ display: 'flex', gap: 5 }}>
          <Btn size="sm" variant="danger" style={{ flex: 1 }} onClick={(e) => { e.stopPropagation(); onKill(video); }}>✗ Kill</Btn>
          <Btn size="sm" variant="success" style={{ flex: 1 }} onClick={(e) => { e.stopPropagation(); onScale(video); }}>✓ Scale</Btn>
        </div>
      );
    }
    return null;
  };

  return (
    <Card
      draggable
      onDragStart={(e) => { setDragId(video.id); e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', video.id); }}
      onDragEnd={() => setDragId(null)}
      onClick={() => onOpen?.(video)}
      style={{
        padding: 8, marginBottom: 10, cursor: 'pointer',
        borderColor: stale ? '#fda4a4' : 'var(--border)',
        opacity: isDragging ? 0.4 : 1,
        transition: 'box-shadow 120ms ease',
      }}
      onMouseEnter={(e) => e.currentTarget.style.boxShadow = '0 4px 16px rgba(0,0,0,0.06)'}
      onMouseLeave={(e) => e.currentTarget.style.boxShadow = 'none'}
    >
      <div style={{ position: 'relative' }}>
        <Thumb ratio={1.05} dur={video.dur} />
        <div style={{ position: 'absolute', top: 8, right: 8 }}>
          {stale ? (
            <StatusPill variant="red" size="sm">⚠ {ageLabel}</StatusPill>
          ) : (
            <span style={{
              background: 'rgba(0,0,0,0.7)', color: '#fff',
              padding: '2px 8px', borderRadius: 999,
              font: '500 10px var(--font-mono)',
            }}>{ageLabel}</span>
          )}
        </div>
        {video.status === 'editing' && (
          <div style={{
            position: 'absolute', bottom: 8, left: 8,
            background: 'rgba(17,17,17,0.85)', color: '#fff',
            padding: '3px 9px', borderRadius: 999,
            font: '600 10.5px var(--font-sans)',
            display: 'flex', alignItems: 'center', gap: 5,
          }}>
            <span style={{ width: 5, height: 5, borderRadius: '50%', background: '#4ade80' }}></span>
            Katlyn · {video.takenHoursAgo}h
          </div>
        )}
      </div>

      <div style={{ padding: '10px 4px 4px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
          <Avatar name={inf.name} size={22} />
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ font: '600 13px var(--font-sans)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{inf.handle}</div>
            <div style={{ font: '500 11px var(--font-sans)', color: 'var(--ink-3)' }}>{inf.name}</div>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 9 }}>
          <PromoCode code={inf.code} />
          {video.kpi && (
            <span style={{ font: '500 10.5px var(--font-mono)', color: 'var(--ink-3)' }}>J{video.daysLive}</span>
          )}
        </div>

        {video.kpi && (
          <div style={{
            display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 4,
            marginTop: 8, padding: '6px 8px',
            background: video.kpi.signal === 'scale' ? '#eefbef' : video.kpi.signal === 'kill' ? '#fff0ee' : 'var(--paper-2)',
            border: video.kpi.signal === 'scale' ? '1px solid #bbe6b5' : video.kpi.signal === 'kill' ? '1px solid #ffcdc7' : '1px solid transparent',
            borderRadius: 7,
            font: '500 11px var(--font-mono)', color: 'var(--ink-3)',
          }}>
            <span>CTR <b style={{ color: 'var(--ink)' }}>{video.kpi.ctr}</b></span>
            <span>CPA <b style={{ color: 'var(--ink)' }}>{video.kpi.cpa}</b></span>
            <span>ROAS <b style={{ color: 'var(--ink)' }}>{video.kpi.roas}</b></span>
          </div>
        )}

        {video.status === 'editing' && (
          <div style={{
            marginTop: 8, padding: '6px 10px',
            background: 'var(--paper-2)', borderRadius: 7,
            font: '500 11px var(--font-mono)', color: 'var(--ink-3)',
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <span>🎬</span>
            <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis' }}>katlyn-{inf.code}-v2.mp4</span>
          </div>
        )}

        {video.status === 'edited' && video.finalFile && (
          <div style={{
            marginTop: 8, padding: '6px 10px',
            background: 'var(--st-grn-bg)', borderRadius: 7,
            font: '500 11px var(--font-mono)', color: 'var(--st-grn-tx)',
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <span>✓</span>
            <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis' }}>{video.finalFile}</span>
            <span>{video.finalSize}</span>
          </div>
        )}

        {renderAction() && <div style={{ marginTop: 10 }}>{renderAction()}</div>}
      </div>
    </Card>
  );
}

// ——— État vide d'une colonne ———
function EmptyColumn({ status }) {
  const s = TA_STATUS_META[status];
  return (
    <div style={{
      padding: '24px 14px', textAlign: 'center',
      border: '1.5px dashed var(--border-2)', borderRadius: 10,
      background: 'var(--paper)',
    }}>
      <div style={{ fontSize: 28, marginBottom: 6, opacity: 0.4 }}>{s.emoji}</div>
      <div style={{ font: '600 12.5px var(--font-sans)', color: 'var(--ink-2)', marginBottom: 3 }}>
        Aucune vidéo {s.label.toLowerCase()}
      </div>
      <div style={{ font: '500 11.5px var(--font-sans)', color: 'var(--ink-3)' }}>{s.description}</div>
    </div>
  );
}

// ——— Bandeau ENTRANTS (Source + Kit, auto) ———
function IncomingStrip({ videos }) {
  const sourceV = videos.filter(v => v.status === 'source');
  const kitV = videos.filter(v => v.status === 'kit');
  const all = [...sourceV, ...kitV];

  return (
    <Card style={{
      padding: 12, marginBottom: 14,
      display: 'flex', alignItems: 'center', gap: 14,
    }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 1, flex: 'none' }}>
        <span style={{ font: '600 11px var(--font-sans)', color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 1 }}>Entrants · auto</span>
        <span style={{ font: '500 11px var(--font-sans)', color: 'var(--ink-3)' }}>transcription + extraction hooks</span>
      </div>
      <div style={{ height: 38, width: 1, background: 'var(--border)', flex: 'none' }} />
      <div style={{ display: 'flex', gap: 8, flex: 1, overflow: 'hidden' }}>
        {all.length === 0 ? (
          <div style={{ font: '500 12px var(--font-sans)', color: 'var(--ink-3)', alignSelf: 'center' }}>
            Aucune vidéo entrante · prochaine arrivée hebdo estimée vendredi
          </div>
        ) : all.map((v) => {
          const inf = window.TA_INFLUENCERS[v.inf];
          const isKit = v.status === 'kit';
          return (
            <div key={v.id} style={{
              display: 'flex', alignItems: 'center', gap: 7,
              padding: '5px 12px 5px 5px', background: 'var(--paper-2)', borderRadius: 999,
              flex: 'none',
            }}>
              <div style={{ width: 28, height: 36, borderRadius: 6, overflow: 'hidden', flex: 'none', position: 'relative' }}>
                <Thumb ratio={36/28} style={{ borderRadius: 0 }} />
                {isKit && (
                  <div style={{
                    position: 'absolute', bottom: 0, left: 0, right: 0, height: 3,
                    background: 'rgba(0,0,0,0.1)',
                  }}>
                    <div style={{ height: '100%', width: `${v.kitProgress * 100}%`, background: 'var(--primary)' }} />
                  </div>
                )}
              </div>
              <div style={{ minWidth: 0 }}>
                <div style={{ font: '600 11.5px var(--font-sans)' }}>{inf.handle}</div>
                <div style={{ font: '500 10px var(--font-mono)', color: isKit ? 'var(--primary)' : 'var(--ink-3)' }}>
                  {isKit ? `⚙️ kit · ${Math.round(v.kitProgress * 100)}%` : '📥 reçue · à l\'instant'}
                </div>
              </div>
            </div>
          );
        })}
      </div>
      <span style={{ font: '500 11px var(--font-sans)', color: 'var(--ink-3)', flex: 'none' }}>
        dernière entrée · il y a 12 min
      </span>
    </Card>
  );
}

// ——— Pipeline (kanban) ———
function PipelinePage({ state, dispatch, onOpenVideo, onOpenInfluencer }) {
  const [dragId, setDragId] = React.useState(null);
  const [hoverCol, setHoverCol] = React.useState(null);
  const [killTarget, setKillTarget] = React.useState(null);
  const [pushTarget, setPushTarget] = React.useState(null); // {video, mode}
  const fileInputRef = React.useRef(null);
  const [uploadingFor, setUploadingFor] = React.useState(null);
  const [uploadProgress, setUploadProgress] = React.useState(0);

  // — Filtre statut courant (chips top)
  const [filter, setFilter] = React.useState('all');
  const visible = state.videos.filter(v => filter === 'all' || v.status === filter);

  // — Mouvement d'une carte
  const handleDrop = (newStatus, e) => {
    e.preventDefault();
    setHoverCol(null);
    const id = e.dataTransfer.getData('text/plain') || dragId;
    if (!id) return;
    const v = state.videos.find(x => x.id === id);
    if (!v || v.status === newStatus) return;
    // Drop sur verdict → ouvre modale appropriée
    if (newStatus === 'killed') return setKillTarget(v);
    if (newStatus === 'scaled') return setPushTarget({ video: v, mode: 'scale' });
    if (newStatus === 'testing' && v.status === 'edited') return setPushTarget({ video: v, mode: 'push' });
    dispatch({ type: 'moveTo', id, status: newStatus });
  };

  // — Action contextuelle déclenchée par bouton
  const handleAction = (action, video) => {
    if (action === 'take') dispatch({ type: 'moveTo', id: video.id, status: 'editing', extra: { takenBy: 'Katlyn', takenHoursAgo: 0 } });
    if (action === 'downloadKit') alert('Téléchargement du kit ' + video.id + ' (.zip · 47Mo) — simulé');
    if (action === 'upload') {
      setUploadingFor(video.id);
      fileInputRef.current?.click();
    }
    if (action === 'push') setPushTarget({ video, mode: 'push' });
  };

  // Simule upload progressif
  const handleFile = (e) => {
    const f = e.target.files?.[0];
    if (!f || !uploadingFor) return;
    setUploadProgress(0);
    const tick = setInterval(() => {
      setUploadProgress(p => {
        const n = Math.min(1, p + 0.12);
        if (n >= 1) {
          clearInterval(tick);
          dispatch({ type: 'moveTo', id: uploadingFor, status: 'edited', extra: { finalFile: f.name, finalSize: (f.size / 1024 / 1024).toFixed(0) + 'Mo' } });
          setUploadingFor(null);
        }
        return n;
      });
    }, 180);
    e.target.value = '';
  };

  const columns = ['toEdit', 'editing', 'edited', 'testing'];
  const counts = Object.fromEntries(window.TA_PIPELINE_ORDER.map(s => [s, state.videos.filter(v => v.status === s).length]));

  return (
    <>
      {/* Filtres en pills (top) */}
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 14 }}>
        <FilterPill active={filter === 'all'} count={state.videos.filter(v => !['scaled','killed'].includes(v.status)).length}>
          <span onClick={() => setFilter('all')}>Toutes</span>
        </FilterPill>
        {['source','kit','toEdit','editing','edited','testing','scaled','killed'].map(s => {
          const m = TA_STATUS_META[s];
          return (
            <span key={s} onClick={() => setFilter(s)}>
              <FilterPill active={filter === s} emoji={m.emoji} count={counts[s] || 0}>{m.short}</FilterPill>
            </span>
          );
        })}
      </div>

      {/* Bandeau entrants */}
      <IncomingStrip videos={state.videos} />

      {/* Upload en cours overlay */}
      {uploadingFor && uploadProgress > 0 && (
        <div style={{
          position: 'absolute', top: 22, left: '50%', transform: 'translateX(-50%)',
          padding: '10px 16px', background: '#111', color: '#fff', borderRadius: 10,
          font: '600 12.5px var(--font-sans)',
          display: 'flex', alignItems: 'center', gap: 10, zIndex: 100,
          boxShadow: '0 8px 24px rgba(0,0,0,0.2)',
        }}>
          <span>↑ Upload en cours…</span>
          <div style={{ width: 120, height: 6, borderRadius: 3, background: 'rgba(255,255,255,0.2)' }}>
            <div style={{ height: '100%', width: `${uploadProgress * 100}%`, background: '#4ade80', borderRadius: 3, transition: 'width 180ms' }} />
          </div>
          <span style={{ font: '500 11px var(--font-mono)' }}>{Math.round(uploadProgress * 100)}%</span>
        </div>
      )}

      {/* Hidden input pour drop final */}
      <input ref={fileInputRef} type="file" accept="video/*" onChange={handleFile} style={{ display: 'none' }} />

      {/* 4 colonnes humaines */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, flex: 1, minHeight: 0, alignItems: 'start' }}>
        {columns.map(status => {
          const items = state.videos.filter(v => v.status === status);
          const ownerLabel = { toEdit: '🪡 Katlyn', editing: '✂ WIP', edited: '🚀 Benjamin', testing: '📡 Live Meta' }[status];
          return (
            <div key={status}
              onDragOver={(e) => { e.preventDefault(); setHoverCol(status); }}
              onDragLeave={() => setHoverCol(h => h === status ? null : h)}
              onDrop={(e) => handleDrop(status, e)}
              className={hoverCol === status ? 'drop-target-active' : ''}
              style={{
                background: 'var(--paper-2)', borderRadius: 10,
                padding: '12px 10px', minHeight: 200,
                display: 'flex', flexDirection: 'column',
              }}>
              <ColHeader status={status} count={items.length} owner={ownerLabel} />
              <div className="scroll-y" style={{ flex: 1, minHeight: 0 }}>
                {items.length === 0
                  ? <EmptyColumn status={status} />
                  : items.map(v => (
                      <VideoCard
                        key={v.id} video={v}
                        onOpen={onOpenVideo}
                        onAction={handleAction}
                        onScale={(video) => setPushTarget({ video, mode: 'scale' })}
                        onKill={(video) => setKillTarget(video)}
                        isDragging={dragId === v.id}
                        setDragId={setDragId} dragId={dragId}
                      />
                    ))
                }
              </div>
            </div>
          );
        })}
      </div>

      {/* Verdict scoreboard */}
      <div
        onDragOver={(e) => e.preventDefault()}
        onDrop={(e) => {
          // Sur le scoreboard, on déduit selon X position : moitié gauche = scale, droite = kill
          const rect = e.currentTarget.getBoundingClientRect();
          const isKill = (e.clientX - rect.left) > rect.width / 2;
          handleDrop(isKill ? 'killed' : 'scaled', e);
        }}
        style={{ marginTop: 14 }}
      >
        <Card style={{
          padding: 12,
          display: 'flex', alignItems: 'center', gap: 14,
        }}>
          <span style={{ font: '600 11px var(--font-sans)', color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 1 }}>Verdict · 7j</span>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
            <span style={{ font: '700 22px var(--font-sans)', color: '#166534' }}>{counts.scaled + 11}</span>
            <span style={{ font: '600 12px var(--font-sans)', color: '#166534' }}>scalées 🚀</span>
          </div>
          <div style={{ width: 1, height: 22, background: 'var(--border)' }} />
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
            <span style={{ font: '700 22px var(--font-sans)', color: '#b91c1c' }}>{counts.killed + 27}</span>
            <span style={{ font: '600 12px var(--font-sans)', color: '#b91c1c' }}>killées ❌</span>
          </div>
          <div style={{ width: 1, height: 22, background: 'var(--border)' }} />
          <span style={{ font: '500 12px var(--font-sans)', color: 'var(--ink-3)' }}>scale rate <b style={{ color: 'var(--ink)' }}>30%</b></span>
          <span style={{ marginLeft: 'auto', font: '500 11.5px var(--font-sans)', color: 'var(--ink-3)' }}>
            astuce · glisse une ad ici pour scaler (gauche) ou killer (droite)
          </span>
        </Card>
      </div>

      {/* Modales */}
      <KillModal
        open={!!killTarget} video={killTarget}
        onClose={() => setKillTarget(null)}
        onConfirm={({ reason, comment }) => {
          dispatch({ type: 'moveTo', id: killTarget.id, status: 'killed', extra: { killReason: reason, killNote: comment } });
          setKillTarget(null);
        }}
      />
      <PushMetaModal
        open={!!pushTarget} video={pushTarget?.video} mode={pushTarget?.mode}
        onClose={() => setPushTarget(null)}
        onConfirm={() => {
          if (pushTarget.mode === 'push') {
            dispatch({ type: 'moveTo', id: pushTarget.video.id, status: 'testing', extra: { metaCampaign: '6543' + Math.floor(Math.random()*1000), daysLive: 0, kpi: { ctr: '—', cpa: '—', roas: '—', spend: '0€', impressions: '0' } } });
          } else {
            dispatch({ type: 'moveTo', id: pushTarget.video.id, status: 'scaled' });
          }
          setPushTarget(null);
        }}
      />
    </>
  );
}

window.TA_PIPELINE = { PipelinePage, VideoCard };
