/* ============================================================
   pipeline.jsx — Pipeline comercial (Kanban arrastável)
   ============================================================ */
function DealCard({ deal, onDragStart, onOpen, dragging }) {
  const svcNames = deal.items.map(i => i.nome);
  const stage = PIPELINE_STAGES.find(s => s.id === deal.stage);
  return (
    <article className={'deal-card' + (dragging ? ' dragging' : '')}
      draggable onDragStart={(e) => onDragStart(e, deal.id)} onClick={() => onOpen(deal)}>
      <div className="row" style={{ justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
        <div className="grow" style={{ minWidth: 0 }}>
          <h4 className="deal-name">{deal.cliente.nome || 'Sem nome'}</h4>
          {deal.cliente.empresa && <div className="deal-sub">{deal.cliente.empresa}</div>}
        </div>
        <span className="deal-grip" style={{ ['--hue']: stage ? stage.hue : 220 }} />
      </div>
      <div className="deal-tags">
        {svcNames.slice(0, 2).map((n, i) => <span key={i} className="deal-tag">{n}</span>)}
        {svcNames.length > 2 && <span className="deal-tag more">+{svcNames.length - 2}</span>}
      </div>
      <div className="deal-foot">
        <span className="mono deal-val">{fmtBRL(deal.total)}</span>
        <span className="deal-date"><Icon name="clock" size={12} /> {new Date(deal.createdAt).toLocaleDateString('pt-BR', { day: '2-digit', month: 'short' })}</span>
      </div>
    </article>
  );
}

function DealDrawer({ deal, onClose, onMove, onDelete, onResume }) {
  if (!deal) return null;
  const stage = PIPELINE_STAGES.find(s => s.id === deal.stage);
  const idx = PIPELINE_STAGES.findIndex(s => s.id === deal.stage);
  return (
    <div className="drawer-scrim" onClick={onClose}>
      <aside className="drawer fade-up" onClick={(e) => e.stopPropagation()}>
        <div className="drawer-head">
          <div>
            <Badge tone="gray">{stage?.nome}</Badge>
            <h2 style={{ fontSize: 22, marginTop: 8 }}>{deal.cliente.nome}</h2>
            {deal.cliente.empresa && <div style={{ color: 'var(--text-3)' }}>{deal.cliente.empresa}</div>}
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>

        <div className="drawer-body">
          <section className="dr-sec">
            <span className="eyebrow">Contato</span>
            <div className="dr-row"><Icon name="doc" size={15} /> {deal.cliente.doc || '—'}</div>
            <div className="dr-row"><Icon name="whatsapp" size={15} /> {deal.cliente.whatsapp || '—'}</div>
            <div className="dr-row"><Icon name="mail" size={15} /> {deal.cliente.email || '—'}</div>
            {deal.cliente.endereco && <div className="dr-row"><Icon name="pin" size={15} /> {deal.cliente.endereco}</div>}
          </section>

          <section className="dr-sec">
            <span className="eyebrow">Serviços · {fmtBRL(deal.total)}</span>
            {deal.items.map(it => (
              <div key={it.id} className="dr-item">
                <div><div style={{ fontWeight: 600, fontSize: 14 }}>{it.nome}</div><div style={{ fontSize: 12, color: 'var(--text-3)' }}>{it.prazo}</div></div>
                <span className="mono">{fmtBRL(it.preco)}</span>
              </div>
            ))}
          </section>

          <section className="dr-sec">
            <span className="eyebrow">Mover etapa</span>
            <div className="dr-stages">
              {PIPELINE_STAGES.map((s, i) => (
                <button key={s.id} className={'dr-stage' + (s.id === deal.stage ? ' on' : '') + (i < idx ? ' past' : '')}
                  onClick={() => onMove(deal.id, s.id)}>
                  <span className="dr-stage-dot" style={{ ['--hue']: s.hue }} />{s.nome}
                </button>
              ))}
            </div>
          </section>
        </div>

        <div className="drawer-foot">
          <Button variant="primary" icon="spark" style={{ flex: 1 }} onClick={() => { onResume(deal); onClose(); }}>Dar sequência</Button>
          <Button variant="danger" icon="trash" onClick={() => { onDelete(deal.id); onClose(); }}>Excluir</Button>
        </div>
      </aside>
    </div>
  );
}

function Pipeline({ deals, onMove, onDelete, onNew, onResume }) {
  const [dragId, setDragId] = React.useState(null);
  const [overCol, setOverCol] = React.useState(null);
  const [open, setOpen] = React.useState(null);
  const [query, setQuery] = React.useState('');

  const filtered = deals.filter(d =>
    !query || (d.cliente.nome + d.cliente.empresa).toLowerCase().includes(query.toLowerCase()));

  const onDragStart = (e, id) => { setDragId(id); e.dataTransfer.effectAllowed = 'move'; };
  const onDrop = (stageId) => { if (dragId) onMove(dragId, stageId); setDragId(null); setOverCol(null); };

  const totalGeral = deals.reduce((s, d) => s + d.total, 0);
  const ganho = deals.filter(d => ['pagamento', 'contrato', 'projeto'].includes(d.stage)).reduce((s, d) => s + d.total, 0);
  const openDeal = open ? deals.find(d => d.id === open) : null;

  return (
    <div className="pipeline">
      <header className="pipe-head">
        <div>
          <div className="row gap-3" style={{ marginBottom: 4 }}>
            <h1 style={{ fontSize: 26 }}>Pipeline comercial</h1>
            <Badge tone="blue">{deals.length} negócios</Badge>
          </div>
          <p style={{ color: 'var(--text-3)', fontSize: 14 }}>
            Em aberto <b className="mono" style={{ color: 'var(--text)' }}>{fmtBRL(totalGeral)}</b>
            <span style={{ margin: '0 8px', color: 'var(--text-dim)' }}>·</span>
            Confirmado <b className="mono" style={{ color: 'var(--success)' }}>{fmtBRL(ganho)}</b>
          </p>
        </div>
        <div className="row gap-3">
          <div className="pipe-search">
            <Icon name="search" size={16} style={{ color: 'var(--text-3)' }} />
            <input placeholder="Buscar cliente…" value={query} onChange={(e) => setQuery(e.target.value)} />
          </div>
          <Button icon="plus" onClick={onNew}>Nova proposta</Button>
        </div>
      </header>

      {deals.length === 0 ? (
        <div className="pipe-empty">
          {window.FAVICON
            ? <img src={window.FAVICON} alt="" style={{ width: 54, height: 54, objectFit: 'contain', margin: '0 auto 16px', display: 'block' }} />
            : <div className="mark" style={{ width: 34, margin: '0 auto 16px' }}><i style={{ height: 20 }}></i><i style={{ height: 20 }}></i></div>}
          <h3 style={{ fontSize: 19 }}>Nenhum negócio ainda</h3>
          <p style={{ color: 'var(--text-3)', maxWidth: 340, margin: '6px auto 18px' }}>
            Crie a primeira proposta. Ao registrar o aceite, o negócio aparece aqui automaticamente.
          </p>
          <Button icon="plus" onClick={onNew}>Criar proposta</Button>
        </div>
      ) : (
      <div className="board">
        {PIPELINE_STAGES.map(stage => {
          const cards = filtered.filter(d => d.stage === stage.id);
          const colTotal = cards.reduce((s, d) => s + d.total, 0);
          return (
            <div key={stage.id}
              className={'column' + (overCol === stage.id ? ' over' : '')}
              onDragOver={(e) => { e.preventDefault(); setOverCol(stage.id); }}
              onDragLeave={(e) => { if (e.currentTarget === e.target) setOverCol(null); }}
              onDrop={() => onDrop(stage.id)}>
              <div className="col-head">
                <span className="col-dot" style={{ ['--hue']: stage.hue }} />
                <span className="col-name">{stage.nome}</span>
                <span className="col-count">{cards.length}</span>
              </div>
              <div className="col-total mono">{fmtBRL(colTotal)}</div>
              <div className="col-body">
                {cards.map(d => (
                  <DealCard key={d.id} deal={d} dragging={dragId === d.id}
                    onDragStart={onDragStart} onOpen={(dd) => setOpen(dd.id)} />
                ))}
                {cards.length === 0 && <div className="col-empty">Solte aqui</div>}
              </div>
            </div>
          );
        })}
      </div>
      )}

      <DealDrawer deal={openDeal} onClose={() => setOpen(null)} onMove={onMove} onDelete={onDelete} onResume={onResume} />
    </div>
  );
}

Object.assign(window, { Pipeline });
