// Kanban.jsx — Drag & Drop Sales Funnel
(function () {
  const { useState, useRef } = React;

  function fmtVal(v) {
    if (v >= 1000000) return (v/1000000).toFixed(1).replace('.',',') + ' M zł';
    if (v >= 1000) return Math.round(v/1000) + ' k zł';
    return v + ' zł';
  }

  const sourceColors = {
    'Google':    '#7C5CFF',
    'Polecenia': '#4DA3FF',
    'Social':    '#00D9FF',
    'Formularz': '#22C55E',
  };
  const sourceLabels = { 'Google':'Google Ads', 'Polecenia':'Polecenia', 'Social':'Meta Ads', 'Formularz':'Formularz' };

  // ── Lead Detail Drawer ───────────────────────────────────────────
  function LeadDrawer({ lead, columns, onClose, onMove, onAddNote }) {
    const [noteText, setNoteText] = React.useState('');
    if (!lead) return null;
    const col = columns.find(c => c.id === lead.column);
    return (
      <>
        <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.45)', zIndex:40, backdropFilter:'blur(3px)' }} />
        <div style={{
          position:'fixed', top:0, right:0, bottom:0, width:400,
          background:'var(--bg-sidebar)', borderLeft:'1px solid var(--bdr)',
          backdropFilter:'blur(32px)', WebkitBackdropFilter:'blur(32px)',
          zIndex:50, display:'flex', flexDirection:'column',
          boxShadow:'-20px 0 60px rgba(0,0,0,0.4)',
        }}>
          <div style={{ padding:'20px 24px 16px', borderBottom:'1px solid var(--bdr)', display:'flex', alignItems:'center', gap:14 }}>
            <div style={{ width:44, height:44, borderRadius:12, background:lead.avatarColor, display:'flex', alignItems:'center', justifyContent:'center', fontSize:14, fontWeight:700, color:'#fff', flexShrink:0 }}>{lead.initials}</div>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:15, fontWeight:700, color:'var(--t1)' }}>{lead.company}</div>
              <div style={{ fontSize:12, color:'var(--t3)', marginTop:1 }}>{lead.person}</div>
            </div>
            <button onClick={onClose} style={{ width:30, height:30, borderRadius:8, border:'1px solid var(--bdr)', background:'var(--bg1)', color:'var(--t2)', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', fontSize:16, outline:'none' }}>✕</button>
          </div>
          <div style={{ flex:1, overflowY:'auto', padding:'20px 24px', display:'flex', flexDirection:'column', gap:18 }}>
            <div style={{ display:'flex', gap:8 }}>
              <span style={{ padding:'3px 10px', borderRadius:99, background:(col?.color||'#7C5CFF')+'22', color:col?.color||'#7C5CFF', fontSize:12, fontWeight:600 }}>{col?.label}</span>
              <span style={{ padding:'3px 10px', borderRadius:99, background:'var(--bg1)', border:'1px solid var(--bdr)', fontSize:12, color:'var(--t2)' }}>{sourceLabels[lead.source] || lead.source}</span>
            </div>
            <div className="glass-card" style={{ padding:16 }}>
              <div style={{ fontSize:12, fontWeight:600, color:'var(--t3)', marginBottom:12, textTransform:'uppercase', letterSpacing:0.8 }}>Szczegóły leada</div>
              {[
                { icon:'◈', label:`Wartość: ${fmtVal(lead.value)}` },
                { icon:'✉', label:`Osoba kontaktowa: ${lead.person}` },
                { icon:'●', label:`Źródło: ${sourceLabels[lead.source] || lead.source}` },
              ].map((r,i) => (
                <div key={i} style={{ display:'flex', gap:10, alignItems:'center', padding:'6px 0', borderBottom: i<2 ? '1px solid var(--bdr)' : 'none' }}>
                  <span style={{ fontSize:14, color:'var(--t3)', width:20, textAlign:'center' }}>{r.icon}</span>
                  <span style={{ fontSize:13, color:'var(--t1)' }}>{r.label}</span>
                </div>
              ))}
            </div>
            <div>
              <div style={{ fontSize:12, fontWeight:600, color:'var(--t3)', marginBottom:10, textTransform:'uppercase', letterSpacing:0.8 }}>Przenieś do etapu</div>
              <div style={{ display:'flex', flexWrap:'wrap', gap:8 }}>
                {columns.map(c => (
                  <button key={c.id} onClick={()=>onMove(lead.id, c.id)} disabled={c.id===lead.column} style={{
                    padding:'7px 12px', borderRadius:9, fontSize:12, fontWeight:600, cursor: c.id===lead.column?'default':'pointer',
                    border: c.id===lead.column ? `1.5px solid ${c.color}` : '1px solid var(--bdr)',
                    background: c.id===lead.column ? c.color+'22' : 'var(--bg1)',
                    color: c.id===lead.column ? c.color : 'var(--t2)',
                  }}>{c.label}</button>
                ))}
              </div>
            </div>
            <div className="glass-card" style={{ padding:16 }}>
              <div style={{ fontSize:12, fontWeight:600, color:'var(--t3)', marginBottom:8, textTransform:'uppercase', letterSpacing:0.8 }}>Notatki</div>
              {lead.notes && <p style={{ fontSize:13, color:'var(--t1)', lineHeight:1.6, margin:'0 0 10px', whiteSpace:'pre-wrap' }}>{lead.notes}</p>}
              <div style={{ display:'flex', gap:8 }}>
                <input value={noteText} onChange={e=>setNoteText(e.target.value)} placeholder="Dopisz notatkę…"
                  style={{ flex:1, padding:'8px 10px', borderRadius:8, border:'1px solid var(--bdr)', background:'var(--bg-input)', color:'var(--t1)', fontSize:12.5, outline:'none' }}
                  onKeyDown={e => { if (e.key==='Enter' && noteText.trim()) { onAddNote(lead.id, noteText.trim()); setNoteText(''); } }}
                />
                <button onClick={() => { if (noteText.trim()) { onAddNote(lead.id, noteText.trim()); setNoteText(''); } }} style={{ padding:'8px 14px', borderRadius:8, border:'none', background:'linear-gradient(135deg,#7C5CFF,#4DA3FF)', color:'#fff', fontWeight:600, fontSize:12.5, cursor:'pointer' }}>Dodaj</button>
              </div>
            </div>
          </div>
          <div style={{ padding:'16px 24px', borderTop:'1px solid var(--bdr)', display:'flex', gap:8 }}>
            <button style={{ flex:1, padding:'9px 0', borderRadius:10, border:'none', background:'linear-gradient(135deg,#7C5CFF,#4DA3FF)', color:'#fff', fontWeight:600, fontSize:13, cursor:'pointer' }}>✉ Wyślij email</button>
            <button style={{ flex:1, padding:'9px 0', borderRadius:10, border:'1px solid var(--bdr)', background:'var(--bg1)', color:'var(--t1)', fontWeight:600, fontSize:13, cursor:'pointer' }}>☎ Zadzwoń</button>
          </div>
        </div>
      </>
    );
  }

  // ── Kanban Card ───────────────────────────────────────────────────
  function KanbanCard({ lead, onDragStart, onOpen }) {
    const [hov, setHov] = useState(false);
    const dragStarted = useRef(false);
    return (
      <div
        draggable
        onDragStart={() => { dragStarted.current = true; onDragStart(lead.id); }}
        onClick={() => { if (!dragStarted.current) onOpen(lead); dragStarted.current = false; }}
        onMouseEnter={() => setHov(true)}
        onMouseLeave={() => setHov(false)}
        style={{
          background: hov ? 'var(--bg2)' : 'var(--bg1)',
          border: '1px solid var(--bdr)',
          borderRadius: 12, padding: '12px 14px', cursor: 'pointer',
          transition: 'all .18s ease',
          transform: hov ? 'translateY(-2px)' : 'none',
          boxShadow: hov ? '0 8px 24px rgba(0,0,0,0.3)' : '0 2px 8px rgba(0,0,0,0.15)',
          userSelect: 'none',
        }}
      >
        {/* Header: avatar + company */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
          <div style={{
            width: 32, height: 32, borderRadius: 8, flexShrink: 0,
            background: lead.avatarColor, opacity: 0.9,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 11, fontWeight: 700, color: '#fff', letterSpacing: 0.5,
          }}>{lead.initials}</div>
          <div style={{ overflow: 'hidden' }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--t1)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 150 }}>{lead.company}</div>
            <div style={{ fontSize: 11, color: 'var(--t3)' }}>{lead.person}</div>
          </div>
        </div>
        {/* Value + source */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 4 }}>
          <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--t1)' }}>{fmtVal(lead.value)}</span>
          <span style={{
            fontSize: 10, fontWeight: 600, padding: '2px 8px', borderRadius: 99,
            background: (sourceColors[lead.source] || '#7C5CFF') + '22',
            color: sourceColors[lead.source] || '#7C5CFF',
            border: `1px solid ${(sourceColors[lead.source] || '#7C5CFF')}44`,
          }}>{sourceLabels[lead.source] || lead.source}</span>
        </div>
      </div>
    );
  }

  // ── Kanban Column ─────────────────────────────────────────────────
  function KanbanColumn({ col, leads, onDragStart, onDrop, onOpen }) {
    const [dragOver, setDragOver] = useState(false);
    const total = leads.reduce((s, l) => s + l.value, 0);

    return (
      <div
        onDragOver={e => { e.preventDefault(); setDragOver(true); }}
        onDragLeave={() => setDragOver(false)}
        onDrop={() => { setDragOver(false); onDrop(col.id); }}
        style={{
          minWidth: 220, maxWidth: 240, flex: '1 1 220px',
          display: 'flex', flexDirection: 'column', gap: 0,
          background: dragOver ? 'rgba(124,92,255,0.06)' : 'transparent',
          border: dragOver ? '1.5px dashed rgba(124,92,255,0.4)' : '1.5px dashed transparent',
          borderRadius: 16, transition: 'all .18s ease',
        }}
      >
        {/* Column header */}
        <div style={{ padding: '12px 14px 10px', borderRadius: '14px 14px 0 0' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
            <div style={{ width: 8, height: 8, borderRadius: '50%', background: col.color, boxShadow: `0 0 8px ${col.color}99`, flexShrink: 0 }} />
            <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--t1)' }}>{col.label}</span>
            <span style={{
              marginLeft: 'auto', fontSize: 11, fontWeight: 600, padding: '1px 7px',
              background: col.color + '22', color: col.color, borderRadius: 99,
            }}>{leads.length}</span>
          </div>
          {leads.length > 0 && (
            <div style={{ fontSize: 12, color: 'var(--t3)' }}>{fmtVal(total)}</div>
          )}
        </div>

        {/* Cards */}
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 8, padding: '0 10px 10px' }}>
          {leads.map(lead => (
            <KanbanCard key={lead.id} lead={lead} onDragStart={onDragStart} onOpen={onOpen} />
          ))}
          {leads.length === 0 && (
            <div style={{
              border: '1.5px dashed var(--bdr)', borderRadius: 12, padding: '20px 0',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: 'var(--t3)', fontSize: 12, minHeight: 80,
            }}>Upuść tutaj</div>
          )}
        </div>
      </div>
    );
  }

  // ── Kanban (main export) ──────────────────────────────────────────
  window.Kanban = function Kanban({ leads, setLeads }) {
    const dragId = useRef(null);
    const S = window.SEED;
    const [openLead, setOpenLead] = useState(null);

    const handleDragStart = (id) => { dragId.current = id; };
    const handleDrop = (colId) => {
      if (!dragId.current) return;
      setLeads(prev => prev.map(l => l.id === dragId.current ? { ...l, column: colId } : l));
      dragId.current = null;
    };
    const moveLead = (id, colId) => {
      setLeads(prev => prev.map(l => l.id === id ? { ...l, column: colId } : l));
      setOpenLead(prev => prev && prev.id === id ? { ...prev, column: colId } : prev);
    };
    const addLeadNote = (id, text) => {
      setLeads(prev => prev.map(l => l.id === id ? { ...l, notes: l.notes ? l.notes + '\n' + text : text } : l));
      setOpenLead(prev => prev && prev.id === id ? { ...prev, notes: prev.notes ? prev.notes + '\n' + text : text } : prev);
    };

    const totalWon = leads.filter(l => l.column === 'won').reduce((s, l) => s + l.value, 0);
    const totalPipeline = leads.filter(l => !['won','lost'].includes(l.column)).reduce((s, l) => s + l.value, 0);

    return (
      <div>
        {/* Stats bar */}
        <div style={{ display: 'flex', gap: 12, marginBottom: 20 }}>
          {[
            { label: 'W toku', val: fmtVal(totalPipeline), color: '#7C5CFF' },
            { label: 'Wygranych', val: fmtVal(totalWon), color: '#22C55E' },
            { label: 'Łącznie leadów', val: leads.length, color: '#4DA3FF' },
          ].map(s => (
            <div key={s.label} className="glass-card" style={{ padding: '12px 20px', display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ width: 6, height: 28, borderRadius: 3, background: s.color }} />
              <div>
                <div style={{ fontSize: 11, color: 'var(--t3)' }}>{s.label}</div>
                <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--t1)' }}>{s.val}</div>
              </div>
            </div>
          ))}
        </div>

        {/* Board */}
        <div style={{ overflowX: 'auto', paddingBottom: 12 }}>
          <div style={{ display: 'flex', gap: 12, minWidth: 'max-content' }}>
            {S.kanbanColumns.map(col => (
              <KanbanColumn
                key={col.id}
                col={col}
                leads={leads.filter(l => l.column === col.id)}
                onDragStart={handleDragStart}
                onDrop={handleDrop}
                onOpen={setOpenLead}
              />
            ))}
          </div>
        </div>
        {openLead && <LeadDrawer lead={openLead} columns={S.kanbanColumns} onClose={()=>setOpenLead(null)} onMove={moveLead} onAddNote={addLeadNote} />}
      </div>
    );
  };
})();
