// Pipeline: Kanban de 10 estágios (280px por coluna, rolagem horizontal), drag and drop HTML5, aging por etapa,
// filtro por responsável e ordenação. Mobile: chips de estágio, uma coluna por vez e "Mover para". Mudanças ficam em memória.
const PL_SORT = { Score: (a, b) => b.total - a.total, Valor: (a, b) => b.potential - a.potential, Aging: (a, b) => b.age - a.age };

function PipelineScreen() {
  const { PageHeader, Select, SegmentedControl, FilterChip, StatusDot, Badge, Avatar, EmptyState } = window.VRticeDesignSystem_d763eb;
  const { bp, toast, go } = useShell();
  const { can } = useAccess();
  const C = window.VXCommercial;
  const P = useProspects();
  const [owner, setOwner] = React.useState('Todos'), [sort, setSort] = React.useState('Score');
  const [drag, setDrag] = React.useState(null), [over, setOver] = React.useState(null), [flash, setFlash] = React.useState(null), [mob, setMob] = React.useState('QUALIFIED');
  const ft = React.useRef(null);
  React.useEffect(() => () => clearTimeout(ft.current), []);
  const edit = can('commercial_intelligence.edit');
  const all = P.filter(p => owner === 'Todos' || (owner === 'Sem responsável' ? !p.owner : p.owner === owner));
  // Confirma só depois que o banco gravou; falha (total ou parcial) aparece como erro.
  const move = async (id, st) => {
    if (!edit) return toast('Sem permissão: commercial_intelligence.edit', 'ph-lock-simple');
    if (P.find(p => p.id === id).stage === st) return;
    try {
      await C.stages.set(id, st);
      setFlash(id); clearTimeout(ft.current); ft.current = setTimeout(() => setFlash(null), 1400);
      toast('Movido para ' + C.STG[st].label, 'ph-arrows-left-right');
    } catch (e) {
      toast(e.partial ? e.message : 'Não foi possível mover: ' + (e.message || e), 'ph-warning');
    }
  };
  const card = p => {
    const ageT = p.age > 21 ? 'danger' : p.age > 14 ? 'warning' : 'neutral';
    return (
      <div key={p.id} draggable={edit && bp !== 'mobile'} onDragStart={e => { setDrag(p.id); e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', p.id); }} onDragEnd={() => { setDrag(null); setOver(null); }} onClick={() => go('prospect', { id: p.id })} className="vx-hovercard" style={{ background: 'var(--surface-card)', border: '1px solid ' + (flash === p.id ? 'var(--vx-sky-400)' : 'var(--border-default)'), borderRadius: 12, padding: 14, display: 'flex', flexDirection: 'column', gap: 10, cursor: edit ? 'grab' : 'pointer', opacity: drag === p.id ? 0.4 : 1, transition: 'border-color .15s, opacity .15s' }}>
        <span style={{ display: 'flex', justifyContent: 'space-between', gap: 8, alignItems: 'flex-start' }}><span style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}><strong style={{ fontSize: 14 }}>{p.name}</strong><span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{p.city} - {p.uf}</span></span><ScoreChip v={p.total} /></span>
        <span style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}><span style={{ ...cxMono, fontSize: 13, color: 'var(--text-accent)' }}>{cxBrl(p.potential)}</span><Badge variant="meta" tone={ageT}>{p.age} d na etapa</Badge></span>
        <span style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8, borderTop: '1px solid var(--border-subtle)', paddingTop: 10 }}>
          <span style={{ display: 'flex', flexDirection: 'column', gap: 1, minWidth: 0 }}><span style={{ fontSize: 12, color: 'var(--text-strong)' }}>{p.next}</span><span style={{ fontSize: 11, color: p.due.startsWith('atras') ? 'var(--status-danger-text)' : 'var(--text-subtle)' }}>{p.due}</span></span>
          {p.owner ? <Avatar name={p.owner} size={26} /> : <i className="ph ph-user-circle-dashed" title="Sem responsável" style={{ fontSize: 26, color: 'var(--status-warning)' }} />}
        </span>
        {bp === 'mobile' && <span onClick={e => e.stopPropagation()}><Select compact value={p.stage} onChange={e => move(p.id, e.target.value)} disabled={!edit} aria-label="Mover para">{C.STAGES.map(s => <option key={s[0]} value={s[0]}>Mover para {s[1]}</option>)}</Select></span>}
      </div>
    );
  };
  const colsToShow = bp === 'mobile' ? C.STAGES.filter(s => s[0] === mob) : C.STAGES;
  const total = all.filter(p => !['LOST', 'CUSTOMER'].includes(p.stage)).reduce((a, p) => a + p.potential, 0);
  return (
    <BlockGrid.Auto id="pipeline">
      <PageHeader size="lg" eyebrow="COMERCIAL" title="Pipeline" description={'Valor potencial em aberto: ' + cxBrl(total) + ' · arraste os cartões para mudar de estágio.'} actions={<PBtn perm="commercial_intelligence.create" icon="ph-plus" onClick={() => go('prospects')}>Adicionar prospect</PBtn>} />
      <ReadOnlyNote perm="commercial_intelligence.edit" />
      <CxLoadError />
      <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
        <div style={{ width: 200 }}><Select compact options={['Todos', 'Sem responsável', ...C.OWNERS]} value={owner} onChange={e => setOwner(e.target.value)} aria-label="Responsável" /></div>
        <SegmentedControl value={sort} onChange={setSort} options={Object.keys(PL_SORT)} />
        <span style={{ fontSize: 13, color: 'var(--text-subtle)' }}>Ordenar cartões por</span>
      </div>
      {bp === 'mobile' && <div style={{ display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 4 }}>{C.STAGES.map(s => <FilterChip key={s[0]} label={s[1]} tone={s[2]} count={all.filter(p => p.stage === s[0]).length} selected={mob === s[0]} onClick={() => setMob(s[0])} />)}</div>}
      <div style={{ display: 'flex', gap: 14, overflowX: 'auto', alignItems: 'flex-start', paddingBottom: 12 }}>
        {colsToShow.map(([id, label, tone]) => {
          const cs = all.filter(p => p.stage === id).sort(PL_SORT[sort]), hot = over === id && drag;
          return (
            <div key={id} onDragOver={e => { if (edit && drag) { e.preventDefault(); setOver(id); } }} onDragLeave={() => setOver(o => o === id ? null : o)} onDrop={e => { e.preventDefault(); if (drag) move(drag, id); setDrag(null); setOver(null); }} style={{ flex: bp === 'mobile' ? '1 1 100%' : '0 0 280px', background: 'var(--surface-sunken)', border: '1px ' + (hot ? 'dashed' : 'solid') + ' ' + (hot ? 'var(--vx-sky-400)' : 'var(--border-default)'), borderRadius: 16, padding: 12, display: 'flex', flexDirection: 'column', gap: 10, minHeight: 200, transition: 'border-color .15s' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '4px 4px 2px' }}><StatusDot tone={tone} label={label} /><span style={{ ...cxMono, fontSize: 12, color: 'var(--text-muted)' }}>{cs.length} · {cxBrl(cs.reduce((a, p) => a + p.potential, 0))}</span></div>
              {cs.map(card)}
              {!cs.length && <EmptyState variant="dropzone">Arraste itens para cá</EmptyState>}
            </div>
          );
        })}
      </div>
    </BlockGrid.Auto>
  );
}
window.PipelineScreen = PipelineScreen;
