// Clients.jsx — Table + Side Drawer
(function () {
  const { useState, useEffect } = React;

  const statusStyle = {
    'Aktywny':     { bg: 'rgba(34,197,94,.15)',   color: '#22C55E', dot: '#22C55E' },
    'W toku':      { bg: 'rgba(245,158,11,.15)',   color: '#F59E0B', dot: '#F59E0B' },
    'Nieaktywny':  { bg: 'rgba(100,116,139,.15)',  color: '#94A3B8', dot: '#94A3B8' },
  };

  const timelineIcon = {
    deal:    { bg: '#22C55E', sym: '✓' },
    call:    { bg: '#4DA3FF', sym: '☎' },
    email:   { bg: '#7C5CFF', sym: '✉' },
    meeting: { bg: '#F59E0B', sym: '⊙' },
  };

  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 sourceLabel = s => s === 'Social' ? 'Meta Ads' : s === 'Google' ? 'Google Ads' : s;

  // ── Status pill ───────────────────────────────────────────────────
  function StatusPill({ status }) {
    const s = statusStyle[status] || statusStyle['W toku'];
    return (
      <span style={{ display:'inline-flex', alignItems:'center', gap:5, padding:'3px 10px', borderRadius:99, background:s.bg, fontSize:12, fontWeight:600, color:s.color }}>
        <span style={{ width:6, height:6, borderRadius:'50%', background:s.dot, display:'inline-block' }} />
        {status}
      </span>
    );
  }

  // ── Client Drawer ─────────────────────────────────────────────────
  function ClientDrawer({ client, onClose, onAddNote }) {
    const [noteText, setNoteText] = useState('');
    useEffect(() => {
      const esc = (e) => { if (e.key === 'Escape') onClose(); };
      document.addEventListener('keydown', esc);
      return () => document.removeEventListener('keydown', esc);
    }, []);

    return (
      <>
        {/* Backdrop */}
        <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.45)', zIndex:40, backdropFilter:'blur(3px)' }} />
        {/* Drawer */}
        <div style={{
          position:'fixed', top:0, right:0, bottom:0, width:420,
          background:'var(--bg-sidebar)', borderLeft:'1px solid var(--bdr)',
          backdropFilter:'blur(32px)', WebkitBackdropFilter:'blur(32px)',
          zIndex:50, display:'flex', flexDirection:'column',
          animation:'slideInRight .25s cubic-bezier(.4,0,.2,1)',
          boxShadow:'-20px 0 60px rgba(0,0,0,0.4)',
        }}>
          {/* Drawer header */}
          <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:client.avatarColor, display:'flex', alignItems:'center', justifyContent:'center', fontSize:14, fontWeight:700, color:'#fff', flexShrink:0 }}>{client.initials}</div>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:15, fontWeight:700, color:'var(--t1)' }}>{client.company}</div>
              <div style={{ fontSize:12, color:'var(--t3)', marginTop:1 }}>{client.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:20 }}>
            {/* Status + source */}
            <div style={{ display:'flex', gap:8 }}>
              <StatusPill status={client.status} />
              <span style={{ padding:'3px 10px', borderRadius:99, background:'var(--bg1)', border:'1px solid var(--bdr)', fontSize:12, color:'var(--t2)' }}>{sourceLabel(client.source)}</span>
            </div>

            {/* Contact info */}
            <div className="glass-card" style={{ padding:16 }}>
              <div style={{ fontSize:12, fontWeight:600, color:'var(--t3)', marginBottom:12, textTransform:'uppercase', letterSpacing:0.8 }}>Dane kontaktowe</div>
              {[
                { icon:'✉', label: client.email },
                { icon:'☎', label: client.phone },
                { icon:'⊙', label: `Ostatni kontakt: ${client.lastContact}` },
                { icon:'◈', label: `${client.deals} ${client.deals === 1 ? 'oferta' : client.deals < 5 ? 'oferty' : 'ofert'} · ${fmtVal(client.value)}` },
              ].map((r,i) => (
                <div key={i} style={{ display:'flex', gap:10, alignItems:'center', padding:'6px 0', borderBottom: i<3 ? '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>

            {/* Notes */}
            <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>
              {client.notes && <p style={{ fontSize:13, color:'var(--t1)', lineHeight:1.6, margin:'0 0 10px' }}>{client.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(client.id, noteText.trim()); setNoteText(''); } }}
                />
                <button onClick={() => { if (noteText.trim()) { onAddNote(client.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>

            {/* Timeline */}
            <div>
              <div style={{ fontSize:12, fontWeight:600, color:'var(--t3)', marginBottom:12, textTransform:'uppercase', letterSpacing:0.8 }}>Historia kontaktów</div>
              <div style={{ display:'flex', flexDirection:'column', gap:0 }}>
                {(client.timeline || []).map((ev, i) => {
                  const ti = timelineIcon[ev.type] || timelineIcon.meeting;
                  return (
                    <div key={i} style={{ display:'flex', gap:12, paddingBottom: i < client.timeline.length-1 ? 16 : 0 }}>
                      <div style={{ display:'flex', flexDirection:'column', alignItems:'center', flexShrink:0 }}>
                        <div style={{ width:26, height:26, borderRadius:8, background:ti.bg+'22', border:`1px solid ${ti.bg}44`, display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, color:ti.bg }}>{ti.sym}</div>
                        {i < client.timeline.length-1 && <div style={{ width:1, flex:1, background:'var(--bdr)', marginTop:4, minHeight:12 }} />}
                      </div>
                      <div style={{ paddingBottom: i < client.timeline.length-1 ? 8 : 0 }}>
                        <div style={{ fontSize:13, color:'var(--t1)' }}>{ev.action}</div>
                        <div style={{ fontSize:11, color:'var(--t3)', marginTop:2 }}>{ev.date}</div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>

          {/* Actions */}
          <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>
        <style>{`@keyframes slideInRight { from { transform: translateX(100%); opacity:0; } to { transform: translateX(0); opacity:1; } }`}</style>
      </>
    );
  }

  // ── Add Client Modal ──────────────────────────────────────────────
  function AddClientModal({ onClose, onSave }) {
    const [form, setForm] = useState({ company:'', person:'', email:'', phone:'', status:'W toku', source:'Google', value:'' });
    const set = (k,v) => setForm(f => ({ ...f, [k]:v }));
    const canSave = form.company.trim().length > 0 && form.person.trim().length > 0;

    const submit = () => {
      if (!canSave) return;
      const initials = form.company.trim().slice(0,2).toUpperCase();
      const colors = ['#7C5CFF','#4DA3FF','#00D9FF','#22C55E','#F59E0B'];
      const today = new Date();
      const dateStr = `${String(today.getDate()).padStart(2,'0')}.${String(today.getMonth()+1).padStart(2,'0')}.${today.getFullYear()}`;
      onSave({
        id:'C'+Math.random().toString(36).slice(2,8).toUpperCase(),
        company:form.company.trim(), person:form.person.trim(),
        email:form.email.trim() || '—', phone:form.phone.trim() || '—',
        status:form.status, source:form.source, value:Number(form.value)||0,
        lastContact:dateStr, deals:0, initials, avatarColor: colors[Math.floor(Math.random()*colors.length)],
        timeline:[{ date:dateStr, action:'Klient dodany do systemu', type:'meeting' }], notes:'',
      });
      onClose();
    };

    const inputStyle = { width:'100%', padding:'9px 12px', borderRadius:9, border:'1px solid var(--bdr)', background:'var(--bg-input)', color:'var(--t1)', fontSize:13, outline:'none' };
    const labelStyle = { fontSize:11, fontWeight:600, color:'var(--t3)', marginBottom:5, display:'block', textTransform:'uppercase', letterSpacing:0.5 };

    return (
      <>
        <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.5)', zIndex:60, backdropFilter:'blur(3px)' }} />
        <div style={{ position:'fixed', top:'50%', left:'50%', transform:'translate(-50%,-50%)', width:460, maxWidth:'92vw', maxHeight:'86vh', overflowY:'auto', background:'var(--bg-sidebar)', border:'1px solid var(--bdr)', borderRadius:18, zIndex:61, padding:24, boxShadow:'0 30px 80px rgba(0,0,0,.5)', backdropFilter:'blur(32px)' }}>
          <div style={{ fontSize:16, fontWeight:700, color:'var(--t1)', marginBottom:18 }}>Nowy klient</div>
          <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
            <div><label style={labelStyle}>Firma *</label><input style={inputStyle} value={form.company} onChange={e=>set('company',e.target.value)} placeholder="np. Techlab Solutions Sp. z o.o." autoFocus /></div>
            <div><label style={labelStyle}>Osoba kontaktowa *</label><input style={inputStyle} value={form.person} onChange={e=>set('person',e.target.value)} placeholder="np. Jan Kowalski" /></div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
              <div><label style={labelStyle}>Email</label><input style={inputStyle} value={form.email} onChange={e=>set('email',e.target.value)} placeholder="jan@firma.pl" /></div>
              <div><label style={labelStyle}>Telefon</label><input style={inputStyle} value={form.phone} onChange={e=>set('phone',e.target.value)} placeholder="+48 500 000 000" /></div>
            </div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
              <div>
                <label style={labelStyle}>Status</label>
                <window.DemoSelect value={form.status} onChange={v=>set('status',v)} options={['Aktywny','W toku','Nieaktywny']} />
              </div>
              <div>
                <label style={labelStyle}>Źródło</label>
                <window.DemoSelect value={form.source} onChange={v=>set('source',v)} options={[{value:'Google',label:'Google Ads'},{value:'Polecenia',label:'Polecenia'},{value:'Social',label:'Meta Ads'},{value:'Formularz',label:'Formularz'}]} />
              </div>
            </div>
            <div><label style={labelStyle}>Wartość (zł)</label><input type="number" style={inputStyle} value={form.value} onChange={e=>set('value',e.target.value)} placeholder="0" /></div>
          </div>
          <div style={{ display:'flex', gap:8, marginTop:22 }}>
            <button onClick={onClose} style={{ flex:1, padding:'10px 0', borderRadius:10, border:'1px solid var(--bdr)', background:'var(--bg1)', color:'var(--t1)', fontWeight:600, fontSize:13, cursor:'pointer' }}>Anuluj</button>
            <button onClick={submit} disabled={!canSave} style={{ flex:1, padding:'10px 0', borderRadius:10, border:'none', background: canSave ? 'linear-gradient(135deg,#7C5CFF,#4DA3FF)' : 'var(--bg2)', color: canSave ? '#fff' : 'var(--t3)', fontWeight:600, fontSize:13, cursor: canSave ? 'pointer' : 'not-allowed' }}>Dodaj klienta</button>
          </div>
        </div>
      </>
    );
  }

  // ── CSV Import ────────────────────────────────────────────────────
  function parseCSV(text) {
    const lines = text.split(/\r?\n/).filter(l => l.trim().length);
    if (lines.length < 2) return [];
    const sep = lines[0].includes(';') ? ';' : ',';
    const headers = lines[0].split(sep).map(h => h.trim().toLowerCase());
    const idx = (names) => headers.findIndex(h => names.some(n => h.includes(n)));
    const iCompany = idx(['firma','company','nazwa']);
    const iPerson  = idx(['osoba','kontakt','person','imię']);
    const iEmail   = idx(['email','e-mail']);
    const iPhone   = idx(['telefon','phone']);
    const iValue   = idx(['wartość','wartosc','value']);
    const colors = ['#7C5CFF','#4DA3FF','#00D9FF','#22C55E','#F59E0B'];
    return lines.slice(1).map(line => {
      const cells = line.split(sep).map(c => c.trim());
      const company = iCompany>=0 ? cells[iCompany] : cells[0] || 'Bez nazwy';
      const person  = iPerson>=0 ? cells[iPerson] : cells[1] || '—';
      return {
        id:'C'+Math.random().toString(36).slice(2,8).toUpperCase(),
        company, person,
        email: iEmail>=0 ? cells[iEmail] : '—',
        phone: iPhone>=0 ? cells[iPhone] : '—',
        status:'W toku', source:'Formularz', value: iValue>=0 ? Number(cells[iValue].replace(/\D/g,''))||0 : 0,
        lastContact:'—', deals:0, initials: company.slice(0,2).toUpperCase(),
        avatarColor: colors[Math.floor(Math.random()*colors.length)],
        timeline:[{ date:'importowano', action:'Zaimportowany z pliku CSV/Excel', type:'meeting' }], notes:'',
      };
    });
  }

  // ── Clients (main export) ─────────────────────────────────────────
  window.Clients = function Clients() {
    const [clients, setClients] = useState(window.SEED.clients);
    const [search, setSearch] = useState('');
    const [filterStatus, setFilterStatus] = useState('Wszyscy');
    const [selected, setSelected] = useState(null);
    const [showAdd, setShowAdd] = useState(false);
    const [importMsg, setImportMsg] = useState('');
    const fileRef = React.useRef(null);

    const handleImport = (e) => {
      const file = e.target.files[0];
      if (!file) return;
      const reader = new FileReader();
      reader.onload = (ev) => {
        const rows = parseCSV(String(ev.target.result));
        if (rows.length === 0) { setImportMsg('Nie znaleziono danych w pliku'); }
        else { setClients(prev => [...rows, ...prev]); setImportMsg(`Zaimportowano ${rows.length} klientów`); }
        setTimeout(() => setImportMsg(''), 4000);
      };
      reader.readAsText(file);
      e.target.value = '';
    };

    const statuses = ['Wszyscy', 'Aktywny', 'W toku', 'Nieaktywny'];
    const filtered = clients.filter(c => {
      const matchSearch = c.company.toLowerCase().includes(search.toLowerCase()) || c.person.toLowerCase().includes(search.toLowerCase());
      const matchStatus = filterStatus === 'Wszyscy' || c.status === filterStatus;
      return matchSearch && matchStatus;
    });

    return (
      <div>
        {/* Toolbar */}
        <div style={{ display:'flex', gap:12, marginBottom:20, alignItems:'center', flexWrap:'wrap' }}>
          <div style={{ position:'relative', flex:'1', maxWidth:340 }}>
            <span style={{ position:'absolute', left:10, top:'50%', transform:'translateY(-50%)', fontSize:14, color:'var(--t3)' }}>🔍</span>
            <input value={search} onChange={e=>setSearch(e.target.value)}
              placeholder="Szukaj klientów…"
              style={{ width:'100%', padding:'9px 12px 9px 34px', borderRadius:10, border:'1px solid var(--bdr)', background:'var(--bg-input)', color:'var(--t1)', fontSize:13, outline:'none' }}
              onFocus={e=>e.target.style.borderColor='rgba(124,92,255,.5)'}
              onBlur={e=>e.target.style.borderColor='var(--bdr)'}
            />
          </div>
          <div style={{ display:'flex', gap:6 }}>
            {statuses.map(s => (
              <button key={s} onClick={()=>setFilterStatus(s)} style={{
                padding:'7px 14px', borderRadius:9, border:'1px solid var(--bdr)',
                background: filterStatus===s ? 'rgba(124,92,255,.2)' : 'var(--bg1)',
                color: filterStatus===s ? '#7C5CFF' : 'var(--t2)',
                fontWeight: filterStatus===s ? 600 : 400, fontSize:12,
                cursor:'pointer', outline:'none', transition:'all .15s',
                boxShadow: filterStatus===s ? 'inset 0 0 0 1px rgba(124,92,255,.4)' : 'none',
              }}>{s}</button>
            ))}
          </div>
          <div style={{ flex:1 }} />
          <input ref={fileRef} type="file" accept=".csv,.txt" onChange={handleImport} style={{ display:'none' }} />
          <button onClick={()=>fileRef.current?.click()} style={{ padding:'9px 16px', borderRadius:10, border:'1px solid var(--bdr)', background:'var(--bg1)', color:'var(--t1)', fontWeight:600, fontSize:13, cursor:'pointer' }}>⬆ Importuj CSV/Excel</button>
          <button onClick={()=>setShowAdd(true)} style={{ padding:'9px 18px', borderRadius:10, border:'none', background:'linear-gradient(135deg,#7C5CFF,#4DA3FF)', color:'#fff', fontWeight:600, fontSize:13, cursor:'pointer' }}>+ Nowy klient</button>
        </div>
        {importMsg && <div style={{ marginBottom:14, padding:'8px 14px', borderRadius:10, background:'rgba(34,197,94,.12)', color:'#22C55E', fontSize:12, fontWeight:600 }}>✓ {importMsg}</div>}

        {/* Table */}
        <div className="glass-card" style={{ overflow:'hidden' }}>
          <table style={{ width:'100%', borderCollapse:'collapse' }}>
            <thead>
              <tr style={{ borderBottom:'1px solid var(--bdr)' }}>
                {['Firma','Kontakt','Status','Źródło','Wartość','Ost. kontakt'].map(h => (
                  <th key={h} style={{ padding:'12px 16px', textAlign:'left', fontSize:11, fontWeight:600, color:'var(--t3)', textTransform:'uppercase', letterSpacing:0.6, whiteSpace:'nowrap' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.map((c, i) => (
                <tr key={c.id} onClick={()=>setSelected(c)}
                  style={{ borderBottom: i<filtered.length-1 ? '1px solid var(--bdr)' : 'none', cursor:'pointer', transition:'background .15s' }}
                  onMouseEnter={e=>e.currentTarget.style.background='var(--bg-hover)'}
                  onMouseLeave={e=>e.currentTarget.style.background='transparent'}
                >
                  <td style={{ padding:'13px 16px' }}>
                    <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                      <div style={{ width:32, height:32, borderRadius:8, background:c.avatarColor, display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:700, color:'#fff', flexShrink:0 }}>{c.initials}</div>
                      <span style={{ fontSize:13, fontWeight:600, color:'var(--t1)', whiteSpace:'nowrap' }}>{c.company}</span>
                    </div>
                  </td>
                  <td style={{ padding:'13px 16px', fontSize:13, color:'var(--t2)' }}>{c.person}</td>
                  <td style={{ padding:'13px 16px' }}><StatusPill status={c.status} /></td>
                  <td style={{ padding:'13px 16px', fontSize:12, color:'var(--t2)' }}>{sourceLabel(c.source)}</td>
                  <td style={{ padding:'13px 16px', fontSize:13, fontWeight:700, color:'var(--t1)' }}>{fmtVal(c.value)}</td>
                  <td style={{ padding:'13px 16px', fontSize:12, color:'var(--t3)' }}>{c.lastContact}</td>
                </tr>
              ))}
            </tbody>
          </table>
          {filtered.length === 0 && (
            <div style={{ padding:'40px', textAlign:'center', color:'var(--t3)', fontSize:14 }}>Brak wyników dla podanych filtrów</div>
          )}
        </div>

        {selected && <ClientDrawer client={selected} onClose={()=>setSelected(null)}
          onAddNote={(id, text) => {
            setClients(prev => prev.map(c => c.id === id ? { ...c, notes: c.notes ? c.notes + '\n' + text : text } : c));
            setSelected(prev => prev && prev.id === id ? { ...prev, notes: prev.notes ? prev.notes + '\n' + text : text } : prev);
          }}
        />}
        {showAdd && <AddClientModal onClose={()=>setShowAdd(false)} onSave={c => setClients(prev => [c, ...prev])} />}
      </div>
    );
  };
})();
