
// ============================================================
// JuFlow — Clients List
// ============================================================
const { useState: useStCL, useMemo: useMemosCL } = React;
const UCL = window.JFUtils;

const Clientes = ({ appointments, onViewClient, onNewAppt }) => {
  const [search, setSearch]     = useStCL('');
  const [statusF, setStatusF]   = useStCL('all');
  const [sortBy, setSortBy]     = useStCL('name');
  const [sortDir, setSortDir]   = useStCL('asc');
  const [showNew, setShowNew]   = useStCL(false);

  const clients = useMemosCL(() => {
    let list = window.JF.CLIENTS;

    if (search) {
      const q = search.toLowerCase();
      list = list.filter(c =>
        c.name.toLowerCase().includes(q) ||
        c.phone.includes(q) ||
        c.email.toLowerCase().includes(q)
      );
    }
    if (statusF !== 'all') list = list.filter(c => c.status === statusF);

    list = [...list].sort((a, b) => {
      let av, bv;
      if (sortBy === 'name')       { av = a.name; bv = b.name; }
      else if (sortBy === 'spent') { av = a.totalSpent; bv = b.totalSpent; }
      else if (sortBy === 'visits'){ av = a.visits; bv = b.visits; }
      else if (sortBy === 'last')  { av = a.lastVisit || ''; bv = b.lastVisit || ''; }
      else                         { av = a.name; bv = b.name; }
      if (sortDir === 'asc')  return av > bv ? 1 : -1;
      return av < bv ? 1 : -1;
    });
    return list;
  }, [search, statusF, sortBy, sortDir]);

  const toggleSort = (col) => {
    if (sortBy === col) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
    else { setSortBy(col); setSortDir('asc'); }
  };

  const SortIcon = ({ col }) => {
    if (sortBy !== col) return <Icon name="ArrowUpDown" size={12} color="#C4CDD6" />;
    return <Icon name={sortDir==='asc' ? 'ArrowUp' : 'ArrowDown'} size={12} color="#FF6B35" />;
  };

  const getFrequency = (clientId) => {
    const count = appointments.filter(a => a.clientId === clientId && a.status === 'completed').length;
    if (count >= 20) return { label:'Frequente', color:'#059669' };
    if (count >= 8)  return { label:'Regular', color:'#0891B2' };
    if (count >= 3)  return { label:'Ocasional', color:'#D97706' };
    return { label:'Novo', color:'#7C3AED' };
  };

  const totalRevenue   = window.JF.CLIENTS.reduce((s,c) => s+c.totalSpent, 0);
  const activeCount    = window.JF.CLIENTS.filter(c => c.status==='active').length;
  const vipCount       = window.JF.CLIENTS.filter(c => c.tags.includes('VIP')).length;
  const inactiveCount  = window.JF.CLIENTS.filter(c => c.status==='inactive').length;

  return (
    <div style={{ padding:28, display:'flex', flexDirection:'column', gap:20 }}>
      {/* Top metrics */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14 }}>
        <MetricCard title="Total de Clientes"  value={window.JF.CLIENTS.length} icon="Users"        color="#0891B2" subtitle="cadastrados" />
        <MetricCard title="Clientes Ativos"    value={activeCount}              icon="UserCheck"     color="#059669" subtitle="ativos" />
        <MetricCard title="Clientes VIP"       value={vipCount}                 icon="Star"          color="#D97706" subtitle="premium" />
        <MetricCard title="Receita Total"      value={UCL.formatCurrency(totalRevenue)} icon="TrendingUp" color="#FF6B35" subtitle="histórico" />
      </div>

      {/* Filters + actions */}
      <div style={{
        background:'#fff', borderRadius:14, padding:'16px 20px',
        boxShadow:'0 2px 8px rgba(10,31,68,.06)',
        display:'flex', alignItems:'center', gap:12, flexWrap:'wrap',
      }}>
        <SearchBar value={search} onChange={setSearch} placeholder="Buscar por nome, telefone ou e-mail..." style={{ flex:'1 1 220px', minWidth:200 }} />

        <div style={{ display:'flex', background:'#F3F4F6', borderRadius:8, padding:3 }}>
          {[['all','Todos'],['active','Ativos'],['inactive','Inativos']].map(([v,l]) => (
            <button key={v} onClick={() => setStatusF(v)} style={{
              padding:'5px 12px', borderRadius:6, fontSize:12, fontWeight:600, cursor:'pointer',
              background: statusF===v ? '#fff' : 'transparent', color: statusF===v ? '#0A1F44' : '#6B7280',
              border:'none', boxShadow: statusF===v ? '0 1px 3px rgba(0,0,0,.08)' : 'none',
              transition:'all .15s',
            }}>{l}</button>
          ))}
        </div>

        <span style={{ fontSize:13, color:'#9CA3AF', marginLeft:'auto' }}>{clients.length} cliente{clients.length!==1?'s':''}</span>
        <Button variant="primary" icon="UserPlus" onClick={() => setShowNew(true)}>Novo Cliente</Button>
      </div>

      {/* Table */}
      <div style={{ background:'#fff', borderRadius:14, boxShadow:'0 2px 8px rgba(10,31,68,.06)', overflow:'hidden' }}>
        {clients.length === 0 ? (
          <EmptyState icon="Users" title="Nenhum cliente encontrado" message="Tente ajustar os filtros ou cadastre um novo cliente." action={<Button variant="primary" icon="UserPlus" onClick={() => setShowNew(true)}>Novo Cliente</Button>} />
        ) : (
          <div style={{ overflowX:'auto' }}>
            <table style={{ width:'100%', borderCollapse:'collapse' }}>
              <thead>
                <tr style={{ background:'#F9FAFB', borderBottom:'2px solid #E2E8F0' }}>
                  {[
                    { label:'Cliente', col:'name', w:'28%' },
                    { label:'Telefone', col:null, w:'14%' },
                    { label:'Tags', col:null, w:'14%' },
                    { label:'Última visita', col:'last', w:'12%' },
                    { label:'Total gasto', col:'spent', w:'12%' },
                    { label:'Frequência', col:'visits', w:'11%' },
                    { label:'Ações', col:null, w:'9%' },
                  ].map(h => (
                    <th key={h.label} style={{
                      padding:'12px 16px', textAlign:'left', fontSize:11, fontWeight:700,
                      color:'#6B7280', textTransform:'uppercase', letterSpacing:.5,
                      width:h.w, whiteSpace:'nowrap',
                      cursor: h.col ? 'pointer' : 'default',
                      userSelect:'none',
                    }}
                      onClick={() => h.col && toggleSort(h.col)}
                    >
                      <span style={{ display:'flex', alignItems:'center', gap:4 }}>
                        {h.label} {h.col && <SortIcon col={h.col} />}
                      </span>
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {clients.map((client, i) => {
                  const freq = getFrequency(client.id);
                  const daysSince = client.lastVisit ? UCL.daysBetween(client.lastVisit, window.JF.TODAY) : 999;
                  return (
                    <tr key={client.id} style={{
                      borderBottom: i < clients.length-1 ? '1px solid #F0F4F8' : 'none',
                      transition:'background .1s', cursor:'pointer',
                    }}
                      onClick={() => onViewClient(client)}
                      onMouseEnter={e => e.currentTarget.style.background='#F9FAFB'}
                      onMouseLeave={e => e.currentTarget.style.background='#fff'}
                    >
                      <td style={{ padding:'13px 16px' }}>
                        <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                          <div style={{ position:'relative' }}>
                            <Avatar name={client.name} color="#0A1F44" size={36} />
                            <div style={{
                              position:'absolute', bottom:0, right:0,
                              width:10, height:10, borderRadius:'50%',
                              background: client.status==='active' ? '#22C55E' : '#D1D5DB',
                              border:'1.5px solid #fff',
                            }} />
                          </div>
                          <div>
                            <div style={{ fontSize:13, fontWeight:700, color:'#0A1F44' }}>{client.name}</div>
                            <div style={{ fontSize:11, color:'#9CA3AF' }}>{client.email}</div>
                          </div>
                        </div>
                      </td>
                      <td style={{ padding:'13px 16px', fontSize:13, color:'#374151' }}>{client.phone}</td>
                      <td style={{ padding:'13px 16px' }}>
                        <div style={{ display:'flex', gap:4, flexWrap:'wrap' }}>
                          {client.tags.map(tag => <TagChip key={tag} tag={tag} />)}
                          {client.tags.length === 0 && <span style={{ fontSize:12, color:'#C4CDD6' }}>—</span>}
                        </div>
                      </td>
                      <td style={{ padding:'13px 16px' }}>
                        <div>
                          <div style={{ fontSize:13, color: daysSince > 60 ? '#EF4444' : '#374151', fontWeight: daysSince > 60 ? 600 : 400 }}>
                            {client.lastVisit ? UCL.formatDate(client.lastVisit) : '—'}
                          </div>
                          {daysSince > 60 && (
                            <div style={{ fontSize:10, color:'#EF4444' }}>{daysSince}d atrás</div>
                          )}
                        </div>
                      </td>
                      <td style={{ padding:'13px 16px' }}>
                        <div style={{ fontSize:13, fontWeight:700, color:'#0A1F44' }}>{UCL.formatCurrency(client.totalSpent)}</div>
                        <div style={{ fontSize:10, color:'#9CA3AF' }}>{client.visits} sessões</div>
                      </td>
                      <td style={{ padding:'13px 16px' }}>
                        <span style={{ fontSize:11, fontWeight:700, color:freq.color, background:UCL.hexToRgba(freq.color, 0.1), padding:'3px 8px', borderRadius:20 }}>
                          {freq.label}
                        </span>
                      </td>
                      <td style={{ padding:'13px 16px' }} onClick={e => e.stopPropagation()}>
                        <div style={{ display:'flex', gap:6 }}>
                          <button
                            onClick={() => onViewClient(client)}
                            title="Ver ficha"
                            style={{ width:30, height:30, borderRadius:7, border:'1px solid #E2E8F0', background:'#F9FAFB', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}
                            onMouseEnter={e => e.currentTarget.style.background='#EFF6FF'}
                            onMouseLeave={e => e.currentTarget.style.background='#F9FAFB'}
                          >
                            <Icon name="Eye" size={13} color="#0891B2" />
                          </button>
                          <button
                            onClick={() => onNewAppt({ clientId: client.id })}
                            title="Novo agendamento"
                            style={{ width:30, height:30, borderRadius:7, border:'1px solid #E2E8F0', background:'#F9FAFB', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}
                            onMouseEnter={e => e.currentTarget.style.background='#FFF0EA'}
                            onMouseLeave={e => e.currentTarget.style.background='#F9FAFB'}
                          >
                            <Icon name="CalendarPlus" size={13} color="#FF6B35" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
};

// ─── NEW CLIENT MODAL ─────────────────────────────────────
const NewClientModal = ({ open, onClose, onSave, addToast }) => {
  const [form, setForm] = useStCL({ name:'', phone:'', email:'', cpf:'', birthdate:'', notes:'' });
  const set = (k,v) => setForm(f => ({...f,[k]:v}));
  const handleSave = () => {
    if (!form.name || !form.phone) { addToast('Nome e telefone são obrigatórios.','error'); return; }
    onSave({ ...form, id:Date.now(), tags:[], status:'active', totalSpent:0, lastVisit:null, visits:0 });
    addToast('Cliente cadastrado com sucesso!','success');
    onClose();
  };
  return (
    <Modal open={open} onClose={onClose} title="Novo Cliente" width={520}
      footer={<><Button variant="secondary" onClick={onClose}>Cancelar</Button><Button variant="primary" icon="Check" onClick={handleSave}>Salvar</Button></>}
    >
      <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
          <Input label="Nome completo" value={form.name} onChange={v=>set('name',v)} placeholder="Maria Silva" required style={{ gridColumn:'1/-1' }} />
          <Input label="Telefone/WhatsApp" value={form.phone} onChange={v=>set('phone',v)} placeholder="(11) 99999-9999" required icon="Phone" />
          <Input label="E-mail" type="email" value={form.email} onChange={v=>set('email',v)} placeholder="maria@email.com" icon="Mail" />
          <Input label="CPF" value={form.cpf} onChange={v=>set('cpf',v)} placeholder="000.000.000-00" />
          <Input label="Data de nascimento" type="date" value={form.birthdate} onChange={v=>set('birthdate',v)} icon="Cake" />
        </div>
        <Textarea label="Observações" value={form.notes} onChange={v=>set('notes',v)} placeholder="Informações relevantes sobre o cliente..." rows={2} />
      </div>
    </Modal>
  );
};

Object.assign(window, { Clientes, NewClientModal });
