/* global React, VendusAtoms, VendusData */
const { I, Chip, Btn, Card, Eyebrow, SectionTitle, AreaChart, Bars, Donut, Sparkline, brl, brlShort, pct } = window.VendusAtoms;
const { STORES, REVENUE_MONTH, COSTS_MONTH, TOP_PRODUCTS, SUPPLIERS, COSTS, CASHFLOW_30D, PAYMENT_ALERTS } = window.VendusData;
const { useState, useMemo } = React;

/* ============================= FLUXO DE CAIXA ============================= */
function CashFlowPage() {
  const [cashFilter, setCashFilter] = useState("all"); // all | in | out
  const totalIn  = CASHFLOW_30D.reduce((s,d) => s + d.in, 0);
  const totalOut = CASHFLOW_30D.reduce((s,d) => s + d.out, 0);
  const balance  = totalIn - totalOut;

  const entries = [
    { date:"15/05", desc:"Recebimento Shopee — semana 19", cat:"Vendas",        type:"in",  value: 32_480, account:"Conta principal" },
    { date:"15/05", desc:"Pagamento Tech Importadora SP",   cat:"Fornecedores",  type:"out", value:  8_500, account:"Conta principal" },
    { date:"14/05", desc:"Recebimento Mercado Livre",       cat:"Vendas",        type:"in",  value: 24_120, account:"Conta principal" },
    { date:"14/05", desc:"Comissão Shopee Ads",             cat:"Marketing",     type:"out", value:  4_280, account:"Conta principal" },
    { date:"13/05", desc:"Recebimento PIX direto",          cat:"Vendas",        type:"in",  value:  6_840, account:"PIX" },
    { date:"13/05", desc:"Folha de pagamento — Maio",       cat:"Pessoal",       type:"out", value: 22_400, account:"Conta principal" },
    { date:"12/05", desc:"Aluguel galpão Tatuapé",          cat:"Aluguel",       type:"out", value:  8_500, account:"Conta principal" },
    { date:"12/05", desc:"Recebimento TikTok Shop",         cat:"Vendas",        type:"in",  value: 11_840, account:"Conta principal" },
  ];
  const shownEntries = cashFilter === "all" ? entries : entries.filter(e => e.type === cashFilter);

  return (
    <div className="page fade-in">
      <div className="page-header">
        <div>
          <Eyebrow>Financeiro</Eyebrow>
          <h1 className="page-title">Fluxo de Caixa</h1>
          <div className="page-sub">Movimentação dos últimos 30 dias</div>
        </div>
        <div style={{ display:"flex", gap:10 }}>
          <Btn variant="outline"><I name="link" size={14}/> Conectar banco</Btn>
          <Btn variant="outline"><I name="download" size={14}/> Exportar</Btn>
          <Btn variant="primary"><I name="plus" size={14}/> Lançar movimento</Btn>
        </div>
      </div>

      <div style={{ display:"grid", gridTemplateColumns:"repeat(4,1fr)", gap: 16, marginBottom: 20 }}>
        <Card className="kpi kpi-success" padding={18}>
          <div className="kpi-icon"><I name="trending-up" size={18}/></div>
          <div className="kpi-label">Entradas</div>
          <div className="kpi-value">{brl(totalIn)}</div>
          <div className="kpi-delta up">{pct(14.2)} vs mês ant.</div>
        </Card>
        <Card className="kpi kpi-danger" padding={18}>
          <div className="kpi-icon"><I name="trending-down" size={18}/></div>
          <div className="kpi-label">Saídas</div>
          <div className="kpi-value">{brl(totalOut)}</div>
          <div className="kpi-delta down">{pct(8.4)} vs mês ant.</div>
        </Card>
        <Card className="kpi kpi-orange" padding={18}>
          <div className="kpi-icon"><I name="wallet" size={18}/></div>
          <div className="kpi-label">Saldo do período</div>
          <div className="kpi-value">{brl(balance)}</div>
          <div className="kpi-delta up">{pct(22.1)} vs mês ant.</div>
        </Card>
        <Card className="kpi" padding={18}>
          <div className="kpi-icon"><I name="banknote" size={18}/></div>
          <div className="kpi-label">Saldo em caixa</div>
          <div className="kpi-value">{brl(184_320)}</div>
          <div className="kpi-delta" style={{ color:"var(--fg-3)", fontWeight: 500 }}>3 contas conectadas</div>
        </Card>
      </div>

      <Card style={{ marginBottom: 16 }}>
        <SectionTitle title="Entradas e saídas" sub="Movimento diário · 14 dias"
          action={
            <div style={{ display:"flex", gap:14, alignItems:"center" }}>
              <span style={{ display:"inline-flex", alignItems:"center", gap:6, fontSize:12 }}><span style={{width:10,height:10,borderRadius:3,background:"#4ADE80"}}></span>Entradas</span>
              <span style={{ display:"inline-flex", alignItems:"center", gap:6, fontSize:12 }}><span style={{width:10,height:10,borderRadius:3,background:"#FF6A6A"}}></span>Saídas</span>
            </div>
          }/>
        <AreaChart
          height={220}
          color1="#4ADE80"
          color2="#FF6A6A"
          series={[
            { label:"Entradas", values: CASHFLOW_30D.map(d => d.in/1000) },
            { label:"Saídas",   values: CASHFLOW_30D.map(d => d.out/1000) },
          ]}
        />
        <div style={{ display:"flex", justifyContent:"space-between", marginTop: 8 }}>
          {CASHFLOW_30D.map((d,i) => (
            <span key={d.date} style={{ fontSize: 10, color:"var(--fg-3)", fontFamily:"Space Grotesk", letterSpacing:".05em" }}>
              {i%2===0 ? d.date : ""}
            </span>
          ))}
        </div>
      </Card>

      <div style={{ display:"grid", gridTemplateColumns:"1.5fr 1fr", gap: 16 }}>
        <Card padding={0}>
          <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--border)", display:"flex", justifyContent:"space-between", alignItems:"center" }}>
            <h3 className="section-title">Últimos lançamentos</h3>
            <div className="seg">
              <button className={cashFilter==="all"?"active":""} onClick={()=>setCashFilter("all")}>Todos</button>
              <button className={cashFilter==="in"?"active":""} onClick={()=>setCashFilter("in")}>Entradas</button>
              <button className={cashFilter==="out"?"active":""} onClick={()=>setCashFilter("out")}>Saídas</button>
            </div>
          </div>
          <table className="tbl">
            <thead>
              <tr>
                <th>Data</th><th>Descrição</th><th>Categoria</th><th>Conta</th><th className="num">Valor</th>
              </tr>
            </thead>
            <tbody>
              {shownEntries.map((e,i) => (
                <tr key={i}>
                  <td className="text-muted">{e.date}</td>
                  <td style={{ fontWeight: 500 }}>
                    <span style={{ display: "inline-flex", alignItems:"center", gap: 8 }}>
                      <span style={{
                        width: 28, height: 28, borderRadius: 8, display:"grid", placeItems:"center",
                        background: e.type==="in" ? "rgba(34,197,94,.12)" : "rgba(239,68,68,.12)",
                        color: e.type==="in" ? "#4ADE80" : "#FCA5A5",
                      }}>
                        <I name={e.type==="in" ? "arrow-down-left" : "arrow-up-right"} size={14}/>
                      </span>
                      {e.desc}
                    </span>
                  </td>
                  <td><Chip tone={e.type==="in"?"success":"violet"}>{e.cat}</Chip></td>
                  <td className="text-muted">{e.account}</td>
                  <td className="num mono-numeric font-display" style={{ fontWeight: 700, color: e.type==="in" ? "#4ADE80" : "#FF6A6A" }}>
                    {e.type==="in" ? "+" : "−"}{brl(e.value)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>

        <Card>
          <SectionTitle title="Categorias de saída" sub="Onde seu dinheiro está indo"/>
          <div style={{ display: "flex", justifyContent: "center", marginBottom: 18 }}>
            <Donut
              size={180} stroke={24}
              slices={[
                { value: 28_460, color:"#FB923C" },
                { value: 22_400, color:"#A78BFA" },
                { value: 19_320, color:"#F472B6" },
                { value: 14_650, color:"#FBBF24" },
                { value:  8_500, color:"#60A5FA" },
                { value:  5_860, color:"#94A3B8" },
              ]}
              center={
                <div>
                  <div className="text-faint" style={{fontSize:10, fontFamily:"Space Grotesk"}}>SAÍDAS</div>
                  <div className="font-display" style={{ fontWeight: 700, fontSize: 18 }}>R$ 99k</div>
                </div>
              }
            />
          </div>
          <div style={{ display:"flex", flexDirection:"column", gap: 10 }}>
            {[
              { l:"Comissão marketplaces", v:28_460, c:"#FB923C" },
              { l:"Folha de pagamento",    v:22_400, c:"#A78BFA" },
              { l:"Frete e logística",     v:19_320, c:"#F472B6" },
              { l:"Anúncios",              v:14_650, c:"#FBBF24" },
              { l:"Aluguel + utilidades",  v: 8_500, c:"#60A5FA" },
              { l:"Outros",                v: 5_860, c:"#94A3B8" },
            ].map(c => (
              <div key={c.l} style={{ display:"flex", justifyContent:"space-between", fontSize: 13 }}>
                <span style={{ display:"flex", gap: 8, alignItems: "center" }}>
                  <span style={{ width:10, height:10, borderRadius:3, background: c.c }}></span>
                  {c.l}
                </span>
                <span className="font-display mono-numeric" style={{ fontWeight: 600 }}>{brl(c.v)}</span>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}

/* ============================= CUSTOS ============================= */
function CostsPage() {
  const [tab, setTab] = useState("all");
  const total = COSTS.reduce((s,c) => s + c.value, 0);
  const fixedTotal = COSTS.filter(c => c.type === "fixed").reduce((s,c) => s + c.value, 0);
  const varTotal   = COSTS.filter(c => c.type === "variable").reduce((s,c) => s + c.value, 0);
  const items = tab==="all" ? COSTS : COSTS.filter(c => c.type === tab);

  return (
    <div className="page fade-in">
      <div className="page-header">
        <div>
          <Eyebrow>Engine de Custos</Eyebrow>
          <h1 className="page-title">Custos fixos e variáveis</h1>
          <div className="page-sub">Tudo o que impacta sua margem, mapeado por categoria</div>
        </div>
        <div style={{ display:"flex", gap: 10 }}>
          <Btn variant="outline"><I name="upload" size={14}/> Importar CSV</Btn>
          <Btn variant="primary"><I name="plus" size={14}/> Adicionar custo</Btn>
        </div>
      </div>

      <div style={{ display:"grid", gridTemplateColumns: "repeat(3,1fr)", gap: 16, marginBottom: 20 }}>
        <Card className="kpi kpi-orange" padding={18}>
          <div className="kpi-icon"><I name="receipt" size={18}/></div>
          <div className="kpi-label">Custo total mensal</div>
          <div className="kpi-value">{brl(total)}</div>
          <div className="kpi-delta down">{pct(6.4)} vs abril</div>
        </Card>
        <Card className="kpi" padding={18}>
          <div className="kpi-icon"><I name="anchor" size={18}/></div>
          <div className="kpi-label">Custos fixos</div>
          <div className="kpi-value">{brl(fixedTotal)}</div>
          <div className="kpi-delta" style={{ color:"var(--fg-3)", fontWeight: 500 }}>{((fixedTotal/(total||1))*100).toFixed(0)}% do total</div>
        </Card>
        <Card className="kpi kpi-info" padding={18}>
          <div className="kpi-icon"><I name="zap" size={18}/></div>
          <div className="kpi-label">Custos variáveis</div>
          <div className="kpi-value">{brl(varTotal)}</div>
          <div className="kpi-delta" style={{ color:"var(--fg-3)", fontWeight: 500 }}>{((varTotal/(total||1))*100).toFixed(0)}% do total</div>
        </Card>
      </div>

      <Card padding={0}>
        <div style={{ padding: "14px 18px", borderBottom:"1px solid var(--border)", display:"flex", justifyContent: "space-between", alignItems:"center" }}>
          <h3 className="section-title">Lista de custos</h3>
          <div className="seg">
            <button onClick={()=>setTab("all")}      className={tab==="all"?"active":""}>Todos</button>
            <button onClick={()=>setTab("fixed")}    className={tab==="fixed"?"active":""}>Fixos</button>
            <button onClick={()=>setTab("variable")} className={tab==="variable"?"active":""}>Variáveis</button>
          </div>
        </div>
        <table className="tbl">
          <thead>
            <tr>
              <th>Custo</th><th>Tipo</th><th>Loja</th><th>Frequência</th><th className="num">Valor</th><th className="num">% do total</th><th></th>
            </tr>
          </thead>
          <tbody>
            {items.map(c => (
              <tr key={c.name}>
                <td>
                  <div style={{ display:"flex", alignItems: "center", gap: 12 }}>
                    <div style={{ width: 32, height: 32, borderRadius: 8, background: "rgba(249,115,22,.12)", color: "var(--primary)", display: "grid", placeItems:"center" }}>
                      <I name={c.type==="fixed" ? "anchor" : "zap"} size={14}/>
                    </div>
                    <span style={{ fontWeight: 500 }}>{c.name}</span>
                  </div>
                </td>
                <td><Chip tone={c.type==="fixed"?"violet":"orange"}>{c.type==="fixed"?"Fixo":"Variável"}</Chip></td>
                <td className="text-muted">{c.store ? STORES.find(s => s.id === c.store)?.channel || "—" : <span className="text-faint">Todas</span>}</td>
                <td className="text-muted">{c.freq}</td>
                <td className="num mono-numeric font-display" style={{ fontWeight: 700 }}>{brl(c.value)}</td>
                <td className="num">
                  <div style={{ display:"flex", alignItems:"center", gap: 8, justifyContent:"flex-end" }}>
                    <div style={{ width: 70, background:"var(--bg-elev-2)", height: 6, borderRadius: 999 }}>
                      <div style={{ height:"100%", width: Math.min(100, (c.value/(total||1))*100*3.5)+"%", borderRadius: 999, background: "var(--primary)" }}></div>
                    </div>
                    <span className="text-muted mono-numeric" style={{ fontSize: 12, minWidth: 38, textAlign:"right" }}>{((c.value/(total||1))*100).toFixed(1).replace(".",",")}%</span>
                  </div>
                </td>
                <td className="num"><Btn variant="ghost" size="sm" iconOnly><I name="more-horizontal" size={14}/></Btn></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

/* ============================= FORNECEDORES ============================= */
function SuppliersPage() {
  return (
    <div className="page fade-in">
      <div className="page-header">
        <div>
          <Eyebrow>Compras</Eyebrow>
          <h1 className="page-title">Fornecedores</h1>
          <div className="page-sub">{SUPPLIERS.length} parceiros ativos · {brl(SUPPLIERS.reduce((s,x)=>s+x.pending,0))} em aberto</div>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <Btn variant="outline"><I name="search" size={14}/> Buscar</Btn>
          <Btn variant="primary"><I name="plus" size={14}/> Novo fornecedor</Btn>
        </div>
      </div>

      <div style={{ display:"grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px,1fr))", gap: 16 }}>
        {SUPPLIERS.map(s => (
          <Card key={s.cnpj} className="card-hover" padding={18}>
            <div style={{ display:"flex", alignItems:"flex-start", justifyContent:"space-between", marginBottom: 14 }}>
              <div className="av" style={{ width: 44, height: 44, fontSize: 14, background: "var(--logo-gradient)" }}>
                {s.name.split(" ").slice(0,2).map(w=>w[0]).join("")}
              </div>
              <span style={{ display:"inline-flex", alignItems:"center", gap: 4, color: "var(--warning)", fontWeight: 700, fontFamily:"Space Grotesk" }}>
                <I name="star" size={12} stroke={2.4}/> {s.score.toFixed(1).replace(".",",")}
              </span>
            </div>
            <div style={{ fontWeight: 600, fontSize: 14 }}>{s.name}</div>
            <div className="text-faint" style={{ fontSize: 11.5, fontFamily:"Space Grotesk" }}>{s.cnpj}</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginTop: 14, paddingTop: 14, borderTop: "1px solid var(--border)" }}>
              <div>
                <div className="text-faint" style={{ fontSize: 10.5, letterSpacing:".06em", fontFamily:"Space Grotesk" }}>PRODUTOS</div>
                <div className="font-display" style={{ fontWeight: 700, fontSize: 15 }}>{s.products}</div>
              </div>
              <div>
                <div className="text-faint" style={{ fontSize: 10.5, letterSpacing:".06em", fontFamily:"Space Grotesk" }}>VOLUME</div>
                <div className="font-display mono-numeric" style={{ fontWeight: 700, fontSize: 15 }}>{brlShort(s.totalBuy)}</div>
              </div>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 14, padding: "10px 12px", background: s.pending > 0 ? "rgba(239,68,68,.06)" : "rgba(34,197,94,.06)", borderRadius: 10 }}>
              <span style={{ fontSize: 12, color: s.pending > 0 ? "#FCA5A5" : "#4ADE80" }}>
                {s.pending > 0 ? "Em aberto" : "Em dia"}
              </span>
              <span className="font-display mono-numeric" style={{ fontWeight: 700, color: s.pending > 0 ? "#FF6A6A" : "#4ADE80" }}>
                {s.pending > 0 ? brl(s.pending) : "✓"}
              </span>
            </div>
          </Card>
        ))}

        <Card padding={18} style={{ border: "1px dashed var(--border-strong)", display:"grid", placeItems:"center", textAlign:"center", color: "var(--fg-3)", cursor:"pointer", minHeight: 220 }}>
          <div>
            <div style={{ width: 44, height: 44, borderRadius: 10, background: "var(--bg-elev)", display:"grid", placeItems:"center", margin:"0 auto 10px" }}>
              <I name="plus" size={20}/>
            </div>
            <div style={{ fontWeight: 600, color: "var(--fg-1)" }}>Adicionar fornecedor</div>
            <div style={{ fontSize: 12 }}>Cadastre uma nova fonte de produtos</div>
          </div>
        </Card>
      </div>
    </div>
  );
}

/* ============================= COMPRAS DE ESTOQUE ============================= */
function StockPurchasesPage() {
  const purchases = [
    { id:"NF-8842", supplier:"Tech Importadora SP", date:"08/05", items: 8, total: 28_400, status:"received", due:"12/05" },
    { id:"NF-8901", supplier:"Tech Importadora SP", date:"11/05", items: 6, total: 18_700, status:"intransit", due:"17/05" },
    { id:"NF-1142", supplier:"Beauty Wholesale BR", date:"09/05", items: 12, total: 14_280, status:"overdue",  due:"14/05" },
    { id:"NF-7711", supplier:"Iluminação Plus",     date:"12/05", items: 4, total:  4_120, status:"pending",  due:"16/05" },
    { id:"NF-3318", supplier:"Distribuidora Eletro", date:"06/05", items: 22, total: 41_800, status:"received", due:"08/05" },
    { id:"NF-9904", supplier:"Gaming Master Ltda",   date:"10/05", items: 5, total: 12_400, status:"intransit",due:"18/05" },
  ];

  const statusMap = {
    received: { l:"Recebido", tone:"success" },
    intransit:{ l:"Em trânsito", tone:"info" },
    pending:  { l:"A pagar", tone:"warning" },
    overdue:  { l:"Atrasado", tone:"danger" },
  };

  return (
    <div className="page fade-in">
      <div className="page-header">
        <div>
          <Eyebrow>Compras</Eyebrow>
          <h1 className="page-title">Compras de estoque</h1>
          <div className="page-sub">Pedidos de reposição e entrada de mercadorias</div>
        </div>
        <div style={{ display:"flex", gap: 10 }}>
          <Btn variant="outline"><I name="filter" size={14}/> Filtros</Btn>
          <Btn variant="primary"><I name="plus" size={14}/> Nova compra</Btn>
        </div>
      </div>

      <div style={{ display:"grid", gridTemplateColumns:"repeat(4,1fr)", gap: 16, marginBottom: 20 }}>
        {[
          { l:"Total comprado (mês)", v: brl(119_700), tone:"orange", icon:"shopping-bag", sub: pct(8.2) },
          { l:"NFs em trânsito",      v: "2",          tone:"info",   icon:"truck", sub:"Chegam até sexta" },
          { l:"A pagar",              v: brl(4_120),   tone:"violet", icon:"clock", sub:"Vence em 4 dias" },
          { l:"Atrasados",            v: brl(14_280),  tone:"danger", icon:"alert-circle", sub:"1 NF" },
        ].map(k => (
          <Card key={k.l} className={`kpi kpi-${k.tone}`} padding={18}>
            <div className="kpi-icon"><I name={k.icon} size={18}/></div>
            <div className="kpi-label">{k.l}</div>
            <div className="kpi-value">{k.v}</div>
            <div className="kpi-delta" style={{ color:"var(--fg-3)", fontWeight: 500 }}>{k.sub}</div>
          </Card>
        ))}
      </div>

      <Card padding={0}>
        <table className="tbl">
          <thead>
            <tr>
              <th>NF</th><th>Fornecedor</th><th>Emissão</th><th>Vencimento</th><th>Itens</th><th>Status</th><th className="num">Total</th><th></th>
            </tr>
          </thead>
          <tbody>
            {purchases.map(p => (
              <tr key={p.id}>
                <td className="font-display" style={{ fontWeight: 600 }}>{p.id}</td>
                <td style={{ fontWeight: 500 }}>{p.supplier}</td>
                <td className="text-muted">{p.date}</td>
                <td className="text-muted">{p.due}</td>
                <td>{p.items} produtos</td>
                <td><Chip tone={statusMap[p.status].tone}>{statusMap[p.status].l}</Chip></td>
                <td className="num mono-numeric font-display" style={{ fontWeight: 700 }}>{brl(p.total)}</td>
                <td className="num"><Btn variant="ghost" size="sm" iconOnly><I name="more-horizontal" size={14}/></Btn></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

window.VendusPagesB = { CashFlowPage, CostsPage, SuppliersPage, StockPurchasesPage };
