/* ============================================================
   AVANZAMENTO — vista Kanban delle opportunità (pipeline commerciale)
   Colonne = fasi attive (pipeline_stages). Card = opportunità.
   Drag&drop per spostare tra fasi (applica booking_action via app).
   Permessi: RLS filtra già le opportunità (commerciale vede le sue).
   ============================================================ */

function Avanzamento({ role, currentUser, users, stages, opportunities, setOpportunities,
                      bookings, clienti, onChangeStage, onOpenOpportunity, onNewOpportunity, toast }) {
  const vp = useViewport();
  const [dragId, setDragId] = useState(null);
  const [overStage, setOverStage] = useState(null);
  const [filterComm, setFilterComm] = useState('all'); // filtro commerciale (solo admin/backoffice)
  const [mostraStoriche, setMostraStoriche] = useState(false); // mostra anche le concluse da oltre 60 gg
  const [q, setQ] = useState('');                      // ricerca libera
  const [filterTipo, setFilterTipo] = useState('all'); // filtro tipo contratto

  const isManager = role === 'admin' || role === 'backoffice';
  const activeStages = (stages || []).filter(s => s.active).sort((a,b)=>(a.sort_order||0)-(b.sort_order||0));

  // Le opportunità concluse (vinte/consegnate o perse) da più di 60 giorni
  // spariscono dall'avanzamento: restano consultabili in archivio.
  const GIORNI_VISIBILITA = 60;
  const isVecchiaConclusa = (o) => {
    const esito = o.esito || 'aperta';
    if (esito === 'aperta') return false;
    if (!o.chiusa_il) return false;
    const giorni = (Date.now() - new Date(o.chiusa_il).getTime()) / 86400000;
    return giorni > GIORNI_VISIBILITA;
  };
  const nascoste = (opportunities || []).filter(isVecchiaConclusa).length;

  // prenotazioni collegate a un'opportunità (per ricerca su macchina/preventivo)
  const bookingsOf = (o) => (bookings||[]).filter(b => (o.bookingIds||[]).includes(b.id));

  // opportunità visibili (RLS ha già filtrato; qui i filtri UI + regola 60 giorni)
  const term = q.trim().toLowerCase();
  const visibleOpps = (opportunities || []).filter(o => {
    if (!mostraStoriche && isVecchiaConclusa(o)) return false;
    if (isManager && filterComm !== 'all' && o.commerciale_id !== filterComm) return false;
    const bs = bookingsOf(o);
    if (filterTipo !== 'all' && !bs.some(b => b.tipo === filterTipo)) return false;
    if (term) {
      const hay = [
        o.cliente || '',
        o.note || '',
        ...bs.map(b => `${b.prodLabel||''} ${b.matricola||''} ${b.numeroPreventivo||''} ${b.tipo||''}`),
      ].join(' ').toLowerCase();
      if (!hay.includes(term)) return false;
    }
    return true;
  });

  const oppsByStage = (stageId) => visibleOpps.filter(o => o.stage_id === stageId);

  const commName = (id) => {
    const u = (users||[]).find(x => x.id === id);
    return u ? u.nome : '—';
  };

  // drag handlers
  const onDragStart = (id) => (e) => { setDragId(id); e.dataTransfer.effectAllowed = 'move'; };
  const onDragOver = (stageId) => (e) => { e.preventDefault(); if (stageId !== overStage) setOverStage(stageId); };
  const onDrop = (stageId) => (e) => {
    e.preventDefault();
    if (dragId) onChangeStage(dragId, stageId);
    setDragId(null); setOverStage(null);
  };
  const onDragEnd = () => { setDragId(null); setOverStage(null); };

  return (
    <div style={{ flex:1, minWidth:0, display:'flex', flexDirection:'column', overflow:'hidden' }}>
      {/* header */}
      <div style={{ padding: vp.isMobile?'14px 12px':'20px 30px 14px', borderBottom:'1px solid var(--line)', background:'var(--surface)',
        display:'flex', alignItems:'center', justifyContent:'space-between', gap:12, flexWrap:'wrap', flexShrink:0 }}>
        <div style={{ minWidth:0 }}>
          <h1 style={{ margin:0, fontFamily:'var(--font-display)', fontSize: vp.isMobile?18:22, fontWeight:800, letterSpacing:'-.01em' }}>Avanzamento</h1>
          <div style={{ fontSize:12.5, color:'var(--ink-3)', marginTop:2 }}>
            {visibleOpps.length} {visibleOpps.length===1?'opportunità':'opportunità'} · pipeline commerciale
          </div>
        </div>
        <div style={{ display:'flex', alignItems:'center', gap:10, flexWrap:'wrap' }}>
          {/* ricerca libera */}
          <div style={{ position:'relative', flex: vp.isMobile?'1 1 100%':'0 1 260px', minWidth: vp.isMobile?0:200 }}>
            <Icon name="search" size={16} style={{ position:'absolute', left:12, top:'50%', transform:'translateY(-50%)', color:'var(--ink-4)' }} />
            <input value={q} onChange={e=>setQ(e.target.value)} placeholder="Cerca cliente, mezzo, preventivo…"
              style={{ width:'100%', padding:'9px 32px 9px 36px', fontSize:13, borderRadius:'var(--r-md)',
                border:'1.5px solid var(--line)', background:'var(--surface-2)', outline:'none' }} />
            {q && <button onClick={()=>setQ('')} style={{ position:'absolute', right:8, top:'50%', transform:'translateY(-50%)', padding:4, color:'var(--ink-4)' }}><Icon name="x" size={14} /></button>}
          </div>
          {/* filtro tipo contratto */}
          <div style={{ position:'relative' }}>
            <select value={filterTipo} onChange={e=>setFilterTipo(e.target.value)}
              style={{ appearance:'none', padding:'9px 32px 9px 13px', fontSize:13, fontWeight:600, borderRadius:'var(--r-md)',
                border:'1.5px solid '+(filterTipo!=='all'?'var(--red)':'var(--line)'),
                background: filterTipo!=='all'?'var(--red-tint)':'var(--surface-2)', color: filterTipo!=='all'?'var(--red)':'var(--ink-2)', cursor:'pointer' }}>
              <option value="all">Tutti i contratti</option>
              {['Vendita','STR','LTR','Prova','Tampone'].map(t=><option key={t} value={t}>{t==='STR'?'Nol. breve':t==='LTR'?'Nol. lungo':t}</option>)}
            </select>
            <Icon name="chevDown" size={15} style={{ position:'absolute', right:11, top:'50%', transform:'translateY(-50%)', color:'var(--ink-3)', pointerEvents:'none' }} />
          </div>
          {isManager && (
            <div style={{ position:'relative' }}>
              <select value={filterComm} onChange={e=>setFilterComm(e.target.value)}
                style={{ appearance:'none', padding:'9px 32px 9px 13px', fontSize:13, fontWeight:600, borderRadius:'var(--r-md)',
                  border:'1.5px solid var(--line)', background:'var(--surface-2)', color:'var(--ink-2)', cursor:'pointer' }}>
                <option value="all">Tutti i commerciali</option>
                {(users||[]).filter(u=>u.role==='commerciale'||u.ruolo==='commerciale').map(u=>(
                  <option key={u.id} value={u.id}>{u.nome}</option>
                ))}
              </select>
              <Icon name="chevDown" size={15} style={{ position:'absolute', right:11, top:'50%', transform:'translateY(-50%)', color:'var(--ink-3)', pointerEvents:'none' }} />
            </div>
          )}
          {nascoste > 0 && (
            <button onClick={()=>setMostraStoriche(v=>!v)}
              title={mostraStoriche?'Nascondi le concluse da oltre 60 giorni':'Mostra anche le concluse da oltre 60 giorni'}
              style={{ display:'inline-flex', alignItems:'center', gap:6, padding:'9px 13px', fontSize:12.5, fontWeight:700, borderRadius:'var(--r-md)',
                border:'1.5px solid '+(mostraStoriche?'var(--red)':'var(--line)'),
                background: mostraStoriche?'var(--red-tint)':'var(--surface-2)', color: mostraStoriche?'var(--red)':'var(--ink-2)' }}>
              <Icon name={mostraStoriche?'eye':'log'} size={14} />
              {vp.isMobile ? nascoste : `${mostraStoriche?'Nascondi':'Mostra'} storiche (${nascoste})`}
            </button>
          )}
          <Btn icon="plus" size={vp.isMobile?'sm':'md'} onClick={onNewOpportunity}>{vp.isMobile?'Nuova':'Nuova opportunità'}</Btn>
        </div>
      </div>

      {/* board */}
      {activeStages.length === 0 ? (
        <div style={{ padding:'60px 20px', textAlign:'center', color:'var(--ink-3)' }}>
          Nessuna fase attiva. Configura le fasi dalla Console Admin → Fasi pipeline.
        </div>
      ) : (
        <div className="scroll kanban-board" style={{ flex:1, overflowX:'auto', overflowY:'hidden', display:'flex', gap:14,
          padding: vp.isMobile?'14px 12px':'18px 30px', alignItems:'stretch' }}>
          {activeStages.map(stage => {
            const opps = oppsByStage(stage.id);
            const isOver = overStage === stage.id;
            return (
              <div key={stage.id}
                onDragOver={onDragOver(stage.id)} onDrop={onDrop(stage.id)}
                style={{ width: vp.isMobile?260:290, flexShrink:0, display:'flex', flexDirection:'column',
                  background: isOver?'var(--red-tint)':'var(--surface-2)', borderRadius:'var(--r-lg)',
                  border:'1.5px solid '+(isOver?'var(--red)':'var(--line)'), transition:'.12s', maxHeight:'100%' }}>
                {/* header colonna */}
                <div style={{ padding:'12px 14px', borderBottom:'1px solid var(--line)', flexShrink:0 }}>
                  <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:8 }}>
                    <span style={{ fontSize:13.5, fontWeight:800, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{stage.nome}</span>
                    <span style={{ fontSize:11.5, fontWeight:800, color:'var(--ink-3)', background:'var(--surface)', padding:'2px 8px', borderRadius:99, flexShrink:0 }}>{opps.length}</span>
                  </div>
                  {/* barra avanzamento */}
                  <div style={{ marginTop:8, height:4, borderRadius:99, background:'var(--line-2)', overflow:'hidden' }}>
                    <div style={{ width:(stage.percent||0)+'%', height:'100%', background:'var(--red)', borderRadius:99 }} />
                  </div>
                  <div style={{ fontSize:10.5, color:'var(--ink-4)', fontWeight:600, marginTop:3 }}>{stage.percent}% avanzamento</div>
                </div>
                {/* cards */}
                <div className="scroll" style={{ flex:1, overflowY:'auto', padding:'10px', display:'flex', flexDirection:'column', gap:9 }}>
                  {opps.length === 0 ? (
                    <div style={{ padding:'20px 8px', textAlign:'center', color:'var(--ink-4)', fontSize:12, fontWeight:600 }}>
                      Nessuna opportunità
                    </div>
                  ) : opps.map(o => (
                    <OpportunityCard key={o.id} opp={o} bookings={bookings}
                      commName={commName} isManager={isManager}
                      dragging={dragId===o.id}
                      onDragStart={onDragStart(o.id)} onDragEnd={onDragEnd}
                      onClick={()=>onOpenOpportunity(o)} />
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

/* Card singola opportunità nel Kanban */
function OpportunityCard({ opp, bookings, commName, isManager, dragging, onDragStart, onDragEnd, onClick }) {
  const nBookings = (opp.bookingIds || []).length;
  const nDesired = (opp.desiredIds || []).length;
  const titolo = opp.cliente || opp.titolo || 'Opportunità';

  return (
    <div draggable onDragStart={onDragStart} onDragEnd={onDragEnd} onClick={onClick}
      style={{ background:'var(--surface)', border:'1px solid var(--line)', borderRadius:'var(--r-md)',
        padding:'11px 12px', cursor:'grab', boxShadow:'var(--sh-1)', opacity: dragging?0.4:1, transition:'opacity .12s' }}>
      <div style={{ fontSize:13.5, fontWeight:800, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis', marginBottom:4 }}>
        {titolo}
      </div>
      {opp.titolo && opp.cliente && (
        <div style={{ fontSize:11.5, color:'var(--ink-3)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis', marginBottom:6 }}>{opp.titolo}</div>
      )}
      {/* chip: prenotazioni + macchine desiderate */}
      <div style={{ display:'flex', flexWrap:'wrap', gap:6, marginBottom: (opp.note||isManager)?7:0 }}>
        {nBookings > 0 && (
          <span style={{ display:'inline-flex', alignItems:'center', gap:4, fontSize:11, fontWeight:700, color:'var(--ink-2)', background:'var(--surface-2)', padding:'3px 8px', borderRadius:99 }}>
            <Icon name="calendar" size={11} /> {nBookings} {nBookings===1?'prenotaz.':'prenotaz.'}
          </span>
        )}
        {nDesired > 0 && (
          <span style={{ display:'inline-flex', alignItems:'center', gap:4, fontSize:11, fontWeight:700, color:'var(--ink-2)', background:'var(--surface-2)', padding:'3px 8px', borderRadius:99 }}>
            <Icon name="boxes" size={11} /> {nDesired} nuova/e
          </span>
        )}
        {opp.prob != null && (
          <span style={{ fontSize:11, fontWeight:700, color:'var(--red)', background:'var(--red-tint)', padding:'3px 8px', borderRadius:99 }}>
            {opp.prob}%
          </span>
        )}
      </div>
      {/* commerciale (solo per manager) */}
      {isManager && opp.commerciale_id && (
        <div style={{ fontSize:11, color:'var(--ink-4)', fontWeight:600, display:'flex', alignItems:'center', gap:4 }}>
          <Icon name="user" size={11} /> {commName(opp.commerciale_id)}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Avanzamento, OpportunityCard });