/* ============================================================
   ZERO — Sales Pipeline. window.Screens.Sales
   ============================================================ */
(function () {
  const { useState } = React;
  const I = window.Icon;
  const { Badge } = window.UI;
  const D = window.DATA;

  const STAGES = ['Lead', 'Discovery', 'Proposal', 'Negotiation', 'Closed Won'];
  const ST_HUE = { Lead: 'var(--tx-2)', Discovery: 'var(--teal)', Proposal: 'var(--violet-2)', Negotiation: 'var(--amber)', 'Closed Won': 'var(--green)' };
  const ST_LABEL = { Lead: 'Lead', Discovery: 'Descoberta', Proposal: 'Proposta', Negotiation: 'Negociação', 'Closed Won': 'Ganho' };
  const money = n => 'R$ ' + (n/1000).toFixed(0) + ' mil';

  function DealCard({ d, onDragStart }) {
    const scoreColor = d.score >= 80 ? 'var(--green)' : d.score >= 60 ? 'var(--teal)' : d.score >= 45 ? 'var(--amber)' : 'var(--tx-2)';
    return (
      <div draggable onDragStart={onDragStart} className="lift"
        style={{ padding: 13, borderRadius: 12, background: 'var(--bg-2)', border: '1px solid var(--line)', cursor: 'grab' }}>
        <div className="row between" style={{ marginBottom: 9 }}>
          <div className="row gap8">
            <span className="avatar" style={{ width: 30, height: 30, background: d.hue }}>{d.co[0]}</span>
            <div><div style={{ fontSize: 13, fontWeight: 700, lineHeight: 1.1 }}>{d.co}</div>
              <div style={{ fontSize: 10.5, color: 'var(--tx-2)' }}>{d.person}</div></div>
          </div>
          <button className="btn btn-icon btn-sm" style={{ padding: 3, border: 'none', background: 'transparent' }}><I.dots w={15} /></button>
        </div>
        <div className="row between" style={{ marginBottom: 10 }}>
          <span className="tnum" style={{ fontSize: 17, fontWeight: 800, letterSpacing: '-0.03em' }}>{money(d.value)}</span>
          <Badge soft={`color-mix(in oklab, ${d.hue}, transparent 86%)`} color={d.hue}>
            {d.tag === 'Quente' && <I.flame w={11} />}{d.tag}
          </Badge>
        </div>
        <div className="row gap8">
          <div className="track grow"><i style={{ width: d.score + '%', background: scoreColor }} /></div>
          <span className="mono" style={{ fontSize: 10, color: scoreColor, fontWeight: 600 }}>{d.score}</span>
        </div>
      </div>
    );
  }

  function Sales() {
    const [board, setBoard] = useState(() => JSON.parse(JSON.stringify(D.pipeline)));
    const [drag, setDrag] = useState(null);
    const [over, setOver] = useState(null);

    function onDrop(stage) {
      if (!drag || drag.stage === stage) { setDrag(null); setOver(null); return; }
      setBoard(prev => {
        const next = { ...prev };
        const card = next[drag.stage].find(c => c.id === drag.id);
        if (stage === 'Closed Won') card.score = 100;
        next[drag.stage] = next[drag.stage].filter(c => c.id !== drag.id);
        next[stage] = [card, ...next[stage]];
        return next;
      });
      setDrag(null); setOver(null);
    }

    const stageTotal = s => board[s].reduce((a, c) => a + c.value, 0);
    const pipelineTotal = STAGES.reduce((a, s) => a + stageTotal(s), 0);
    const won = stageTotal('Closed Won');

    return (
      <div className="page" style={{ maxWidth: 1600 }}>
        <div className="row between wrap gap12" style={{ marginBottom: 18 }}>
          <div className="row gap16 wrap">
            <Stat label="Valor do pipeline" value={money(pipelineTotal)} hue="var(--violet-2)" />
            <Stat label="Fechados (ganho)" value={money(won)} hue="var(--green)" />
            <Stat label="Taxa de ganho" value="34%" hue="var(--teal)" />
            <Stat label="Ticket médio" value="R$ 18 mil" hue="var(--amber)" />
            <Stat label="Atividade da Vega" value="12 follow-ups" hue="var(--rose)" />
          </div>
          <div className="row gap8">
            <button className="btn"><I.filter w={15} /> Filtrar</button>
            <button className="btn btn-primary"><I.plus w={15} /> Novo negócio</button>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5,1fr)', gap: 14, alignItems: 'start' }}>
          {STAGES.map(stage => (
            <div key={stage}
              onDragOver={e => { e.preventDefault(); setOver(stage); }}
              onDragLeave={() => setOver(o => o === stage ? null : o)}
              onDrop={() => onDrop(stage)}
              style={{ borderRadius: 14, padding: 10, minHeight: 220,
                background: over === stage ? 'color-mix(in oklab,'+ST_HUE[stage]+', transparent 90%)' : 'oklch(0.165 0.013 265 /.5)',
                border: '1px solid ' + (over === stage ? 'color-mix(in oklab,'+ST_HUE[stage]+', transparent 55%)' : 'var(--line)'),
                transition: 'all .15s ease' }}>
              <div style={{ padding: '4px 6px 12px' }}>
                <div className="row between" style={{ marginBottom: 6 }}>
                  <div className="row gap8">
                    <span style={{ width: 8, height: 8, borderRadius: 3, background: ST_HUE[stage] }} />
                    <span style={{ fontSize: 12.5, fontWeight: 700 }}>{ST_LABEL[stage]}</span>
                  </div>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--tx-3)' }}>{board[stage].length}</span>
                </div>
                <span className="mono tnum" style={{ fontSize: 11.5, color: 'var(--tx-2)', paddingLeft: 16 }}>{money(stageTotal(stage))}</span>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {board[stage].map(d => <DealCard key={d.id} d={d} onDragStart={() => setDrag({ stage, id: d.id })} />)}
                {board[stage].length === 0 && <div className="placeholder-img" style={{ height: 64, fontSize: 10.5 }}>solte aqui</div>}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  function Stat({ label, value, hue }) {
    return (
      <div className="panel" style={{ padding: '10px 16px', minWidth: 120 }}>
        <div style={{ fontSize: 11, color: 'var(--tx-2)' }}>{label}</div>
        <div className="row gap6" style={{ alignItems: 'baseline' }}>
          <span style={{ width: 7, height: 7, borderRadius: 2, background: hue }} />
          <span className="tnum" style={{ fontSize: 19, fontWeight: 800, letterSpacing: '-0.03em' }}>{value}</span>
        </div>
      </div>
    );
  }

  window.Screens = window.Screens || {};
  window.Screens.Sales = Sales;
})();
