"use client";

import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { ArrowLeft, PackagePlus, Pencil, Radio, RotateCw, Sparkles, Trash2 } from "lucide-react";

import type { CompraDeLiveNoOwner, PacoteDeLive, PainelDaLive } from "@/lib/live-owner";

import {
  BOTAO_PRIMARIO,
  BOTAO_SECUNDARIO,
  CLASSE_DO_CAMPO,
  Campo,
  dataEHora,
  decimalDoCampo,
  decimalParaCampo,
  Interruptor,
  Modal,
  moeda,
  pedir,
  plural,
  Recado,
  Selo,
  type Tom,
} from "../notas-fiscais/ui";

type Aba = "geral" | "pacotes" | "compras" | "uso" | "regras";

type Rascunho = { id: string | null; nome: string; descricao: string; lives: string; pessoas: string; preco: string; ordem: string; ativo: boolean; destaque: boolean };

const VAZIO: Rascunho = { id: null, nome: "", descricao: "", lives: "", pessoas: "", preco: "", ordem: "0", ativo: true, destaque: false };

const STATUS: Record<string, { rotulo: string; tom: Tom }> = {
  pendente: { rotulo: "Aguardando", tom: "violeta" },
  aprovada: { rotulo: "Paga", tom: "verde" },
  recusada: { rotulo: "Recusada", tom: "vermelho" },
  cancelada: { rotulo: "Cancelada", tom: "cinza" },
  reembolsada: { rotulo: "Reembolsada", tom: "cinza" },
  contestada: { rotulo: "Contestada", tom: "vermelho" },
};

/* Quanto a live custa na Cloudflare: ~1,5 Mbps por pessoa, US$ 0,05/GB depois de 1.000 GB grátis no mês. */
function custo(pessoas: number, minutos = 90, dolar = 5.5) {
  const gb = (pessoas * 1.5 * 1_000_000 * minutos * 60) / 8 / 1_000_000_000;
  return { gb, reais: gb * 0.05 * dolar };
}

function corpoDoPacote(r: Rascunho | PacoteDeLive) {
  return {
    nome: r.nome,
    descricao: r.descricao,
    lives: Number(r.lives),
    pessoas: Number(r.pessoas),
    preco: typeof r.preco === "number" ? r.preco : decimalDoCampo(r.preco),
    ordem: Number(r.ordem) || 0,
    ativo: r.ativo,
    destaque: r.destaque,
  };
}

export default function PainelDaLiveNoOwner({ inicial, erroInicial }: { inicial: PainelDaLive | null; erroInicial: string | null }) {
  const [painel, setPainel] = useState<PainelDaLive | null>(inicial);
  const [erro, setErro] = useState<string | null>(erroInicial);
  const [carregando, setCarregando] = useState(false);
  const [aba, setAba] = useState<Aba>("geral");
  const [aviso, setAviso] = useState<{ tom: "ok" | "erro"; texto: string; id: number } | null>(null);

  const avisar = useCallback((tom: "ok" | "erro", texto: string) => setAviso({ tom, texto, id: Date.now() }), []);

  useEffect(() => {
    if (!aviso) return;
    const t = window.setTimeout(() => setAviso(null), aviso.tom === "erro" ? 6000 : 3500);
    return () => window.clearTimeout(t);
  }, [aviso]);

  const atualizar = useCallback(async () => {
    setCarregando(true);
    try {
      setPainel(await pedir<PainelDaLive>("/api/live"));
      setErro(null);
    } catch (falha) {
      setErro(falha instanceof Error ? falha.message : "Não foi possível carregar.");
    } finally {
      setCarregando(false);
    }
  }, []);

  const abas: Array<{ chave: Aba; rotulo: string; contagem?: number }> = [
    { chave: "geral", rotulo: "Visão geral" },
    { chave: "pacotes", rotulo: "Pacotes", contagem: painel?.pacotes.length },
    { chave: "compras", rotulo: "Compras", contagem: painel?.compras.filter((c) => c.status === "pendente").length || undefined },
    { chave: "uso", rotulo: "Lives feitas", contagem: painel?.numeros.livesNoMes },
    { chave: "regras", rotulo: "Regras" },
  ];

  return (
    <div className="min-h-screen bg-slate-50/50 p-4 font-sans sm:p-8 lg:p-10">
      <div className="mx-auto max-w-[1180px]">
        <div className="flex flex-wrap items-end justify-between gap-4">
          <div className="min-w-0">
            <Link href="/" className="inline-flex items-center gap-2 text-sm font-medium text-slate-500 hover:text-slate-900">
              <ArrowLeft size={16} />
              Voltar ao painel
            </Link>
            <h1 className="mt-3 flex items-center gap-2 text-2xl font-semibold tracking-tight text-slate-900">
              <Radio size={22} className="text-rose-500" /> KtaloguLive
            </h1>
            <p className="mt-1 max-w-2xl text-sm text-slate-500">
              As lives grátis de cada mês, os pacotes que as empresas compram em Assinatura → Produtos Digitais (no seu Mercado Pago, o mesmo das notas) e o
              que já foi usado.
            </p>
          </div>
          <button
            type="button"
            onClick={() => void atualizar()}
            disabled={carregando}
            className="inline-flex h-11 items-center gap-2 rounded-xl border border-slate-200 bg-white px-4 text-sm font-medium text-slate-700 shadow-sm transition hover:bg-slate-50 disabled:opacity-60"
          >
            <RotateCw size={15} className={carregando ? "animate-spin" : ""} />
            {carregando ? "Atualizando…" : "Atualizar"}
          </button>
        </div>

        <div className="mt-6 flex gap-1 overflow-x-auto border-b border-slate-200" role="tablist">
          {abas.map((item) => (
            <button
              key={item.chave}
              type="button"
              role="tab"
              aria-selected={aba === item.chave}
              onClick={() => setAba(item.chave)}
              className={`-mb-px inline-flex h-11 shrink-0 items-center gap-2 border-b-2 px-3 text-sm font-medium transition ${
                aba === item.chave ? "border-slate-900 text-slate-900" : "border-transparent text-slate-500 hover:text-slate-800"
              }`}
            >
              {item.rotulo}
              {typeof item.contagem === "number" ? (
                <span className={`rounded-full px-1.5 py-0.5 text-[11px] font-semibold tabular-nums ${aba === item.chave ? "bg-slate-900 text-white" : "bg-slate-100 text-slate-600"}`}>
                  {item.contagem}
                </span>
              ) : null}
            </button>
          ))}
        </div>

        <div className="mt-6">
          {erro ? (
            <div className="mb-4">
              <Recado tom="erro">{erro}</Recado>
            </div>
          ) : null}
          {painel ? (
            <div className={carregando ? "opacity-60" : ""}>
              {aba === "geral" ? <VisaoGeral painel={painel} irPara={setAba} /> : null}
              {aba === "pacotes" ? <Pacotes painel={painel} aoMudar={atualizar} avisar={avisar} /> : null}
              {aba === "compras" ? <Compras compras={painel.compras} /> : null}
              {aba === "uso" ? <Uso painel={painel} /> : null}
              {aba === "regras" ? <Regras painel={painel} aoMudar={atualizar} avisar={avisar} /> : null}
            </div>
          ) : null}
        </div>
      </div>

      {aviso ? (
        <div className="pointer-events-none fixed inset-x-0 bottom-6 z-[60] flex justify-center px-4" role="status">
          <div key={aviso.id} className={`pointer-events-auto rounded-xl px-4 py-3 text-sm font-medium shadow-lg ${aviso.tom === "erro" ? "bg-rose-600 text-white" : "bg-slate-900 text-white"}`}>
            {aviso.texto}
          </div>
        </div>
      ) : null}
    </div>
  );
}

function Numero({ rotulo, valor, detalhe }: { rotulo: string; valor: string; detalhe?: string }) {
  return (
    <div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
      <p className="text-[11px] font-semibold uppercase tracking-wider text-slate-500">{rotulo}</p>
      <p className="mt-1 text-2xl font-semibold tabular-nums text-slate-900">{valor}</p>
      {detalhe ? <p className="mt-0.5 text-xs text-slate-500">{detalhe}</p> : null}
    </div>
  );
}

function VisaoGeral({ painel, irPara }: { painel: PainelDaLive; irPara: (aba: Aba) => void }) {
  const { numeros, regras } = painel;
  const gratis = custo(regras.gratis_pessoas);
  return (
    <div className="grid gap-4">
      {!regras.vendas_abertas ? <Recado tom="atencao">A venda de pacotes está pausada nas Regras: ninguém consegue comprar agora.</Recado> : null}
      {painel.pacotes.filter((p) => p.ativo).length === 0 ? (
        <Recado tom="atencao">
          Nenhum pacote à venda: as empresas só têm as lives grátis do mês.{" "}
          <button type="button" className="font-semibold underline" onClick={() => irPara("pacotes")}>
            Criar pacote
          </button>
        </Recado>
      ) : null}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <Numero rotulo="Ao vivo agora" valor={String(numeros.aoVivoAgora)} />
        <Numero rotulo="Lives neste mês" valor={String(numeros.livesNoMes)} detalhe={`${numeros.gratisNoMes} grátis · ${numeros.livesNoMes - numeros.gratisNoMes} de pacote`} />
        <Numero rotulo="Empresas que fizeram live" valor={String(numeros.empresasQueUsaram)} detalhe="neste mês" />
        <Numero rotulo="Pacotes vendidos no mês" valor={moeda(numeros.receitaNoMes)} detalhe="no seu Mercado Pago" />
      </div>
      <div className="rounded-2xl border border-slate-200 bg-white px-5 py-4 text-sm leading-6 text-slate-600 shadow-sm">
        <p className="font-semibold text-slate-900">Quanto custa uma live para você (Cloudflare Realtime)</p>
        <p className="mt-1">
          Cada pessoa assistindo usa uns 1,5 Mbps. A Cloudflare cobra US$ 0,05 por GB, depois de 1.000 GB grátis por mês somando todas as lives. Uma live
          grátis de 1h30 com {regras.gratis_pessoas} pessoas usa ~{gratis.gb.toFixed(0)} GB, cerca de <strong className="text-slate-900">{moeda(gratis.reais)}</strong>{" "}
          quando passa do grátis (dólar a R$ 5,50). Os pacotes mostram a margem de cada um.
        </p>
      </div>
    </div>
  );
}

function Pacotes({ painel, aoMudar, avisar }: { painel: PainelDaLive; aoMudar: () => Promise<void>; avisar: (tom: "ok" | "erro", texto: string) => void }) {
  const [rascunho, setRascunho] = useState<Rascunho | null>(null);
  const [salvando, setSalvando] = useState(false);
  const [erroDoForm, setErroDoForm] = useState<string | null>(null);
  const [excluindo, setExcluindo] = useState<PacoteDeLive | null>(null);
  const [ocupado, setOcupado] = useState("");

  const abrir = (p: PacoteDeLive | null) => {
    setErroDoForm(null);
    setRascunho(
      p
        ? { id: p.id, nome: p.nome, descricao: p.descricao ?? "", lives: String(p.lives), pessoas: String(p.pessoas), preco: decimalParaCampo(p.preco), ordem: String(p.ordem), ativo: p.ativo, destaque: p.destaque }
        : { ...VAZIO, ordem: String(painel.pacotes.length) },
    );
  };

  const salvar = async () => {
    if (!rascunho) return;
    const corpo = corpoDoPacote(rascunho);
    if (rascunho.nome.trim().length < 2) return setErroDoForm("Dê um nome ao pacote.");
    if (!Number.isInteger(corpo.lives) || corpo.lives < 1) return setErroDoForm("Quantas lives o pacote libera?");
    if (!Number.isInteger(corpo.pessoas) || corpo.pessoas < 1) return setErroDoForm("Quantas pessoas cabem em cada live?");
    if (!Number.isFinite(corpo.preco) || corpo.preco < 1) return setErroDoForm("O preço precisa ser de pelo menos R$ 1,00.");
    setSalvando(true);
    try {
      if (rascunho.id) await pedir(`/api/live/pacotes?id=${rascunho.id}`, { method: "PUT", body: JSON.stringify(corpo) });
      else await pedir("/api/live/pacotes", { method: "POST", body: JSON.stringify(corpo) });
      await aoMudar();
      avisar("ok", rascunho.id ? "Pacote atualizado." : "Pacote criado.");
      setRascunho(null);
    } catch (falha) {
      setErroDoForm(falha instanceof Error ? falha.message : "Não foi possível salvar.");
    } finally {
      setSalvando(false);
    }
  };

  const alternar = async (p: PacoteDeLive) => {
    setOcupado(p.id);
    try {
      await pedir(`/api/live/pacotes?id=${p.id}`, { method: "PUT", body: JSON.stringify(corpoDoPacote({ ...p, ativo: !p.ativo })) });
      await aoMudar();
      avisar("ok", p.ativo ? `"${p.nome}" saiu da venda.` : `"${p.nome}" está à venda.`);
    } catch (falha) {
      avisar("erro", falha instanceof Error ? falha.message : "Não foi possível mudar.");
    } finally {
      setOcupado("");
    }
  };

  const excluir = async () => {
    if (!excluindo) return;
    setOcupado(excluindo.id);
    try {
      const r = await pedir<{ saiuDaVenda?: boolean }>(`/api/live/pacotes?id=${excluindo.id}`, { method: "DELETE" });
      await aoMudar();
      avisar("ok", r.saiuDaVenda ? "Este pacote já foi comprado: ele só saiu da venda." : "Pacote excluído.");
      setExcluindo(null);
    } catch (falha) {
      avisar("erro", falha instanceof Error ? falha.message : "Não foi possível excluir.");
    } finally {
      setOcupado("");
    }
  };

  const previa = rascunho ? corpoDoPacote(rascunho) : null;
  const custoDaPrevia = previa && previa.pessoas > 0 ? custo(previa.pessoas) : null;

  return (
    <div className="grid gap-4">
      <div className="flex flex-wrap items-end justify-between gap-3">
        <div>
          <h2 className="text-base font-semibold text-slate-900">Pacotes à venda</h2>
          <p className="mt-0.5 max-w-2xl text-sm text-slate-500">
            Cada pacote dá um número de lives com até tantas pessoas cada, válidas por {painel.regras.validade_dias} dias. A vaga só é gasta quando a empresa
            entra ao vivo.
          </p>
        </div>
        <button type="button" onClick={() => abrir(null)} className={BOTAO_PRIMARIO}>
          <PackagePlus size={16} /> Novo pacote
        </button>
      </div>

      {painel.pacotes.length === 0 ? (
        <div className="rounded-2xl border border-dashed border-slate-300 bg-white px-6 py-12 text-center">
          <p className="text-sm font-medium text-slate-800">Nenhum pacote cadastrado.</p>
          <p className="mx-auto mt-1 max-w-md text-xs leading-5 text-slate-500">Sem pacote à venda as empresas ficam só com as lives grátis do mês.</p>
        </div>
      ) : (
        <div className="overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
          <div className="hidden grid-cols-[minmax(0,1fr)_80px_90px_110px_110px_140px_150px] gap-4 border-b border-slate-100 bg-slate-50/70 px-5 py-2.5 text-[11px] font-semibold uppercase tracking-wider text-slate-500 lg:grid">
            <span>Pacote</span>
            <span className="text-right">Lives</span>
            <span className="text-right">Pessoas</span>
            <span className="text-right">Preço</span>
            <span className="text-right">Por live</span>
            <span className="text-right">Custo por live*</span>
            <span className="text-right">À venda</span>
          </div>
          <ul className="divide-y divide-slate-100">
            {painel.pacotes.map((p) => {
              const porLive = p.preco / p.lives;
              const c = custo(p.pessoas);
              return (
                <li key={p.id} className="grid gap-3 px-5 py-4 lg:grid-cols-[minmax(0,1fr)_80px_90px_110px_110px_140px_150px] lg:items-center lg:gap-4">
                  <div className="min-w-0">
                    <div className="flex flex-wrap items-center gap-2">
                      <span className="text-sm font-semibold text-slate-900">{p.nome}</span>
                      {p.destaque ? (
                        <Selo tom="violeta">
                          <Sparkles size={11} /> Mais escolhido
                        </Selo>
                      ) : null}
                      {!p.ativo ? <Selo tom="cinza">Fora da venda</Selo> : null}
                    </div>
                    {p.descricao ? <p className="mt-0.5 line-clamp-2 text-xs text-slate-500">{p.descricao}</p> : null}
                  </div>
                  <span className="text-sm tabular-nums text-slate-700 lg:text-right">{p.lives}</span>
                  <span className="text-sm tabular-nums text-slate-700 lg:text-right">{p.pessoas.toLocaleString("pt-BR")}</span>
                  <span className="text-sm font-medium tabular-nums text-slate-900 lg:text-right">{moeda(p.preco)}</span>
                  <span className="text-sm tabular-nums text-slate-600 lg:text-right">{moeda(porLive)}</span>
                  <span className={`text-sm tabular-nums lg:text-right ${porLive - c.reais >= 0 ? "text-emerald-700" : "text-rose-700"}`}>
                    {moeda(c.reais)} <span className="text-xs text-slate-400">({c.gb.toFixed(0)} GB)</span>
                  </span>
                  <div className="flex items-center justify-between gap-2 lg:justify-end">
                    <Interruptor ligado={p.ativo} rotulo={p.ativo ? `Tirar ${p.nome} da venda` : `Pôr ${p.nome} à venda`} desabilitado={ocupado === p.id} aoMudar={() => void alternar(p)} />
                    <button type="button" onClick={() => abrir(p)} aria-label={`Editar ${p.nome}`} className="inline-flex h-9 w-9 items-center justify-center rounded-lg text-slate-500 hover:bg-slate-100">
                      <Pencil size={15} />
                    </button>
                    <button type="button" onClick={() => setExcluindo(p)} aria-label={`Excluir ${p.nome}`} className="inline-flex h-9 w-9 items-center justify-center rounded-lg text-slate-400 hover:bg-rose-50 hover:text-rose-600">
                      <Trash2 size={15} />
                    </button>
                  </div>
                </li>
              );
            })}
          </ul>
          <p className="border-t border-slate-100 px-5 py-3 text-xs text-slate-500">
            * Live de 1h30 cheia, depois dos 1.000 GB grátis do mês na Cloudflare (US$ 0,05/GB, dólar a R$ 5,50). Verde: o preço por live cobre o custo.
          </p>
        </div>
      )}

      <Modal
        aberto={Boolean(rascunho)}
        aoFechar={() => (salvando ? undefined : setRascunho(null))}
        titulo={rascunho?.id ? "Editar pacote" : "Novo pacote"}
        descricao="Mudar o preço não mexe em compras já feitas."
        rodape={
          <>
            <button type="button" onClick={() => setRascunho(null)} disabled={salvando} className={BOTAO_SECUNDARIO}>
              Cancelar
            </button>
            <button type="button" onClick={() => void salvar()} disabled={salvando} className={BOTAO_PRIMARIO}>
              {salvando ? "Salvando…" : rascunho?.id ? "Salvar pacote" : "Criar pacote"}
            </button>
          </>
        }
      >
        {rascunho ? (
          <form
            className="grid gap-4"
            onSubmit={(e) => {
              e.preventDefault();
              void salvar();
            }}
          >
            <Campo rotulo="Nome">
              {(id) => <input id={id} className={CLASSE_DO_CAMPO} value={rascunho.nome} placeholder="Ex.: Live Pro" autoFocus onChange={(e) => setRascunho({ ...rascunho, nome: e.target.value.slice(0, 60) })} />}
            </Campo>
            <Campo rotulo="Descrição curta" ajuda="Opcional. Aparece no cartão do pacote.">
              {(id) => (
                <input id={id} className={CLASSE_DO_CAMPO} value={rascunho.descricao} placeholder="Ex.: Para quem faz live toda semana" onChange={(e) => setRascunho({ ...rascunho, descricao: e.target.value.slice(0, 200) })} />
              )}
            </Campo>
            <div className="grid gap-4 sm:grid-cols-3">
              <Campo rotulo="Lives">
                {(id) => (
                  <input id={id} inputMode="numeric" className={`${CLASSE_DO_CAMPO} tabular-nums`} value={rascunho.lives} placeholder="4" onChange={(e) => setRascunho({ ...rascunho, lives: e.target.value.replace(/\D/g, "").slice(0, 4) })} />
                )}
              </Campo>
              <Campo rotulo="Pessoas por live">
                {(id) => (
                  <input id={id} inputMode="numeric" className={`${CLASSE_DO_CAMPO} tabular-nums`} value={rascunho.pessoas} placeholder="200" onChange={(e) => setRascunho({ ...rascunho, pessoas: e.target.value.replace(/\D/g, "").slice(0, 6) })} />
                )}
              </Campo>
              <Campo rotulo="Preço (R$)">
                {(id) => (
                  <input id={id} inputMode="decimal" className={`${CLASSE_DO_CAMPO} tabular-nums`} value={rascunho.preco} placeholder="97,00" onChange={(e) => setRascunho({ ...rascunho, preco: e.target.value.replace(/[^\d.,]/g, "").slice(0, 12) })} />
                )}
              </Campo>
            </div>
            {custoDaPrevia && previa && previa.lives > 0 ? (
              <p className="rounded-xl bg-slate-50 px-3.5 py-2.5 text-xs leading-5 text-slate-600">
                Custo estimado por live cheia de 1h30: <strong>{moeda(custoDaPrevia.reais)}</strong> ({custoDaPrevia.gb.toFixed(0)} GB). O pacote inteiro:{" "}
                <strong>{moeda(custoDaPrevia.reais * previa.lives)}</strong>
                {Number.isFinite(previa.preco) && previa.preco > 0 ? ` para ${moeda(previa.preco)} de venda.` : "."}
              </p>
            ) : null}
            <div className="flex flex-wrap items-center gap-6">
              <label className="flex items-center gap-2 text-sm text-slate-700">
                <Interruptor ligado={rascunho.ativo} rotulo="À venda" aoMudar={(v) => setRascunho({ ...rascunho, ativo: v })} /> À venda
              </label>
              <label className="flex items-center gap-2 text-sm text-slate-700">
                <Interruptor ligado={rascunho.destaque} rotulo="Mais escolhido" aoMudar={(v) => setRascunho({ ...rascunho, destaque: v })} /> Mais escolhido
              </label>
            </div>
            {erroDoForm ? <p className="text-sm font-medium text-rose-600">{erroDoForm}</p> : null}
          </form>
        ) : null}
      </Modal>

      <Modal
        aberto={Boolean(excluindo)}
        aoFechar={() => setExcluindo(null)}
        titulo="Excluir este pacote?"
        descricao={excluindo ? `"${excluindo.nome}" sai da venda. Se alguém já comprou, ele só sai da venda (as compras continuam valendo).` : undefined}
        rodape={
          <>
            <button type="button" onClick={() => setExcluindo(null)} className={BOTAO_SECUNDARIO}>
              Voltar
            </button>
            <button type="button" onClick={() => void excluir()} disabled={Boolean(ocupado)} className={`${BOTAO_PRIMARIO} bg-rose-600 hover:bg-rose-700`}>
              Excluir
            </button>
          </>
        }
      />
    </div>
  );
}

function Compras({ compras }: { compras: CompraDeLiveNoOwner[] }) {
  if (!compras.length) return <p className="rounded-2xl border border-dashed border-slate-300 bg-white px-6 py-12 text-center text-sm text-slate-600">Nenhuma compra ainda.</p>;
  return (
    <div className="overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
      <ul className="divide-y divide-slate-100">
        {compras.map((c) => {
          const s = STATUS[c.status] ?? STATUS.pendente;
          return (
            <li key={c.id} className="flex flex-wrap items-center gap-3 px-5 py-3">
              <div className="min-w-[14rem] flex-1">
                <p className="text-sm font-semibold text-slate-900">{c.empresa}</p>
                <p className="text-xs text-slate-500">
                  {c.pacote_nome} · {plural(c.lives, "live", "lives")} até {c.pessoas} pessoas · {dataEHora(c.aprovada_em || c.created_at)}
                  {c.valida_ate && c.status === "aprovada" ? ` · vale até ${new Date(c.valida_ate).toLocaleDateString("pt-BR")}` : ""}
                </p>
              </div>
              <span className="text-sm font-medium tabular-nums text-slate-900">{moeda(c.preco)}</span>
              <Selo tom={s.tom}>{s.rotulo}</Selo>
            </li>
          );
        })}
      </ul>
    </div>
  );
}

function Uso({ painel }: { painel: PainelDaLive }) {
  if (!painel.usos.length) return <p className="rounded-2xl border border-dashed border-slate-300 bg-white px-6 py-12 text-center text-sm text-slate-600">Nenhuma live foi ao ar ainda.</p>;
  return (
    <div className="overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
      <ul className="divide-y divide-slate-100">
        {painel.usos.map((u) => (
          <li key={u.id} className="flex flex-wrap items-center gap-3 px-5 py-3">
            <div className="min-w-[14rem] flex-1">
              <p className="text-sm font-semibold text-slate-900">{u.titulo}</p>
              <p className="text-xs text-slate-500">
                {u.empresa} · {dataEHora(u.created_at)}
                {u.minutos ? ` · ${u.minutos} min no ar` : ""}
              </p>
            </div>
            <span className="text-xs tabular-nums text-slate-600">
              {/* 100.000 = cortesia sem limite de pessoas (migration 203). */}
              {u.pessoas >= 100000 ? `pico de ${u.pico} pessoas · sem limite` : `pico de ${u.pico} / ${u.pessoas} pessoas`}
            </span>
            <Selo tom={u.origem === "gratis" ? "cinza" : "violeta"}>{u.origem === "gratis" ? "Grátis do mês" : "Pacote"}</Selo>
          </li>
        ))}
      </ul>
    </div>
  );
}

function Regras({ painel, aoMudar, avisar }: { painel: PainelDaLive; aoMudar: () => Promise<void>; avisar: (tom: "ok" | "erro", texto: string) => void }) {
  const [gratis, setGratis] = useState(String(painel.regras.gratis_lives_por_mes));
  const [pessoas, setPessoas] = useState(String(painel.regras.gratis_pessoas));
  const [validade, setValidade] = useState(String(painel.regras.validade_dias));
  const [vendas, setVendas] = useState(painel.regras.vendas_abertas);
  const [salvando, setSalvando] = useState(false);

  const salvar = async () => {
    setSalvando(true);
    try {
      await pedir("/api/live/regras", {
        method: "PUT",
        body: JSON.stringify({ gratis_lives_por_mes: Number(gratis), gratis_pessoas: Number(pessoas), validade_dias: Number(validade), vendas_abertas: vendas }),
      });
      await aoMudar();
      avisar("ok", "Regras salvas.");
    } catch (falha) {
      avisar("erro", falha instanceof Error ? falha.message : "Não foi possível salvar.");
    } finally {
      setSalvando(false);
    }
  };

  return (
    <div className="grid max-w-2xl gap-5 rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
      <div className="grid gap-4 sm:grid-cols-3">
        <Campo rotulo="Lives grátis por mês" ajuda="Para cada empresa.">
          {(id) => <input id={id} inputMode="numeric" className={`${CLASSE_DO_CAMPO} tabular-nums`} value={gratis} onChange={(e) => setGratis(e.target.value.replace(/\D/g, "").slice(0, 4))} />}
        </Campo>
        <Campo rotulo="Pessoas na live grátis">
          {(id) => <input id={id} inputMode="numeric" className={`${CLASSE_DO_CAMPO} tabular-nums`} value={pessoas} onChange={(e) => setPessoas(e.target.value.replace(/\D/g, "").slice(0, 6))} />}
        </Campo>
        <Campo rotulo="Validade do pacote (dias)">
          {(id) => <input id={id} inputMode="numeric" className={`${CLASSE_DO_CAMPO} tabular-nums`} value={validade} onChange={(e) => setValidade(e.target.value.replace(/\D/g, "").slice(0, 4))} />}
        </Campo>
      </div>
      <label className="flex items-center justify-between gap-4 text-sm text-slate-800">
        <span>
          <span className="block font-medium">Venda de pacotes aberta</span>
          <span className="block text-xs text-slate-500">Desligado, ninguém compra (as lives grátis continuam).</span>
        </span>
        <Interruptor ligado={vendas} rotulo="Venda de pacotes aberta" aoMudar={setVendas} />
      </label>
      {painel.regras.updated_at ? (
        <p className="text-xs text-slate-500">
          Última mudança {dataEHora(painel.regras.updated_at)}
          {painel.regras.updated_by ? ` por ${painel.regras.updated_by}` : ""}
        </p>
      ) : null}
      <div>
        <button type="button" onClick={() => void salvar()} disabled={salvando} className={BOTAO_PRIMARIO}>
          {salvando ? "Salvando…" : "Salvar regras"}
        </button>
      </div>
    </div>
  );
}
