"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import {
  Ban,
  Check,
  Copy,
  Download,
  FileCode2,
  FileText,
  Loader2,
  Mail,
  MessageCircle,
  PenLine,
  Pencil,
  RefreshCw,
  RotateCcw,
  Send,
  Trash2,
  Undo2,
  X,
} from "lucide-react";

import { Aviso } from "@/components/ui/aviso";
import CaixaDeConfirmacao, { type Confirmacao } from "@/components/ui/caixa-de-confirmacao";
import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
import type { NotaNaTela } from "@/lib/fiscal/servidor/apresentacao";

import { PainelDeDevolucao } from "./painel-de-devolucao";

import {
  chaveEmBlocos,
  dataEHora,
  documentoFormatado,
  ErroDaTela,
  haQuantoTempo,
  ListaDePendencias,
  MarcaDoModelo,
  moeda,
  pedirFiscal,
  SeloDoStatus,
  SeloSemValorFiscal,
} from "./comum";
import { linkPublicoDoPedido, numeroDeWhatsapp } from "./link-do-pedido";
import type { Pendencia } from "@/lib/fiscal/montar";

type Evento = { id: string; tipo: string; titulo: string; detalhe: string | null; atorNome: string | null; created_at: string };

type Painel = "cancelar" | "corrigir" | "devolver" | null;

const ONDE_CORRIGIR: Record<string, { texto: string; link: (nota: NotaNaTela) => string | null }> = {
  cliente: { texto: "Abrir o cliente", link: () => null },
  produto: { texto: "Código fiscal dos produtos", link: () => "/dashboard/notas-fiscais/configuracao?passo=notas&abrir=produtos" },
  empresa: { texto: "Dados da empresa", link: () => "/dashboard/notas-fiscais/configuracao?passo=empresa" },
  certificado: { texto: "Certificado digital", link: () => "/dashboard/notas-fiscais/configuracao?passo=certificado" },
  tributacao: { texto: "Revisar os impostos", link: () => "/dashboard/notas-fiscais/configuracao?passo=notas&abrir=ajustes" },
  numeracao: { texto: "Ajustar a numeração", link: () => "/dashboard/notas-fiscais/configuracao?passo=notas" },
  csc: { texto: "Ajustes do cupom fiscal", link: () => "/dashboard/notas-fiscais/configuracao?passo=notas" },
};

export function DetalheDaNota({
  notaId,
  aberta,
  aoFechar,
  aoMudar,
  telefoneDoCliente,
  clienteId,
  permissoes,
}: {
  notaId: string | null;
  aberta: boolean;
  aoFechar: () => void;
  /** Avisa quem abriu que a nota mudou (para recarregar a lista). */
  aoMudar?: (nota: NotaNaTela) => void;
  telefoneDoCliente?: string | null;
  clienteId?: string | null;
  permissoes: { emitir: boolean; cancelar: boolean };
}) {
  const [nota, setNota] = useState<NotaNaTela | null>(null);
  const [eventos, setEventos] = useState<Evento[]>([]);
  const [carregando, setCarregando] = useState(false);
  const [ocupado, setOcupado] = useState<string | null>(null);
  const [erro, setErro] = useState<string | null>(null);
  const [pendencias, setPendencias] = useState<Pendencia[]>([]);
  const [okMensagem, setOkMensagem] = useState<string | null>(null);
  const [painel, setPainel] = useState<Painel>(null);
  const [texto, setTexto] = useState("");
  const [confirmacao, setConfirmacao] = useState<Confirmacao | null>(null);
  const [copiado, setCopiado] = useState(false);

  const carregar = useCallback(
    async (silencioso = false) => {
      if (!notaId) return;
      if (!silencioso) setCarregando(true);
      try {
        const json = await pedirFiscal<{ nota: NotaNaTela; eventos: Evento[] }>(`/api/fiscal/notas/${notaId}`);
        setNota(json.nota);
        setEventos(json.eventos);
      } catch (e) {
        setErro(e instanceof Error ? e.message : "Não foi possível abrir a nota.");
      } finally {
        if (!silencioso) setCarregando(false);
      }
    },
    [notaId]
  );

  useEffect(() => {
    if (!aberta || !notaId) return;
    setNota(null);
    setEventos([]);
    setErro(null);
    setPendencias([]);
    setOkMensagem(null);
    setPainel(null);
    setTexto("");
    void carregar();
  }, [aberta, notaId, carregar]);

  /* Enquanto a SEFAZ não responde, a tela se atualiza sozinha. */
  useEffect(() => {
    if (!aberta || !nota?.emAndamento) return;
    const relogio = setInterval(() => void carregar(true), 4000);
    return () => clearInterval(relogio);
  }, [aberta, nota?.emAndamento, carregar]);

  const executar = useCallback(
    async (chave: string, acao: () => Promise<NotaNaTela | null | void>, sucesso?: string) => {
      setOcupado(chave);
      setErro(null);
      setPendencias([]);
      setOkMensagem(null);
      try {
        const atualizada = await acao();
        if (atualizada) {
          setNota(atualizada);
          aoMudar?.(atualizada);
        }
        if (sucesso) setOkMensagem(sucesso);
        await carregar(true);
        return true;
      } catch (e) {
        setErro(e instanceof Error ? e.message : "Não deu certo.");
        if (e instanceof ErroDaTela) setPendencias(e.pendencias);
        return false;
      } finally {
        setOcupado(null);
      }
    },
    [aoMudar, carregar]
  );

  const abrirArquivo = (tipo: "pdf" | "xml") => {
    if (!nota) return;
    const url = `/api/fiscal/notas/${nota.id}/arquivo?tipo=${tipo}${tipo === "xml" ? "&baixar=1" : ""}${nota.status === "rascunho" ? "&previa=1" : ""}`;
    window.open(url, "_blank", "noopener,noreferrer");
  };

  const enviarWhatsapp = async () => {
    if (!nota) return;
    setOcupado("whatsapp");
    try {
      const link = nota.pedidoId ? await linkPublicoDoPedido(nota.pedidoId) : null;
      const primeiroNome = (nota.destinatarioNome || "").split(" ")[0];
      const partes = [
        `Olá${primeiroNome ? `, ${primeiroNome}` : ""}! A nota fiscal${nota.pedidoNumero ? ` do pedido #${nota.pedidoNumero}` : ""} já está disponível.`,
        `${nota.modeloNome}${nota.numero ? ` nº ${nota.numero}` : ""} · ${moeda(nota.valor)}`,
        link ? `Baixe aqui: ${link}` : null,
        nota.chave ? `Chave de acesso: ${chaveEmBlocos(nota.chave)}` : null,
      ].filter(Boolean);
      const numero = numeroDeWhatsapp(telefoneDoCliente);
      const url = `https://wa.me/${numero ?? ""}?text=${encodeURIComponent(partes.join("\n"))}`;
      window.open(url, "_blank", "noopener,noreferrer");
    } catch {
      setErro("Não foi possível montar o link para o cliente.");
    } finally {
      setOcupado(null);
    }
  };

  const copiarChave = async () => {
    if (!nota?.chave) return;
    try {
      await navigator.clipboard.writeText(nota.chave);
      setCopiado(true);
      setTimeout(() => setCopiado(false), 1500);
    } catch {
      setErro("Não foi possível copiar.");
    }
  };

  const limiteDoTexto = painel === "cancelar" ? 255 : 1000;
  const textoValido = texto.trim().length >= 15 && texto.trim().length <= limiteDoTexto;

  const explicacao = nota?.explicacao;
  const clienteDaNota = clienteId ?? nota?.clienteId ?? null;
  const acaoDeCorrecao = explicacao?.onde ? ONDE_CORRIGIR[explicacao.onde] : null;
  const linkDeCorrecao = useMemo(() => {
    if (!nota || !acaoDeCorrecao) return null;
    if (explicacao?.onde === "cliente") return clienteDaNota ? `/dashboard/clients/${clienteDaNota}?editar=1` : null;
    return acaoDeCorrecao.link(nota);
  }, [nota, acaoDeCorrecao, explicacao?.onde, clienteDaNota]);

  return (
    <>
      <Dialog open={aberta} onOpenChange={(v) => !v && aoFechar()}>
        <DialogContent
          hideClose
          className="flex max-h-[92vh] w-[calc(100vw-24px)] max-w-[720px] flex-col gap-0 overflow-hidden rounded-[24px] border-0 bg-[var(--ks-color-bg-elevated)] p-0 shadow-[0_30px_80px_rgba(26,26,43,0.28)]"
        >
          <DialogTitle className="sr-only">Nota fiscal</DialogTitle>
          <DialogDescription className="sr-only">Detalhes, arquivos e ações da nota fiscal.</DialogDescription>

          {carregando || !nota ? (
            <div className="flex min-h-[320px] items-center justify-center">
              {erro ? (
                <div className="px-6 text-center text-sm text-[var(--ks-color-text-muted)]">{erro}</div>
              ) : (
                <Loader2 className="h-7 w-7 animate-spin text-[var(--ks-color-primary)]" />
              )}
            </div>
          ) : (
            <>
              <header className="flex items-start gap-4 px-6 pb-4 pt-6">
                <MarcaDoModelo modelo={nota.modelo} />
                <div className="min-w-0 flex-1">
                  <div className="flex flex-wrap items-center gap-2">
                    <h2 className="text-lg font-extrabold tracking-tight text-[var(--ks-color-text-primary)]">
                      {nota.modeloNome}
                      {nota.numero ? <span className="ks-num"> nº {nota.numero}</span> : null}
                      {nota.serie ? <span className="text-sm font-semibold text-[var(--ks-color-text-soft)]"> · série {nota.serie}</span> : null}
                    </h2>
                    <SeloDoStatus tom={nota.tom} rotulo={nota.rotulo} titulo={nota.descricaoDoStatus} />
                    {nota.semValorFiscal ? <SeloSemValorFiscal /> : null}
                  </div>
                  <p className="mt-1 truncate text-sm text-[var(--ks-color-text-muted)]">
                    {nota.destinatarioNome || "Consumidor não identificado"}
                    {nota.destinatarioDocumento ? ` · ${documentoFormatado(nota.destinatarioDocumento)}` : ""}
                  </p>
                </div>
                <div className="text-right">
                  <p className="ks-num text-xl font-extrabold text-[var(--ks-color-text-primary)]">{moeda(nota.valor)}</p>
                  {nota.pedidoNumero ? (
                    <a href={`/dashboard/orders/${nota.pedidoId}`} className="text-xs font-semibold text-[var(--ks-color-primary)] hover:underline">
                      Pedido #{nota.pedidoNumero}
                    </a>
                  ) : nota.origem === "teste" ? (
                    <p className="text-xs text-[var(--ks-color-text-soft)]">Nota de teste</p>
                  ) : nota.semPedido ? (
                    <p className="text-xs text-[var(--ks-color-text-soft)]">Emitida sem pedido</p>
                  ) : null}
                </div>
                <button
                  type="button"
                  onClick={aoFechar}
                  className="-mr-2 -mt-2 rounded-full p-2 text-[var(--ks-color-text-soft)] transition hover:bg-[var(--ks-color-bg-hover)] hover:text-[var(--ks-color-text-primary)]"
                  aria-label="Fechar"
                >
                  <X size={18} />
                </button>
              </header>

              <div className="flex-1 space-y-5 overflow-y-auto px-6 pb-6">
                {nota.emAndamento ? (
                  <Aviso
                    tom="neutro"
                    titulo={nota.status === "cancelando" ? "Cancelamento a caminho" : "Aguardando a autorização"}
                    acao={
                      <button
                        type="button"
                        onClick={() => void executar("consultar", async () => (await pedirFiscal<{ nota: NotaNaTela }>(`/api/fiscal/notas/${nota.id}/consultar`, { method: "POST" })).nota)}
                        disabled={ocupado !== null}
                        className="ks-button ks-button-soft ks-button-sm"
                      >
                        {ocupado === "consultar" ? <Loader2 size={14} className="animate-spin" /> : <RefreshCw size={14} />}
                        Atualizar agora
                      </button>
                    }
                  >
                    {nota.descricaoDoStatus} Esta tela se atualiza sozinha.
                  </Aviso>
                ) : null}

                {["rejeitada", "erro", "denegada"].includes(nota.status) && explicacao ? (
                  <Aviso
                    tom="ruim"
                    titulo={explicacao.titulo}
                    acao={
                      linkDeCorrecao ? (
                        <a href={linkDeCorrecao} target="_blank" rel="noopener noreferrer" className="ks-button ks-button-soft ks-button-sm">
                          {acaoDeCorrecao?.texto}
                        </a>
                      ) : undefined
                    }
                  >
                    <span className="block">{explicacao.dica}</span>
                    {nota.mensagem ? (
                      <details className="mt-2">
                        <summary className="cursor-pointer text-xs font-semibold text-[var(--ks-color-text-soft)]">Ver a mensagem original</summary>
                        <span className="mt-1 block break-words text-xs text-[var(--ks-color-text-soft)]">
                          {nota.mensagemCodigo ? `${nota.mensagemCodigo} · ` : ""}
                          {nota.mensagem}
                        </span>
                      </details>
                    ) : null}
                  </Aviso>
                ) : null}

                {nota.status === "autorizada" && nota.mensagem ? (
                  <Aviso tom="atencao" titulo="Última tentativa de cancelamento">
                    {nota.mensagem}
                  </Aviso>
                ) : null}

                {erro ? (
                  <Aviso tom="ruim" aoFechar={() => setErro(null)}>
                    {erro}
                  </Aviso>
                ) : null}
                {pendencias.length ? (
                  <div className="rounded-2xl bg-[var(--ks-color-bg-inset)] px-4 py-2">
                    <ListaDePendencias pendencias={pendencias} contexto={{ clienteId: clienteDaNota, pedidoId: nota.pedidoId, semPedido: nota.semPedido }} />
                  </div>
                ) : null}
                {okMensagem ? (
                  <Aviso tom="bom" aoFechar={() => setOkMensagem(null)}>
                    {okMensagem}
                  </Aviso>
                ) : null}

                {/* Ações */}
                <div className="flex flex-wrap gap-2">
                  {nota.temArquivos || nota.status === "rascunho" ? (
                    <>
                      <button type="button" onClick={() => abrirArquivo("pdf")} className="ks-button ks-button-primary ks-button-sm">
                        <FileText size={14} />
                        {nota.status === "rascunho" ? "Ver prévia" : "PDF da nota"}
                      </button>
                      {nota.status !== "rascunho" ? (
                        <button type="button" onClick={() => abrirArquivo("xml")} className="ks-button ks-button-soft ks-button-sm">
                          <FileCode2 size={14} />
                          XML
                        </button>
                      ) : null}
                    </>
                  ) : null}
                  {nota.status === "autorizada" && nota.pedidoId ? (
                    <button type="button" onClick={() => void enviarWhatsapp()} disabled={ocupado !== null} className="ks-button ks-button-soft ks-button-sm">
                      {ocupado === "whatsapp" ? <Loader2 size={14} className="animate-spin" /> : <MessageCircle size={14} />}
                      WhatsApp
                    </button>
                  ) : null}
                  {nota.podeEnviarEmail && permissoes.emitir ? (
                    <button
                      type="button"
                      disabled={ocupado !== null}
                      onClick={() =>
                        void executar(
                          "email",
                          async () => {
                            await pedirFiscal(`/api/fiscal/notas/${nota.id}/email`, { method: "POST" });
                          },
                          `E-mail reenviado para ${nota.destinatarioEmail}.`
                        )
                      }
                      className="ks-button ks-button-soft ks-button-sm"
                    >
                      {ocupado === "email" ? <Loader2 size={14} className="animate-spin" /> : <Mail size={14} />}
                      Reenviar e-mail
                    </button>
                  ) : null}
                  {(nota.podeReenviar || nota.podeEmitirPrevia) && permissoes.emitir ? (
                    <button
                      type="button"
                      disabled={ocupado !== null}
                      onClick={() =>
                        void executar(
                          "reenviar",
                          async () => (await pedirFiscal<{ nota: NotaNaTela }>(`/api/fiscal/notas/${nota.id}/reenviar`, { method: "POST", json: {} })).nota,
                          nota.podeEmitirPrevia ? "Nota enviada para autorização." : "Nota reenviada com os dados de agora."
                        )
                      }
                      className="ks-button ks-button-primary ks-button-sm"
                    >
                      {ocupado === "reenviar" ? <Loader2 size={14} className="animate-spin" /> : nota.podeEmitirPrevia ? <Send size={14} /> : <RotateCcw size={14} />}
                      {nota.podeEmitirPrevia ? "Emitir esta nota" : "Corrigi, reenviar"}
                    </button>
                  ) : null}
                  {nota.podeEditarNaEmissao && permissoes.emitir ? (
                    <a href={`/dashboard/notas-fiscais/emitir?nota=${nota.id}`} className="ks-button ks-button-soft ks-button-sm">
                      <Pencil size={14} />
                      Editar a nota
                    </a>
                  ) : null}
                  {nota.podeCopiar && permissoes.emitir ? (
                    <a href={`/dashboard/notas-fiscais/emitir?copiar=${nota.id}`} className="ks-button ks-button-soft ks-button-sm">
                      <Copy size={14} />
                      Emitir outra igual
                    </a>
                  ) : null}
                  {nota.podeDevolver && permissoes.emitir ? (
                    <button
                      type="button"
                      onClick={() => {
                        setPainel(painel === "devolver" ? null : "devolver");
                        setTexto("");
                      }}
                      className="ks-button ks-button-soft ks-button-sm"
                      title="O cliente devolveu o que comprou"
                    >
                      <Undo2 size={14} />
                      Devolver
                    </button>
                  ) : null}
                  {nota.podeCorrigir && permissoes.cancelar ? (
                    <button type="button" onClick={() => { setPainel(painel === "corrigir" ? null : "corrigir"); setTexto(""); }} className="ks-button ks-button-soft ks-button-sm">
                      <PenLine size={14} />
                      Carta de correção
                    </button>
                  ) : null}
                  {nota.podeCancelar && permissoes.cancelar ? (
                    <button
                      type="button"
                      onClick={() => { setPainel(painel === "cancelar" ? null : "cancelar"); setTexto(""); }}
                      className="ks-button ks-button-soft ks-button-sm text-[var(--ks-color-status-danger)]"
                    >
                      <Ban size={14} />
                      Cancelar nota
                    </button>
                  ) : null}
                  {nota.podeDescartar && permissoes.emitir ? (
                    <button
                      type="button"
                      disabled={ocupado !== null}
                      onClick={() =>
                        setConfirmacao({
                          titulo: nota.status === "rascunho" ? "Descartar esta prévia?" : "Descartar esta nota?",
                          texto: "Ela ainda não tem valor fiscal. Some da lista e não gasta nota do pacote.",
                          confirmar: "Descartar",
                          tom: "perigo",
                          aoConfirmar: async () => {
                            setConfirmacao(null);
                            await executar("descartar", async () => (await pedirFiscal<{ nota: NotaNaTela }>(`/api/fiscal/notas/${nota.id}`, { method: "DELETE" })).nota);
                          },
                        })
                      }
                      className="ks-button ks-button-ghost ks-button-sm"
                    >
                      <Trash2 size={14} />
                      Descartar
                    </button>
                  ) : null}
                </div>

                {painel === "devolver" ? (
                  <PainelDeDevolucao
                    notaId={nota.id}
                    aoEmitir={() => {
                      setPainel(null);
                      aoMudar?.(nota);
                      aoFechar();
                    }}
                  />
                ) : null}

                {painel === "cancelar" || painel === "corrigir" ? (
                  <div className="space-y-3 rounded-2xl bg-[var(--ks-color-bg-inset)] p-4">
                    <div>
                      <p className="text-sm font-bold text-[var(--ks-color-text-primary)]">
                        {painel === "cancelar" ? "Por que esta nota está sendo cancelada?" : "O que precisa ser corrigido?"}
                      </p>
                      <p className="text-xs leading-5 text-[var(--ks-color-text-muted)]">
                        {painel === "cancelar"
                          ? nota.modelo === "nfce"
                            ? "A NFC-e costuma poder ser cancelada só nos primeiros 30 minutos (varia por estado). O motivo vai para a SEFAZ."
                            : nota.modelo === "nfe"
                              ? "A NF-e pode ser cancelada em até 24 horas da autorização. O motivo vai para a SEFAZ."
                              : "O prazo de cancelamento da NFS-e depende da prefeitura. O motivo vai para ela."
                          : "A carta de correção não muda valores, impostos, dados do cliente nem datas. Para isso, cancele e emita de novo."}
                      </p>
                    </div>
                    <textarea
                      value={texto}
                      onChange={(e) => setTexto(e.target.value.slice(0, limiteDoTexto))}
                      rows={3}
                      className="ks-field w-full resize-none"
                      placeholder={painel === "cancelar" ? "Ex.: cliente desistiu da compra antes da entrega" : "Ex.: onde se lê Rua A, leia-se Rua B no endereço de entrega"}
                    />
                    <div className="flex flex-wrap items-center justify-between gap-2">
                      <span className={`text-xs tabular-nums ${texto.trim().length < 15 ? "text-[var(--ks-color-text-soft)]" : "text-emerald-600"}`}>
                        {texto.trim().length < 15 ? `mínimo 15 letras (${texto.trim().length})` : `${texto.trim().length}/${limiteDoTexto}`}
                      </span>
                      <div className="flex gap-2">
                        <button type="button" onClick={() => setPainel(null)} className="ks-button ks-button-ghost ks-button-sm">
                          Voltar
                        </button>
                        <button
                          type="button"
                          disabled={!textoValido || ocupado !== null}
                          onClick={() =>
                            painel === "cancelar"
                              ? setConfirmacao({
                                  titulo: `Cancelar ${nota.modeloNome}${nota.numero ? ` nº ${nota.numero}` : ""}?`,
                                  texto: "O cancelamento vai para a autoridade e não tem volta. A nota do pacote não é devolvida.",
                                  confirmar: "Cancelar nota",
                                  cancelar: "Voltar",
                                  tom: "perigo",
                                  aoConfirmar: async () => {
                                    setConfirmacao(null);
                                    const deu = await executar(
                                      "cancelar",
                                      async () => (await pedirFiscal<{ nota: NotaNaTela }>(`/api/fiscal/notas/${nota.id}/cancelar`, { method: "POST", json: { motivo: texto } })).nota,
                                      "Cancelamento enviado."
                                    );
                                    if (deu) setPainel(null);
                                  },
                                })
                              : void executar(
                                  "corrigir",
                                  async () => {
                                    await pedirFiscal(`/api/fiscal/notas/${nota.id}/correcao`, { method: "POST", json: { texto } });
                                  },
                                  "Carta de correção enviada."
                                ).then((deu) => deu && setPainel(null))
                          }
                          className={`ks-button ks-button-sm ${painel === "cancelar" ? "bg-[#e13a58] text-white hover:opacity-90" : "ks-button-primary"}`}
                        >
                          {ocupado === "cancelar" || ocupado === "corrigir" ? <Loader2 size={14} className="animate-spin" /> : null}
                          {painel === "cancelar" ? "Cancelar nota" : "Enviar correção"}
                        </button>
                      </div>
                    </div>
                  </div>
                ) : null}

                {/* Dados */}
                <dl className="divide-y divide-slate-100/60 rounded-2xl">
                  {nota.chave ? (
                    <div className="flex flex-wrap items-center justify-between gap-2 py-2.5">
                      <dt className="text-xs text-[var(--ks-color-text-muted)]">Chave de acesso</dt>
                      <dd className="flex items-center gap-2">
                        <span className="ks-num break-all text-right text-[12px] font-semibold text-[var(--ks-color-text-primary)]">{chaveEmBlocos(nota.chave)}</span>
                        <button type="button" onClick={() => void copiarChave()} className="rounded-lg p-1.5 text-[var(--ks-color-text-soft)] hover:bg-[var(--ks-color-bg-hover)]" aria-label="Copiar chave">
                          {copiado ? <Check size={14} className="text-emerald-600" /> : <Copy size={14} />}
                        </button>
                      </dd>
                    </div>
                  ) : null}
                  {nota.protocolo ? <Linha rotulo="Protocolo" valor={nota.protocolo} /> : null}
                  <Linha rotulo="Criada" valor={dataEHora(nota.criadaEm)} />
                  {nota.autorizadaEm ? <Linha rotulo="Autorizada" valor={dataEHora(nota.autorizadaEm)} /> : null}
                  {nota.canceladaEm ? <Linha rotulo="Cancelada" valor={dataEHora(nota.canceladaEm)} /> : null}
                  {nota.cancelamentoMotivo ? <Linha rotulo="Motivo do cancelamento" valor={nota.cancelamentoMotivo} /> : null}
                  <Linha
                    rotulo="Ambiente"
                    valor={nota.ambienteNota === "producao" ? "Nota de verdade, com valor fiscal" : "Nota de teste, sem valor fiscal"}
                  />
                  <Linha
                    rotulo="Pacote do mês"
                    valor={
                      !nota.contaCredito
                        ? "Não gasta nota"
                        : nota.credito === "consumido"
                          ? "Gastou 1 nota"
                          : nota.credito === "reservado"
                            ? "1 nota reservada"
                            : "Não gastou nota"
                    }
                  />
                </dl>

                {/* Linha do tempo */}
                {eventos.length ? (
                  <section>
                    <h3 className="mb-2 text-[11px] font-bold uppercase tracking-[0.14em] text-[var(--ks-color-text-soft)]">Histórico</h3>
                    <ol className="relative space-y-3 border-l-2 border-[var(--ks-color-border-subtle)] pl-4">
                      {eventos.map((evento) => (
                        <li key={evento.id} className="relative">
                          <span className="absolute -left-[21px] top-1.5 h-2.5 w-2.5 rounded-full bg-[var(--ks-color-primary)] ring-4 ring-[var(--ks-color-bg-elevated)]" />
                          <p className="text-[13px] font-semibold text-[var(--ks-color-text-primary)]">{evento.titulo}</p>
                          {evento.detalhe ? <p className="text-xs leading-5 text-[var(--ks-color-text-muted)]">{evento.detalhe}</p> : null}
                          <p className="text-[11px] text-[var(--ks-color-text-soft)]">
                            {haQuantoTempo(evento.created_at)}
                            {evento.atorNome ? ` · ${evento.atorNome}` : ""}
                          </p>
                        </li>
                      ))}
                    </ol>
                  </section>
                ) : null}
              </div>

              {nota.temArquivos && nota.status !== "rascunho" ? (
                <footer className="flex items-center justify-between gap-3 border-t border-[var(--ks-color-border-subtle)] px-6 py-3 text-xs text-[var(--ks-color-text-soft)]">
                  <span>PDF e XML ficam guardados por 5 anos.</span>
                  <button type="button" onClick={() => abrirArquivo("xml")} className="inline-flex items-center gap-1 font-semibold text-[var(--ks-color-primary)] hover:underline">
                    <Download size={12} />
                    Baixar XML
                  </button>
                </footer>
              ) : null}
            </>
          )}
        </DialogContent>
      </Dialog>
      <CaixaDeConfirmacao pedido={confirmacao} ocupado={ocupado !== null} aoFechar={() => setConfirmacao(null)} />
    </>
  );
}

function Linha({ rotulo, valor }: { rotulo: string; valor: string }) {
  return (
    <div className="flex items-start justify-between gap-4 py-2.5">
      <dt className="shrink-0 text-xs text-[var(--ks-color-text-muted)]">{rotulo}</dt>
      <dd className="text-right text-[13px] font-semibold text-[var(--ks-color-text-primary)]">{valor}</dd>
    </div>
  );
}
