// ─────────────────────────────────────────────────────────────
// ÁREA DO CRIADOR — Gerador de Tokens  (acesso só pelo caminho /admin)
// Simples como o original: senha → gerar → lista verde/vermelho.
// Conversa com tokens_api.php (senha validada NO SERVIDOR — nunca no app).
// Mesmo banco do burn_token.php (tokens_db.txt / usados.txt).
// ─────────────────────────────────────────────────────────────

const { useState: useStateAdmin } = React;

// link bonito que você compartilha: .../comportamentos/analise/TOKEN
function linkDoToken(tk) {
  return `${location.origin}/comportamentos/analise/${encodeURIComponent(tk)}`;
}

// gerador local (só pra pré-visualização sem servidor)
function tokenLocalDemo(prefix) {
  const b = new Uint8Array(6);
  (window.crypto || window.msCrypto).getRandomValues(b);
  const hex = [...b].map((x) => x.toString(16).padStart(2, "0")).join("").toUpperCase();
  return (prefix ? prefix + "_" : "") + hex;
}

function AdminScreen({ t, onBack }) {
  const [auth, setAuth] = useStateAdmin(false);
  const [senha, setSenha] = useStateAdmin("");
  const [prefix, setPrefix] = useStateAdmin("");
  const [qty, setQty] = useStateAdmin(1);
  const [tokens, setTokens] = useStateAdmin([]); // [{token, used}]
  const [busy, setBusy] = useStateAdmin(false);
  const [erro, setErro] = useStateAdmin(null);
  const [demo, setDemo] = useStateAdmin(false);
  const [copied, setCopied] = useStateAdmin(null);
  const [stats, setStats] = useStateAdmin(null); // {totais, por_dia}
  const [leads, setLeads] = useStateAdmin([]);

  const API = "tokens_api.php";

  // entrar: valida senha no servidor e já traz a lista (verde/vermelho)
  const entrar = async (e) => {
    e && e.preventDefault();
    if (!senha.trim()) { setErro("Digite a senha."); return; }
    setBusy(true); setErro(null);
    try {
      const r = await fetch(API, {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ senha, action: "list" }),
      });
      const data = await r.json();
      if (!r.ok || data.status !== "success") { setErro(data.message || "Senha incorreta."); setBusy(false); return; }
      setTokens(data.tokens || []); setAuth(true); setDemo(false);
      buscarStats(); buscarLeads();
    } catch (err) {
      // sem servidor (preview): entra em modo demonstração
      setAuth(true); setDemo(true); setTokens([]);
    } finally { setBusy(false); }
  };

  const gerar = async () => {
    const n = Math.max(1, Math.min(100, parseInt(qty, 10) || 1));
    setBusy(true); setErro(null);
    try {
      const r = await fetch(API, {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ senha, action: "generate", prefix: prefix.trim(), quantity: n }),
      });
      const data = await r.json();
      if (!r.ok || data.status !== "success") { setErro(data.message || "Erro ao gerar."); setBusy(false); return; }
      setTokens(data.tokens || []);
    } catch (err) {
      // preview: gera localmente só pra demonstração
      const novos = Array.from({ length: n }, () => ({ token: tokenLocalDemo(prefix.trim()), used: false }));
      setTokens((prev) => [...novos, ...prev]); setDemo(true);
    } finally { setBusy(false); }
  };

  const buscarLeads = async () => {
    try {
      const r = await fetch("leads.php", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ senha, action: "list" }),
      });
      const data = await r.json();
      if (r.ok && data.status === "success") setLeads(data.leads || []);
    } catch (e) {}
  };

  const buscarStats = async () => {
    try {
      const r = await fetch("eventos.php", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ senha, action: "stats" }),
      });
      const data = await r.json();
      if (r.ok && data.status === "success") setStats({ totais: data.totais || {}, por_dia: data.por_dia || {} });
    } catch (e) {}
  };

  const atualizar = async () => {
    setBusy(true); setErro(null);
    buscarStats(); buscarLeads();
    try {
      const r = await fetch(API, {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ senha, action: "list" }),
      });
      const data = await r.json();
      if (r.ok && data.status === "success") setTokens(data.tokens || []);
    } catch (err) {} finally { setBusy(false); }
  };

  const copiar = async (texto, id) => {
    try { await navigator.clipboard.writeText(texto); }
    catch {
      const ta = document.createElement("textarea");
      ta.value = texto; document.body.appendChild(ta); ta.select();
      document.execCommand("copy"); ta.remove();
    }
    setCopied(id); setTimeout(() => setCopied(null), 1500);
  };

  const lbl = {
    fontFamily: TYPE.sans, fontSize: 9.5, color: t.ink3,
    letterSpacing: "0.18em", textTransform: "uppercase", fontWeight: 700, marginBottom: 8,
  };
  const inp = {
    width: "100%", padding: "13px 15px", boxSizing: "border-box",
    background: t.bg0, border: `1px solid ${t.border}`, borderRadius: RADIUS.md,
    color: t.ink1, fontFamily: TYPE.sans, fontSize: 14, fontWeight: 600, outline: "none",
  };

  return (
    <div style={{
      position: "absolute", inset: 0, background: t.bg0, color: t.ink1,
      paddingTop: 56, paddingBottom: 40, overflowY: "auto", overflowX: "hidden",
      WebkitOverflowScrolling: "touch",
    }}>
      {/* TOPO */}
      <div style={{
        position: "sticky", top: 0, zIndex: 20, background: t.bg0,
        backdropFilter: "blur(20px)", WebkitBackdropFilter: "blur(20px)",
        padding: "10px 14px 12px", borderBottom: `1px solid ${t.border}`,
        display: "flex", alignItems: "center", gap: 12, boxShadow: `0 6px 16px ${t.bg0}`,
      }}>
        <button onClick={onBack} style={{
          flexShrink: 0, width: 38, height: 38, borderRadius: 999,
          background: t.bg1, border: `1px solid ${t.border}`,
          display: "flex", alignItems: "center", justifyContent: "center",
          color: t.ink2, cursor: "pointer",
        }}>
          <Icon name="back" size={16} stroke="currentColor" />
        </button>
        <span style={{
          fontFamily: TYPE.sans, fontSize: 10, color: t.ink3,
          letterSpacing: "0.18em", textTransform: "uppercase", fontWeight: 700, flex: 1,
        }}>Área do Criador</span>
        {auth && (
          <button onClick={atualizar} disabled={busy} title="Atualizar status" style={{
            flexShrink: 0, background: "transparent", border: "none", cursor: "pointer",
            color: t.ink3, fontFamily: TYPE.sans, fontSize: 10, fontWeight: 700,
            letterSpacing: "0.12em", textTransform: "uppercase",
          }}>Atualizar</button>
        )}
      </div>

      {/* ── LOGIN ── */}
      {!auth && (
        <div style={{ padding: "40px 24px 0", maxWidth: 360, margin: "0 auto" }}>
          <h1 style={{
            fontFamily: TYPE.display, fontSize: 44, lineHeight: 0.95, color: t.ink1,
            letterSpacing: "-0.015em", margin: "0 0 18px", textTransform: "uppercase", textAlign: "center",
          }}>Acesso<br/>restrito</h1>
          <form onSubmit={entrar} style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <input type="password" value={senha} onChange={(e) => setSenha(e.target.value)}
              placeholder="Senha de admin" autoComplete="off" style={{ ...inp, textAlign: "center" }} />
            <button type="submit" disabled={busy} style={{
              width: "100%", padding: "16px", background: t.ink1, color: t.bg0, border: "none",
              borderRadius: RADIUS.md, cursor: busy ? "default" : "pointer", opacity: busy ? 0.6 : 1,
              fontFamily: TYPE.sans, fontSize: 14, fontWeight: 800, letterSpacing: "0.12em", textTransform: "uppercase",
            }}>{busy ? "Entrando..." : "Entrar"}</button>
          </form>
          {erro && <div style={{
            marginTop: 14, padding: "12px 14px", borderRadius: RADIUS.md,
            border: `1px solid ${t.danger}`, color: t.danger,
            fontFamily: TYPE.sans, fontSize: 12.5, lineHeight: 1.5, textAlign: "center",
          }}>{erro}</div>}
        </div>
      )}

      {/* ── GERADOR ── */}
      {auth && (
        <div>
          <div style={{ padding: "20px 20px 6px" }}>
            <h1 style={{
              fontFamily: TYPE.display, fontSize: 40, lineHeight: 0.92, color: t.ink1,
              letterSpacing: "-0.015em", margin: 0, textTransform: "uppercase",
            }}>Gerador<br/>de tokens</h1>
          </div>

          {/* MÉTRICAS — resumo do funil (grátis, do seu servidor) */}
          {stats && (
            <div style={{ padding: "10px 16px 4px" }}>
              <div style={{ ...lbl, padding: "0 4px 4px" }}>Funil (total)</div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                {[
                  ["Iniciaram", stats.totais.iniciou || 0],
                  ["Concluíram", stats.totais.concluiu || 0],
                  ["Clic. consulta", stats.totais.clicou_consulta || 0],
                  ["Compartilharam", stats.totais.compartilhou || 0],
                ].map(([nome, val], i) => (
                  <div key={i} style={{
                    background: t.bg1, border: `1px solid ${t.border}`, borderRadius: RADIUS.md, padding: "12px 14px",
                  }}>
                    <div style={{ fontFamily: TYPE.display, fontSize: 30, color: t.ink1, lineHeight: 1 }}>{val}</div>
                    <div style={{ fontFamily: TYPE.sans, fontSize: 9.5, color: t.ink3, letterSpacing: "0.1em", textTransform: "uppercase", fontWeight: 700, marginTop: 4 }}>{nome}</div>
                  </div>
                ))}
              </div>
              {(() => {
                const ini = stats.totais.iniciou || 0;
                const con = stats.totais.clicou_consulta || 0;
                const tx = ini ? Math.round((con / ini) * 100) : 0;
                return (
                  <div style={{
                    marginTop: 8, padding: "12px 14px", background: t.bg1,
                    border: `1px solid ${t.border}`, borderRadius: RADIUS.md,
                    display: "flex", alignItems: "baseline", justifyContent: "space-between",
                  }}>
                    <span style={{ fontFamily: TYPE.sans, fontSize: 10, color: t.ink3, letterSpacing: "0.1em", textTransform: "uppercase", fontWeight: 700 }}>Conversão p/ consulta</span>
                    <span style={{ fontFamily: TYPE.display, fontSize: 26, color: t.accent }}>{tx}%</span>
                  </div>
                );
              })()}

              {/* GRÁFICO — análises por dia (últimos 14 dias) */}
              <DailyChart t={t} porDia={stats.por_dia} />
            </div>
          )}

          {/* FORM */}
          <div style={{ margin: "12px 16px", padding: "16px 18px", background: t.bg1, border: `1px solid ${t.border}`, borderRadius: RADIUS.lg }}>
            <div style={{ display: "flex", gap: 12 }}>
              <div style={{ flex: 2 }}>
                <div style={lbl}>Prefixo (opcional)</div>
                <input value={prefix} onChange={(e) => setPrefix(e.target.value)} placeholder="Ex: INSTA" style={inp} />
              </div>
              <div style={{ flex: 1 }}>
                <div style={lbl}>Qtd</div>
                <input type="number" min="1" max="100" value={qty} onChange={(e) => setQty(e.target.value)} style={inp} />
              </div>
            </div>
            <button onClick={gerar} disabled={busy} style={{
              marginTop: 16, width: "100%", padding: "15px",
              background: t.ink1, color: t.bg0, border: "none", borderRadius: RADIUS.md,
              cursor: busy ? "default" : "pointer", opacity: busy ? 0.6 : 1,
              fontFamily: TYPE.sans, fontSize: 14, fontWeight: 800, letterSpacing: "0.1em", textTransform: "uppercase",
            }}>{busy ? "Gerando..." : "Gerar tokens"}</button>
            {erro && <div style={{ marginTop: 12, color: t.danger, fontFamily: TYPE.sans, fontSize: 12 }}>{erro}</div>}
            {demo && <div style={{ marginTop: 12, color: t.ink3, fontFamily: TYPE.sans, fontSize: 11, lineHeight: 1.5 }}>
              Pré-visualização (sem servidor). Na Hostinger os tokens são salvos no banco e o status fica real.
            </div>}
          </div>

          {/* LISTA VERDE / VERMELHO */}
          {tokens.length > 0 && (
            <div style={{ padding: "0 16px 8px", display: "flex", flexDirection: "column", gap: 8 }}>
              {tokens.map((row, i) => {
                const link = linkDoToken(row.token);
                const cor = row.used ? "#ef4444" : "#22c55e";
                return (
                  <div key={i} style={{ background: t.bg1, border: `1px solid ${t.border}`, borderRadius: RADIUS.md, padding: "12px 14px" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                      <span style={{ width: 8, height: 8, borderRadius: 999, background: cor, flexShrink: 0 }}></span>
                      <span style={{
                        fontFamily: TYPE.mono, fontSize: 12.5, color: cor, wordBreak: "break-all",
                        textDecoration: row.used ? "line-through" : "none",
                      }}>{row.token}{row.used ? "  (USADO)" : ""}</span>
                    </div>
                    <div style={{ fontFamily: TYPE.mono, fontSize: 10, color: t.ink4, wordBreak: "break-all", marginBottom: 10 }}>{link}</div>
                    <div style={{ display: "flex", gap: 8 }}>
                      <button onClick={() => copiar(link, "l" + i)} style={adminMiniBtn(t, copied === "l" + i)}>
                        {copied === "l" + i ? "Copiado!" : "Copiar link"}
                      </button>
                      <button onClick={() => copiar(row.token, "t" + i)} style={adminMiniBtn(t, copied === "t" + i, true)}>
                        {copied === "t" + i ? "Copiado!" : "Só o código"}
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          )}

          {/* LEADS — contatos deixados no final da análise */}
          {leads.length > 0 && (
            <div style={{ padding: "12px 16px 24px" }}>
              <div style={{ ...lbl, padding: "0 4px 6px" }}>Contatos recebidos ({leads.length})</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {leads.map((ld, i) => {
                  const num = (ld.whatsapp || "").replace(/\D/g, "").replace(/^55/, "");
                  const msg = encodeURIComponent("Olá! Aqui é o Dr. Ulisses Nakagawa. Vi que você fez a Análise de Comportamento. Quer agendar uma consulta para alcançar os seus objetivos?");
                  return (
                  <a key={i}
                    href={`https://wa.me/55${num}?text=${msg}`}
                    target="_blank" rel="noreferrer"
                    style={{
                      display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10,
                      background: t.bg1, border: `1px solid ${t.border}`, borderRadius: RADIUS.md,
                      padding: "12px 14px", textDecoration: "none",
                    }}>
                    <span style={{ minWidth: 0 }}>
                      <span style={{ display: "block", fontFamily: TYPE.sans, fontSize: 14, fontWeight: 700, color: t.ink1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{ld.nome}</span>
                      <span style={{ display: "block", fontFamily: TYPE.mono, fontSize: 11, color: t.ink3, marginTop: 2 }}>{ld.whatsapp} · {ld.data}</span>
                    </span>
                    <span style={{ flexShrink: 0, color: t.accent }}>
                      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>
                    </span>
                  </a>
                  );
                })}
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function adminMiniBtn(t, active, ghost) {
  return {
    flex: 1, padding: "10px 8px", borderRadius: RADIUS.sm, cursor: "pointer",
    border: `1px solid ${active ? t.ink1 : t.border}`,
    background: ghost ? "transparent" : (active ? t.ink1 : t.bg2),
    color: ghost ? t.ink2 : (active ? t.bg0 : t.ink1),
    fontFamily: TYPE.sans, fontSize: 11, fontWeight: 700,
    letterSpacing: "0.06em", textTransform: "uppercase",
  };
}

// ── Gráfico de barras: análises iniciadas por dia (últimos 14 dias) ──
function DailyChart({ t, porDia }) {
  const dias = [];
  const hoje = new Date();
  for (let i = 13; i >= 0; i--) {
    const d = new Date(hoje); d.setDate(d.getDate() - i);
    const iso = d.toISOString().slice(0, 10);
    const v = (porDia && porDia[iso] && porDia[iso].iniciou) || 0;
    dias.push({ iso, v, dia: iso.slice(8, 10) });
  }
  const max = Math.max(1, ...dias.map((x) => x.v));
  return (
    <div style={{
      marginTop: 8, padding: "14px 14px 10px", background: t.bg1,
      border: `1px solid ${t.border}`, borderRadius: RADIUS.md,
    }}>
      <div style={{ fontFamily: TYPE.sans, fontSize: 9.5, color: t.ink3, letterSpacing: "0.14em", textTransform: "uppercase", fontWeight: 700, marginBottom: 12 }}>Análises por dia · 14 dias</div>
      <div style={{ display: "flex", alignItems: "flex-end", gap: 4, height: 90 }}>
        {dias.map((d, i) => (
          <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
            <div style={{ fontFamily: TYPE.sans, fontSize: 9, color: d.v ? t.ink2 : t.ink4, fontWeight: 700 }}>{d.v || ""}</div>
            <div style={{
              width: "100%", height: Math.max(3, Math.round((d.v / max) * 64)),
              background: d.v ? t.accent : t.bg2, borderRadius: 3,
              transition: "height .3s ease",
            }}></div>
            <div style={{ fontFamily: TYPE.mono, fontSize: 8.5, color: t.ink4 }}>{d.dia}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { AdminScreen });
