/* Clientes — Distribuidores e Picolezeiros */

function Clientes({ ctx }) {
  const [sub, setSub] = useState("distribuidores");
  const [editing, setEditing] = useState(null);
  const [history, setHistory] = useState(null); // { kind, client }

  return (
    <>
      <div className="page-head">
        <div>
          <h1>Clientes</h1>
          <p>Cadastro completo de distribuidores e picolezeiros</p>
        </div>
        <div className="page-head__actions">
          <Button variant="primary" icon={<Icons.Plus size={14} strokeWidth={2.2}/>} onClick={() => setEditing("new")}>
            {sub === "distribuidores" ? "Novo distribuidor" : "Novo picolezeiro"}
          </Button>
        </div>
      </div>

      <Tabs
        items={[
          { value:"distribuidores", label:`Distribuidores · ${ctx.state.distributors.length}` },
          { value:"picolezeiros",   label:`Picolezeiros · ${ctx.state.picolezeiros.length}` },
        ]}
        value={sub}
        onChange={setSub}
      />

      {sub === "distribuidores" && <DistribuidoresList ctx={ctx} onEdit={setEditing} onHistory={(d) => setHistory({ kind:"distributor", client:d })} />}
      {sub === "picolezeiros"   && <PicolezeirosList   ctx={ctx} onEdit={setEditing} onHistory={(p) => setHistory({ kind:"picolezeiro", client:p })} />}

      {editing && (sub === "distribuidores"
        ? <DistribuidorModal
            initial={editing === "new" ? null : editing}
            onClose={() => setEditing(null)}
            onSave={(v) => {
              if (editing === "new") ctx.actions.addDistributor(v);
              else ctx.actions.updateDistributor(editing.id, v);
              setEditing(null);
            }}
          />
        : <PicolezeiroModal
            initial={editing === "new" ? null : editing}
            beaches={ctx.state.beaches}
            defaultCommission={ctx.state.settings.commission}
            onClose={() => setEditing(null)}
            onSave={(v) => {
              if (editing === "new") ctx.actions.addPicolezeiro(v);
              else ctx.actions.updatePicolezeiro(editing.id, v);
              setEditing(null);
            }}
          />
      )}

      {history && (
        <ClientHistoryModal
          ctx={ctx}
          kind={history.kind}
          client={history.client}
          onClose={() => setHistory(null)}
        />
      )}
    </>
  );
}

function DistribuidoresList({ ctx, onEdit, onHistory }) {
  const [search, setSearch] = useState("");
  const list = ctx.state.distributors.filter(d => d.name.toLowerCase().includes(search.toLowerCase()) || d.city.toLowerCase().includes(search.toLowerCase()) || d.doc.includes(search));

  const onDelete = (d) => ctx.askConfirm({
    title: "Excluir distribuidor?",
    message: `Excluir "${d.name}"?`,
    detail: "O histórico de vendas deste cliente permanecerá nos relatórios.",
    danger: true,
    onConfirm: () => ctx.actions.deleteDistributor(d.id),
  });

  return (
    <>
      <div className="grid-4" style={{ marginBottom: 14 }}>
        <KPI tone="brand" medal={<Icons.Store size={18} strokeWidth={2}/>} label="Distribuidores ativos" value={ctx.state.distributors.length + ""} sub="Pessoa jurídica" />
        <KPI tone="info" medal={<Icons.Receipt size={18} strokeWidth={2}/>} label="Compras (mês)" value={ctx.state.distributors.reduce((s,d)=>s+d.totals.compras,0)+""} sub="Vendas registradas" />
        <KPI tone="success" medal={<Icons.ArrowDown size={18} strokeWidth={2}/>} label="Volume (mês)" value={fmtBRL(ctx.state.distributors.reduce((s,d)=>s+d.totals.valor,0))} trend="+12,8%" trendDir="up" />
        <KPI tone="warning" medal={<Icons.Wallet size={18} strokeWidth={2}/>} label="Ticket médio" value={fmtBRL(ctx.state.distributors.length ? ctx.state.distributors.reduce((s,d)=>s+d.totals.valor,0) / Math.max(1, ctx.state.distributors.reduce((s,d)=>s+d.totals.compras,0)) : 0)} sub="Por compra" />
      </div>

      <Card flush
        title="Distribuidores"
        action={
          <div style={{ display:"flex", gap:8 }}>
            <div className="topbar__search" style={{ width: 240, margin:0, padding:"5px 10px" }}>
              <Icons.Search size={13} />
              <input placeholder="Buscar..." value={search} onChange={e => setSearch(e.target.value)} />
            </div>
          </div>
        }
      >
        {list.length === 0 ? (
          <div className="empty">
            <Icons.Store size={26} color="var(--ink-300)"/>
            <h4>{search ? "Nenhum resultado" : "Nenhum distribuidor"}</h4>
            <p>{search ? "Tente outro termo de busca." : "Clique em \"Novo distribuidor\" para cadastrar o primeiro."}</p>
          </div>
        ) : (
        <table className="tbl">
          <thead>
            <tr>
              <th>Razão social</th>
              <th>CNPJ</th>
              <th>Cidade</th>
              <th>Pagamento</th>
              <th className="num">Compras</th>
              <th className="num">Volume</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {list.map(d => (
              <tr key={d.id} style={{ cursor:"pointer" }} onClick={() => onHistory(d)}>
                <td>
                  <div style={{ display:"flex", alignItems:"center", gap:10 }}>
                    <div className="avatar" style={{ width: 30, height: 30, fontSize:11, background: "linear-gradient(135deg, var(--brand-500), var(--brand-700))" }}>{d.name.split(" ").map(w => w[0]).slice(0,2).join("")}</div>
                    <div>
                      <div style={{ fontWeight:600, color:"var(--ink-900)" }}>{d.name}</div>
                      <div className="subtle">{d.phone}</div>
                    </div>
                  </div>
                </td>
                <td className="mono muted">{d.doc}</td>
                <td>{d.city}</td>
                <td><Chip>{d.payment}</Chip></td>
                <td className="num numeric">{d.totals.compras}</td>
                <td className="num strong numeric">{fmtBRL(d.totals.valor)}</td>
                <td onClick={e => e.stopPropagation()}>
                  <div style={{ display:"flex", gap: 2 }}>
                    <button className="icon-btn" title="Ver histórico" onClick={() => onHistory(d)}><Icons.History /></button>
                    <button className="icon-btn" title="Editar" onClick={() => onEdit(d)}><Icons.Edit /></button>
                    <button className="icon-btn" title="Excluir" onClick={() => onDelete(d)}><Icons.Trash /></button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        )}
      </Card>
    </>
  );
}

function PicolezeirosList({ ctx, onEdit, onHistory }) {
  const onDelete = (p) => ctx.askConfirm({
    title: "Excluir picolezeiro?",
    message: `Excluir "${p.name}"?`,
    detail: "O histórico de saídas permanecerá nos relatórios.",
    danger: true,
    onConfirm: () => ctx.actions.deletePicolezeiro(p.id),
  });

  if (ctx.state.picolezeiros.length === 0) {
    return (
      <Card>
        <div className="empty">
          <Icons.Sun size={26} color="var(--ink-300)"/>
          <h4>Nenhum picolezeiro cadastrado</h4>
          <p>Cadastre picolezeiros para começar a registrar saídas e consignações.</p>
        </div>
      </Card>
    );
  }

  return (
    <div className="grid-3" style={{ gap: 14 }}>
      {ctx.state.picolezeiros.map(p => {
        const beaches = p.beaches.map(bid => ctx.state.beaches.find(b => b.id === bid)?.name).filter(Boolean);
        return (
          <Card key={p.id} flush>
            <div style={{ padding: 16 }}>
              <div style={{ display:"flex", gap:14, alignItems:"center", marginBottom:14 }}>
                <div className="avatar" style={{ width: 52, height: 52, fontSize:16, background: "linear-gradient(135deg, #333, #1a1a1a)" }}>{p.photo}</div>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontWeight:700, color:"var(--ink-900)", fontSize:14 }}>{p.name}</div>
                  <div className="subtle">{p.phone}</div>
                  <div style={{ fontSize:11, color:"var(--ink-400)", marginTop:2 }}>{p.since ? "Desde " + fmtDate(p.since) : ""}</div>
                </div>
                <Chip tone="brand" dot>{p.commission}%</Chip>
              </div>

              <div className="subtle" style={{ display:"flex", alignItems:"center", gap:6, marginBottom:6 }}>
                <Icons.MapPin size={11}/> Praias atendidas
              </div>
              <div style={{ display:"flex", flexWrap:"wrap", gap:5, marginBottom:14, minHeight:22 }}>
                {beaches.length > 0 ? beaches.map((b,i) => <Chip key={i}>{b}</Chip>) : <span className="subtle">Nenhuma praia atribuída</span>}
              </div>

              <div className="pill-row" style={{ paddingTop:10, borderTop:"1px solid var(--line)" }}>
                <div className="pm"><strong>{p.totals.saidas}</strong><span>Saídas</span></div>
                <div className="pm"><strong>{fmtBRL(p.totals.vendido)}</strong><span>Faturado</span></div>
                <div className="pm"><strong style={{ color:"var(--brand-700)" }}>{fmtBRL(p.totals.comissao)}</strong><span>Comissão</span></div>
              </div>

              <div style={{ display:"flex", gap:6, marginTop:14 }}>
                <Button variant="primary" size="sm" icon={<Icons.History size={12}/>} onClick={() => onHistory(p)} style={{ flex:1, justifyContent:"center" }}>Histórico</Button>
                <Button variant="secondary" size="sm" icon={<Icons.Edit size={12}/>} onClick={() => onEdit(p)}>Editar</Button>
                <Button variant="danger" size="sm" icon={<Icons.Trash size={12}/>} onClick={() => onDelete(p)} />
              </div>
            </div>
          </Card>
        );
      })}
    </div>
  );
}

function DistribuidorModal({ initial, onClose, onSave }) {
  const [type, setType] = useState(initial?.type || "PJ");
  const [name, setName] = useState(initial?.name || "");
  const [doc, setDoc] = useState(initial?.doc || "");
  const [ie, setIe] = useState(initial?.ie || "");
  const [phone, setPhone] = useState(initial?.phone || "");
  const [email, setEmail] = useState(initial?.email || "");
  const [cep, setCep] = useState(initial?.cep || "");
  const [city, setCity] = useState(initial?.city || "");
  const [address, setAddress] = useState(initial?.address || "");
  const [payment, setPayment] = useState(initial?.payment || "PIX");
  const [err, setErr] = useState({});

  const submit = () => {
    const e = {};
    if (!name.trim()) e.name = "Informe a razão social";
    if (!doc.trim()) e.doc = "Informe o documento";
    if (!phone.trim()) e.phone = "Informe o WhatsApp";
    setErr(e);
    if (Object.keys(e).length) return;
    onSave({ type, name: name.trim(), doc, ie, phone, email, cep, city, address, payment });
  };

  return (
    <Modal title={initial ? "Editar distribuidor" : "Novo distribuidor"} subtitle={initial?.name || "Cadastrar nova loja, mercado ou parceiro"} onClose={onClose} size="lg"
      footer={<><Button variant="ghost" onClick={onClose}>Cancelar</Button><Button variant="primary" onClick={submit}>{initial ? "Salvar alterações" : "Salvar distribuidor"}</Button></>}
    >
      <Segmented options={[{label:"Pessoa Jurídica", value:"PJ"},{label:"Pessoa Física", value:"PF"}]} value={type} onChange={setType} />
      <div style={{ height:14 }} />
      <div className="grid-2" style={{ gap:14 }}>
        <Field label={type === "PJ" ? "Razão social" : "Nome"} required error={err.name} style={{ gridColumn:"span 2" }}>
          <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder={type === "PJ" ? "Empresa LTDA" : "Nome completo"} autoFocus />
        </Field>
        <Field label={type === "PJ" ? "CNPJ" : "CPF"} required error={err.doc}>
          <input className="input" value={doc} onChange={e => setDoc(type === "PJ" ? maskCNPJ(e.target.value) : maskCPF(e.target.value))} placeholder={type === "PJ" ? "00.000.000/0000-00" : "000.000.000-00"} />
        </Field>
        {type === "PJ" && <Field label="Inscrição Estadual"><input className="input" value={ie} onChange={e => setIe(e.target.value)} placeholder="000.000.000.000" /></Field>}
        {type === "PF" && <Field label=" " hint=""><span /></Field>}
        <Field label="WhatsApp" required error={err.phone}>
          <input className="input" value={phone} onChange={e => setPhone(maskPhone(e.target.value))} placeholder="(00) 00000-0000" />
        </Field>
        <Field label="E-mail">
          <input className="input" value={email} onChange={e => setEmail(e.target.value)} placeholder="contato@..." />
        </Field>
        <Field label="CEP">
          <input className="input" value={cep} onChange={e => setCep(maskCEP(e.target.value))} placeholder="00000-000" />
        </Field>
        <Field label="Cidade / UF">
          <input className="input" value={city} onChange={e => setCity(e.target.value)} placeholder="Salvador / BA" />
        </Field>
        <Field label="Endereço" style={{ gridColumn:"span 2" }}>
          <input className="input" value={address} onChange={e => setAddress(e.target.value)} placeholder="Rua, número, bairro" />
        </Field>
        <Field label="Forma de pagamento padrão">
          <select className="select" value={payment} onChange={e => setPayment(e.target.value)}>
            <option>PIX</option><option>Dinheiro</option><option>Cartão</option><option>Boleto 14d</option><option>Prazo 30d</option>
          </select>
        </Field>
      </div>
    </Modal>
  );
}

function PicolezeiroModal({ initial, beaches, defaultCommission, onClose, onSave }) {
  const [name, setName] = useState(initial?.name || "");
  const [cpf, setCpf] = useState(initial?.cpf || "");
  const [rg, setRg] = useState(initial?.rg || "");
  const [phone, setPhone] = useState(initial?.phone || "");
  const [address, setAddress] = useState(initial?.address || "");
  const [commission, setCommission] = useState(initial?.commission ?? defaultCommission);
  const [selBeaches, setSelBeaches] = useState(initial?.beaches || []);
  const [since, setSince] = useState(initial?.since || "");
  const [err, setErr] = useState({});

  const submit = () => {
    const e = {};
    if (!name.trim()) e.name = "Informe o nome";
    if (!cpf.trim()) e.cpf = "Informe o CPF";
    if (!phone.trim()) e.phone = "Informe o WhatsApp";
    if (selBeaches.length === 0) e.beaches = "Selecione ao menos uma praia";
    setErr(e);
    if (Object.keys(e).length) return;
    const photo = name.trim().split(" ").map(w => w[0]).slice(0,2).join("").toUpperCase();
    onSave({
      name: name.trim(), cpf, rg, phone, address,
      commission: parseInt(commission || 0, 10), beaches: selBeaches, photo, since,
    });
  };

  return (
    <Modal title={initial ? "Editar picolezeiro" : "Novo picolezeiro"} subtitle={initial?.name || "Cadastrar vendedor de consignação"} onClose={onClose} size="lg"
      footer={<><Button variant="ghost" onClick={onClose}>Cancelar</Button><Button variant="primary" onClick={submit}>{initial ? "Salvar alterações" : "Salvar picolezeiro"}</Button></>}
    >
      <div className="grid-2" style={{ gap:14 }}>
        <Field label="Nome completo" required error={err.name} style={{ gridColumn:"span 2" }}>
          <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="Nome do picolezeiro" autoFocus />
        </Field>
        <Field label="CPF" required error={err.cpf}>
          <input className="input" value={cpf} onChange={e => setCpf(maskCPF(e.target.value))} placeholder="000.000.000-00" />
        </Field>
        <Field label="RG">
          <input className="input" value={rg} onChange={e => setRg(e.target.value)} placeholder="00.000.000-0" />
        </Field>
        <Field label="WhatsApp" required error={err.phone}>
          <input className="input" value={phone} onChange={e => setPhone(maskPhone(e.target.value))} placeholder="(00) 00000-0000" />
        </Field>
        <Field label="Data de início">
          <input className="input" value={since} onChange={e => setSince(e.target.value)} placeholder="AAAA-MM-DD" />
        </Field>
        <Field label="Endereço" style={{ gridColumn:"span 2" }}>
          <input className="input" value={address} onChange={e => setAddress(e.target.value)} placeholder="Rua, número, bairro, cidade" />
        </Field>
        <Field label="Comissão (%)" hint={`Padrão da empresa: ${defaultCommission}%`}>
          <input className="input numeric" value={commission} onChange={e => setCommission(e.target.value.replace(/\D/g,""))} />
        </Field>
        <Field label=""><span /></Field>
        <Field label="Praias atendidas" required error={err.beaches} style={{ gridColumn:"span 2" }}>
          <div style={{ display:"flex", flexWrap:"wrap", gap:6 }}>
            {beaches.length === 0 ? (
              <span className="subtle">Cadastre praias em Configurações antes.</span>
            ) : beaches.map(b => {
              const on = selBeaches.includes(b.id);
              return (
                <button key={b.id} type="button" onClick={() => setSelBeaches(prev => on ? prev.filter(x => x !== b.id) : [...prev, b.id])}
                  style={{
                    padding:"6px 12px", borderRadius:100, fontSize:12, fontWeight:600,
                    border: "1px solid " + (on ? "var(--brand-600)" : "var(--line-strong)"),
                    background: on ? "var(--brand-50)" : "white",
                    color: on ? "var(--brand-700)" : "var(--ink-700)",
                    cursor:"pointer", display:"inline-flex", gap: 5, alignItems:"center"
                  }}
                >
                  {on && <Icons.Check size={11} strokeWidth={2.4} />}
                  {b.name}
                </button>
              );
            })}
          </div>
        </Field>
      </div>
    </Modal>
  );
}

window.Clientes = Clientes;
