// ESTÚDIO — Páginas E: Clientes + CRM Criativo (dados da Agência, portados do Lorenna OS)
(function () {
  const { useState } = React;
  const { PageHead, Card } = window.UI;
  const h = React.createElement;

  const PAG_COR = { pago: "#7FB68C", pendente: "#E89B4C", atrasado: "#C0392B" };
  const PAG_LABEL = { pago: "pago", pendente: "pendente", atrasado: "atrasado" };

  // ══════════════════ CLIENTES ══════════════════
  function Clientes() {
    const [sel, setSel] = useState(null);
    const clientes = window.DEMO_CLIENTS || [];
    return h("div", { className: "page" },
      h(PageHead, { titulo: "Clientes", sub: clientes.length + " contas · Agência Logue · status de pagamento e produção" }),
      h("div", { className: "cli-grid" }, clientes.map((c) => {
        const st = c.pagamento.status_mes;
        return h(Card, { key: c.id, className: "cli-card", onClick: () => setSel(c) },
          h("div", { className: "cli-strip", style: { background: c.cor } }),
          h("div", { className: "cli-body" },
            h("div", { className: "cli-head" },
              h("div", { className: "cli-avatar", style: { background: c.cor + "33", color: c.cor } }, c.nome[0]),
              h("div", { className: "grow" }, h("h3", { className: "cli-nome" }, c.nome), h("div", { className: "cli-setor" }, c.setor)),
              h("span", { className: "status-pill", style: { background: PAG_COR[st] + "22", color: PAG_COR[st] } }, PAG_LABEL[st])
            ),
            h("div", { className: "cli-row" }, h("span", null, "💰 R$ " + c.receita + "/mês"), h("span", null, "📅 vence dia " + c.pagamento.dia)),
            h("div", { className: "cli-pacote" }, c.pacote),
            h("div", { className: "cli-prox" }, h("div", { className: "mini-label", style: { margin: "0 0 6px" } }, "Próximas ações"),
              h("ul", { className: "cli-list" }, c.proximas.slice(0, 3).map((p, i) => h("li", { key: i }, h("span", { className: "cap-arrow" }, "→"), p)))
            ),
            c.influencers && h("div", { className: "cli-inf" }, (c.pendentes || 0) + " tarefa(s) pendente(s) · " + c.influencers.filter((x) => !x.vazio).length + " influencers na semana")
          )
        );
      })),
      sel && h(CliModal, { c: sel, onClose: () => setSel(null) })
    );
  }

  function CliModal({ c, onClose }) {
    return h("div", { className: "modal-bg", onClick: onClose },
      h("div", { className: "modal", onClick: (e) => e.stopPropagation() },
        h("button", { className: "modal-x", onClick: onClose }, "✕"),
        h("div", { className: "modal-tags" }, h("span", { className: "cli-avatar sm", style: { background: c.cor + "33", color: c.cor } }, c.nome[0])),
        h("h2", { className: "modal-title" }, c.nome),
        h("div", { className: "modal-sub" }, c.setor, " · cliente desde ", c.inicio),
        h("div", { className: "modal-grid" },
          h("div", { className: "mstat" }, h("span", null, "Contrato"), h("b", null, "R$ " + c.contrato.valor)),
          h("div", { className: "mstat" }, h("span", null, "Prazo"), h("b", null, c.contrato.prazo)),
          h("div", { className: "mstat" }, h("span", null, "Pagamento"), h("b", { style: { color: PAG_COR[c.pagamento.status_mes] } }, PAG_LABEL[c.pagamento.status_mes]))
        ),
        h("div", { className: "msec" }, h("div", { className: "msec-t" }, "Histórico de pagamento"),
          c.pagamento.historico.map((p, i) => h("div", { key: i, className: "pay-row" },
            h("span", null, p.mes), h("span", { className: "pay-val" }, "R$ " + p.valor), h("span", { className: "status-pill", style: { background: PAG_COR[p.status] + "22", color: PAG_COR[p.status] } }, PAG_LABEL[p.status]), h("span", { className: "pay-date" }, p.data)
          ))
        ),
        c.influencers && h("div", { className: "msec" }, h("div", { className: "msec-t" }, "Agenda de influencers"),
          h("div", { className: "inf-grid" }, c.influencers.map((x, i) => h("div", { key: i, className: "inf-cell" + (x.vazio ? " inf-empty" : "") },
            h("div", { className: "inf-dia" }, x.dia), x.vazio ? h("div", { className: "inf-livre" }, "livre") : h("div", null, h("div", { className: "inf-nome" }, x.nome), h("div", { className: "inf-tipo" }, x.tipo))
          )))
        ),
        h("div", { className: "msec" }, h("div", { className: "msec-t" }, "Tarefas"),
          c.tarefas.map((t) => h("div", { key: t.id, className: "chk-row" }, h("span", { className: "chk-box" + (t.status === "concluida" ? " chk-on" : "") }), t.titulo, h("span", { className: "cli-deadline" }, t.deadline)))
        ),
        c.insights && h("div", { className: "msec" }, h("div", { className: "msec-t" }, "💡 Insights de conteúdo"),
          c.insights.map((ins, i) => h("div", { key: i, className: "ins-card" },
            h("div", { className: "ins-top" }, h("b", null, ins.titulo), h("span", { className: "ins-custo" }, ins.custo)),
            h("p", null, ins.ideia)
          ))
        )
      )
    );
  }

  // ══════════════════ CRM CRIATIVO ══════════════════
  const CRM_COLS = [["potencial", "Potencial", "#908F8E"], ["em_contato", "Em contato", "#A89AC9"], ["negociando", "Negociando", "#E89B4C"], ["fechado", "Fechado", "#7FB68C"]];
  function CRM() {
    const [map, setMap] = useState(() => Object.fromEntries((window.DEMO_CRM || []).map((x) => [x.id, x.status])));
    const [drag, setDrag] = useState(null);
    const [over, setOver] = useState(null);
    const all = window.DEMO_CRM || [];
    function setStatus(id, s) { setMap((m) => ({ ...m, [id]: s })); }
    const tipoIc = { marca: "🏷️", influencer: "⭐", collab: "🤝" };
    return h("div", { className: "page" },
      h(PageHead, { titulo: "CRM Criativo", sub: "Marcas, collabs e parcerias — arraste pelo funil" }),
      h("div", { className: "pauta-board crm-board" }, CRM_COLS.map(([st, label, cor]) => {
        const inCol = all.filter((x) => map[x.id] === st);
        return h("div", {
          key: st, className: "pb-col" + (over === st ? " kb-over" : ""),
          onDragOver: (e) => { e.preventDefault(); setOver(st); },
          onDragLeave: () => setOver((o) => (o === st ? null : o)),
          onDrop: () => { if (drag) setStatus(drag, st); setDrag(null); setOver(null); },
        },
          h("div", { className: "pb-col-head", style: { borderTopColor: cor } }, h("span", { className: "pb-col-name" }, label), h("span", { className: "kb-count" }, inCol.length)),
          h("div", { className: "pb-col-body" }, inCol.map((x) => h("div", {
            key: x.id, className: "pb-card" + (drag === x.id ? " kb-dragging" : ""), draggable: true,
            onDragStart: () => setDrag(x.id), onDragEnd: () => { setDrag(null); setOver(null); }, style: { background: cor + "14", borderColor: cor + "55" },
          },
            h("div", { className: "pb-top" }, h("span", null, tipoIc[x.tipo] || "•"), h("span", { className: "crm-nome" }, x.nome), x.valor && h("span", { className: "crm-valor" }, "R$ " + x.valor)),
            h("div", { className: "pb-title" }, x.proposta),
            h("div", { className: "crm-prox" }, "→ " + x.proxima),
            x.followup && h("div", { className: "crm-follow" }, "⏰ follow-up " + x.followup)
          )))
        );
      }))
    );
  }

  // ══════════════════ MONETIZAÇÃO ══════════════════
  function Monetizacao() {
    const streams = window.DATA.monetStreams;
    const cats = window.DATA.monetCats;
    const pool = window.DATA.monetPool;
    const [ideias, setIdeias] = useState(() => pool.slice(0, 3));
    const totAtual = streams.reduce((s, x) => s + x.atual, 0);
    const totMeta = streams.reduce((s, x) => s + x.meta, 0);
    function sortear() { setIdeias([...pool].sort(() => Math.random() - 0.5).slice(0, 3)); }
    return h("div", { className: "page" },
      h(PageHead, {
        titulo: "Monetização", sub: "R$ " + totAtual.toLocaleString("pt-BR") + " atual · meta R$ " + totMeta.toLocaleString("pt-BR") + "/mês",
        right: h("button", { className: "btn-pink", onClick: sortear }, "✨ Ideias de hoje")
      }),
      h("div", { className: "monet-hoje" },
        h("div", { className: "mini-label" }, "⚡ Pra monetizar hoje — 3 ações rápidas"),
        h("div", { className: "monet-ideias" }, ideias.map((idea, i) => h("div", { key: i, className: "monet-idea" },
          h("div", { className: "monet-cat" }, (cats[idea.cat] || {}).emoji, " ", (cats[idea.cat] || {}).label),
          h("p", { className: "monet-desc" }, idea.desc),
          h("div", { className: "monet-meta" }, h("span", { className: "badge-pink" }, idea.plataforma), h("span", { className: "monet-tempo" }, "⏱ " + idea.tempo))
        )))
      ),
      h("div", { className: "mini-label" }, "Fontes de renda"),
      h("div", { className: "monet-grid" }, streams.map((s) => {
        const pct = Math.min(100, Math.round((s.atual / s.meta) * 100));
        return h(Card, { key: s.id, className: "monet-card" },
          h("div", { className: "monet-card-head" }, h("span", { className: "monet-ic", style: { background: s.cor + "22" } }, s.icon), h("b", null, s.nome)),
          h("p", { className: "monet-card-desc" }, s.descricao),
          h("div", { className: "monet-canais" }, s.canais.map((c) => h("span", { key: c, className: "monet-canal" }, c))),
          h("div", { className: "monet-bar-top" }, h("span", null, "R$ " + s.atual.toLocaleString("pt-BR") + " / " + s.meta.toLocaleString("pt-BR")), h("span", { style: { color: s.cor, fontWeight: 700 } }, pct + "%")),
          h("div", { className: "monet-bar" }, h("div", { className: "monet-bar-fill", style: { width: pct + "%", background: s.cor } })),
          h("div", { className: "monet-tipo" }, s.tipo)
        );
      }))
    );
  }

  Object.assign(window, { Clientes, CRM, Monetizacao });
})();
