/* ========== Pipeline 河流視圖 ========== */

function PipelineView({ items, onSelect, narrow }) {
  const [filter, setFilter] = useState('all');
  const [mode, setMode] = useState('flow'); // flow | board | list

  const counts = useMemo(() => {
    const c = {};
    STATUSES.forEach(s => c[s] = items.filter(i => i.status === s).length);
    return c;
  }, [items]);

  const stuckTotal = items.filter(isStuck).length;

  return (
    <div style={{ flex: 1, overflowY: 'auto', padding: 22 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 16, flexWrap: 'wrap' }}>
        <h1 style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em' }}>Pipeline</h1>
        <Pill color="var(--ink-2)" bg="var(--bg-2)" border="var(--line)" size="md">{items.length} 筆</Pill>
        {stuckTotal > 0 && <Pill color="var(--low)" bg="var(--low-tint)" border="var(--low-glow)" size="md">⚠ {stuckTotal} 卡關</Pill>}
        <div style={{ flex: 1 }} />
        <div style={{ display: 'flex', gap: 2, padding: 3, background: 'var(--bg-2)', borderRadius: 7, border: '1px solid var(--line)' }}>
          {[['flow','河流'],['board','看板'],['list','清單']].map(([m, l]) => (
            <button key={m} onClick={() => setMode(m)} style={{
              padding: '5px 11px', borderRadius: 5, fontSize: 11.5, fontWeight: 500,
              background: mode === m ? 'var(--bg-4)' : 'transparent',
              color: mode === m ? 'var(--ink-0)' : 'var(--ink-2)',
            }}>{l}</button>
          ))}
        </div>
      </div>

      {/* 河流圖：階段梯形 */}
      {mode === 'flow' && <FlowDiagram items={items} counts={counts} onSelect={onSelect} />}
      {mode === 'board' && <BoardMode items={items} onSelect={onSelect} />}
      {mode === 'list' && <ListMode items={items} onSelect={onSelect} />}
    </div>
  );
}

function FlowDiagram({ items, counts, onSelect }) {
  const stages = ['inbox', 'selected', '待拍', '剪輯中', '已上線'];
  const max = Math.max(...stages.map(s => counts[s] || 0), 1);

  return (
    <div>
      {/* 漏斗條：每個階段相對寬度 */}
      <div style={{
        display: 'grid', gridTemplateColumns: stages.map(s => `${Math.max(0.6, (counts[s] || 0) / max)}fr`).join(' '),
        gap: 8, marginBottom: 22, height: 100,
      }}>
        {stages.map((s, i) => (
          <FlowStage key={s} stage={s} count={counts[s]} stuckCount={items.filter(i => i.status === s && isStuck(i)).length} delay={i * 0.08} />
        ))}
      </div>

      {/* 各階段詳情 */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {stages.map(s => {
          const stageItems = items.filter(i => i.status === s);
          if (stageItems.length === 0) return null;
          return (
            <Card
              key={s}
              padding={0}
              accent={stageColor(s)}
              title={
                <span style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                  <Dot color={stageColor(s)} size={8} />
                  <span style={{ color: stageColor(s) }}>{STAGE_LABELS[s]}</span>
                  <Pill color="var(--ink-2)" bg="var(--bg-3)">{stageItems.length}</Pill>
                  {THRESHOLDS[s] && <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>時限 ≤ {THRESHOLDS[s]} 天</span>}
                </span>
              }
            >
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 1, background: 'var(--line-faint)' }}>
                {stageItems.map(it => <PipeCard key={it.id} item={it} onClick={() => onSelect(it.id)} />)}
              </div>
            </Card>
          );
        })}
      </div>
    </div>
  );
}

function FlowStage({ stage, count, stuckCount, delay }) {
  return (
    <div style={{
      background: `linear-gradient(180deg, ${stageColor(stage)}22, ${stageColor(stage)}08)`,
      border: `1px solid ${stageColor(stage)}33`,
      borderRadius: 8, padding: 12,
      display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
      animation: `slide-up 0.4s ${delay}s var(--ease-out) both`,
      position: 'relative', overflow: 'hidden',
    }}>
      <div style={{ fontSize: 11, color: stageColor(stage), fontWeight: 600 }}>{STAGE_LABELS[stage]}</div>
      <div className="mono" style={{ fontSize: 28, fontWeight: 700, color: 'var(--ink-0)', lineHeight: 1 }}>{count}</div>
      {stuckCount > 0 && (
        <div className="mono" style={{ fontSize: 10, color: 'var(--low)', fontWeight: 600 }}>⚠ {stuckCount} 卡</div>
      )}
    </div>
  );
}

function PipeCard({ item, onClick }) {
  const stuck = isStuck(item);
  const perf = item.b?.p;
  return (
    <button onClick={onClick} style={{
      background: 'var(--bg-1)', padding: 12, textAlign: 'left',
      transition: 'background 0.12s',
      borderLeft: stuck ? '3px solid var(--low)' : perf === 'high' ? '3px solid var(--high)' : '3px solid transparent',
    }}
      onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-2)'}
      onMouseLeave={e => e.currentTarget.style.background = 'var(--bg-1)'}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6, flexWrap: 'wrap' }}>
        <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>{item.id}</span>
        {item.vid && <><span style={{ color: 'var(--ink-3)' }}>→</span><span className="mono" style={{ fontSize: 10, color: 'var(--kai-bright)' }}>{item.vid}</span></>}
        <div style={{ flex: 1 }} />
        {perf === 'high' && <Pill color="var(--high)" bg="var(--high-tint)" size="xs">🏆</Pill>}
        {stuck && <Pill color="var(--low)" bg="var(--low-tint)" size="xs">{item.age}d</Pill>}
      </div>
      <div style={{ fontSize: 12.5, color: 'var(--ink-0)', lineHeight: 1.4, marginBottom: 6, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
        {item.title || item.topic}
      </div>
      {item.b && (
        <div style={{ display: 'flex', gap: 12, fontSize: 10.5, fontFamily: 'var(--mono)', color: 'var(--ink-2)' }}>
          <span>👁 {fmtNum(item.b.v)}</span>
          <span>留 {fmtPct(item.b.r, 0)}</span>
          <span>完 {fmtPct(item.b.c, 0)}</span>
        </div>
      )}
      {!item.b && item.tags?.length > 0 && (
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {item.tags.slice(0, 2).map(t => <Pill key={t} color="var(--ink-2)" size="xs">#{t}</Pill>)}
        </div>
      )}
    </button>
  );
}

function BoardMode({ items, onSelect }) {
  const stages = ['inbox', 'selected', '待拍', '剪輯中', '已上線'];
  return (
    <div style={{ display: 'flex', gap: 12, overflowX: 'auto', paddingBottom: 8 }}>
      {stages.map(s => {
        const stageItems = items.filter(i => i.status === s);
        return (
          <div key={s} style={{ width: 280, flexShrink: 0, background: 'var(--bg-1)', border: '1px solid var(--line)', borderRadius: 8, display: 'flex', flexDirection: 'column', maxHeight: 'calc(100vh - 220px)' }}>
            <div style={{ padding: '10px 12px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 8 }}>
              <Dot color={stageColor(s)} size={7} />
              <span style={{ fontSize: 12, fontWeight: 600, color: stageColor(s) }}>{STAGE_LABELS[s]}</span>
              <Pill color="var(--ink-3)" bg="var(--bg-3)">{stageItems.length}</Pill>
            </div>
            <div style={{ flex: 1, overflowY: 'auto', padding: 8, display: 'flex', flexDirection: 'column', gap: 6 }}>
              {stageItems.map(it => <PipeCard key={it.id} item={it} onClick={() => onSelect(it.id)} />)}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function ListMode({ items, onSelect }) {
  const [sort, setSort] = useState('age');
  const sorted = useMemo(() => {
    const a = [...items];
    if (sort === 'age') a.sort((x, y) => (y.age || 0) - (x.age || 0));
    if (sort === 'views') a.sort((x, y) => (y.b?.v || 0) - (x.b?.v || 0));
    if (sort === 'retention') a.sort((x, y) => (y.b?.r || 0) - (x.b?.r || 0));
    return a;
  }, [items, sort]);

  return (
    <Card padding={0}>
      <div style={{ display: 'grid', gridTemplateColumns: '80px 80px 1fr 90px 90px 80px 110px', padding: '10px 16px', borderBottom: '1px solid var(--line)', fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', fontFamily: 'var(--mono)', letterSpacing: '0.06em' }}>
        <div>IDEA</div><div>VID</div><div>標題</div>
        <div style={{ cursor: 'pointer', color: sort === 'age' ? 'var(--kai-bright)' : 'var(--ink-3)' }} onClick={() => setSort('age')}>狀態 ↓</div>
        <div>表現</div>
        <div style={{ cursor: 'pointer', color: sort === 'views' ? 'var(--kai-bright)' : 'var(--ink-3)' }} onClick={() => setSort('views')}>觀看</div>
        <div style={{ cursor: 'pointer', color: sort === 'retention' ? 'var(--kai-bright)' : 'var(--ink-3)' }} onClick={() => setSort('retention')}>留存/完播</div>
      </div>
      <div style={{ maxHeight: 'calc(100vh - 240px)', overflowY: 'auto' }}>
        {sorted.map(it => (
          <button key={it.id} onClick={() => onSelect(it.id)} style={{
            display: 'grid', gridTemplateColumns: '80px 80px 1fr 90px 90px 80px 110px',
            padding: '10px 16px', borderBottom: '1px solid var(--line-faint)',
            alignItems: 'center', textAlign: 'left', width: '100%',
            transition: 'background 0.1s',
          }}
            onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-2)'}
            onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
            <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>{it.id}</span>
            <span className="mono" style={{ fontSize: 10.5, color: it.vid ? 'var(--kai-bright)' : 'var(--ink-3)' }}>{it.vid || '—'}</span>
            <span style={{ fontSize: 12, color: 'var(--ink-0)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', paddingRight: 12 }}>{it.title || it.topic}</span>
            <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
              <Dot color={stageColor(it.status)} size={5} />
              <span style={{ fontSize: 11, color: stageColor(it.status) }}>{STAGE_LABELS[it.status]}</span>
            </div>
            <span style={{ fontSize: 11, color: it.b ? perfColor(it.b.p) : 'var(--ink-3)' }}>
              {it.b ? perfLabel(it.b.p) : '—'}
            </span>
            <span className="mono" style={{ fontSize: 11, color: 'var(--ink-1)' }}>{it.b ? fmtNum(it.b.v) : '—'}</span>
            <span className="mono" style={{ fontSize: 11, color: 'var(--ink-2)' }}>{it.b ? `${it.b.r.toFixed(0)}/${it.b.c.toFixed(0)}` : '—'}</span>
          </button>
        ))}
      </div>
    </Card>
  );
}

Object.assign(window, { PipelineView });
