"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import {
  ArrowLeft,
  Bold,
  ExternalLink,
  Image as IconeImagem,
  Italic,
  Link2,
  List,
  ListOrdered,
  Minus,
  Quote,
  SquareArrowOutUpRight,
  Strikethrough,
  BarChart3,
  Table,
  Tag,
} from "lucide-react";
import { getSupabaseClient } from "@/lib/supabase";
import { faxinarSlug } from "@/lib/faxina-html";

/**
 * O editor do boletim: uma folha para escrever.
 *
 * O texto é editado direto na página, com a mesma tipografia do endereço
 * publicado, e o que sai daqui é HTML. A rota faz a faxina antes de gravar, e
 * é ela que decide o que sobrevive: aqui em cima nada é considerado seguro.
 *
 * A formatação usa `document.execCommand`. Ele está marcado como obsoleto há
 * anos e continua sendo o que todo navegador implementa para texto rico; a
 * alternativa seria arrastar um editor inteiro para dentro do projeto, e o
 * boletim não precisa de tanto.
 */

export type BoletimInicial = {
  id: string;
  slug: string;
  title: string;
  subtitle: string | null;
  tag: string | null;
  cover_image_url: string | null;
  body_html: string;
  status: string;
  published_at: string | null;
};

type Titulo = { id: string; texto: string; nivel: number };

const ESPERA_PARA_SALVAR = 1800;

/* Andaimes prontos para os blocos que ninguém escreveria à mão em HTML.
   Nascem com texto de exemplo porque bloco vazio no meio do texto some da
   vista, e a pessoa não descobre que precisa preencher. */
const ANDAIME_PRECOS = `<div class="boletim-precos"><div class="boletim-preco"><span class="boletim-preco-nome">Mensal</span><span class="boletim-preco-antes">R$ 00,00</span><span class="boletim-preco-valor">R$ 00,00</span><span class="boletim-preco-nota">Uma linha explicando o plano.</span></div><div class="boletim-preco boletim-preco-destaque"><span class="boletim-selo">Sai mais barato</span><span class="boletim-preco-nome">Anual</span><span class="boletim-preco-antes">R$ 00,00</span><span class="boletim-preco-valor">R$ 00,00</span><span class="boletim-preco-nota">Uma linha explicando o plano.</span></div></div><p><br /></p>`;

const ANDAIME_TABELA = `<table class="boletim-tabela"><thead><tr><th>O quê</th><th>Antes</th><th>Agora</th></tr></thead><tbody><tr><td>Primeira linha</td><td>—</td><td>—</td></tr><tr><td>Segunda linha</td><td>—</td><td>—</td></tr></tbody></table><p><br /></p>`;

const ANDAIME_BARRAS = `<div class="boletim-barras"><div class="boletim-barra"><span class="boletim-barra-rotulo">Primeiro</span><span class="boletim-barra-trilho"><i class="boletim-barra-preenche" style="width:100%"></i></span><span class="boletim-barra-valor">100</span></div><div class="boletim-barra"><span class="boletim-barra-rotulo">Segundo</span><span class="boletim-barra-trilho"><i class="boletim-barra-preenche" style="width:60%"></i></span><span class="boletim-barra-valor">60</span></div></div><p><br /></p>`;

const ANDAIME_DESTAQUE = `<div class="boletim-destaque">A frase que você quer que ninguém perca.</div><p><br /></p>`;

function contarPalavras(html: string) {
  const texto = html.replace(/<[^>]*>/g, " ").replace(/&[a-z]+;/gi, " ");
  const palavras = texto.split(/\s+/).filter(Boolean);
  return palavras.length;
}

export default function BoletimEditorClient({
  inicial,
  base,
}: {
  inicial: BoletimInicial | null;
  /** O endereço onde o boletim vai morar, mostrado ao lado do campo. */
  base: string;
}) {
  const folha = useRef<HTMLDivElement | null>(null);
  const arquivo = useRef<HTMLInputElement | null>(null);
  const selecaoGuardada = useRef<Range | null>(null);

  /* O id como referência, e não só como estado.
     O primeiro salvamento CRIA o boletim, e `setId` só chega na renderização
     seguinte. Se o salvamento automático e o clique em Publicar caírem no
     mesmo intervalo, o segundo ainda veria id vazio e criaria um segundo
     boletim — foi exatamente o que aconteceu no primeiro teste. */
  const idRef = useRef(inicial?.id ?? "");
  const salvandoRef = useRef<Promise<string | null> | null>(null);

  /* `id` existe só para a tela reagir ao boletim que acabou de nascer (o botão
     "Ver publicado" precisa dele). Quem manda no salvamento é o `idRef`. */
  const [, setId] = useState(inicial?.id ?? "");
  const [title, setTitle] = useState(inicial?.title ?? "");
  const [subtitle, setSubtitle] = useState(inicial?.subtitle ?? "");
  const [tag, setTag] = useState(inicial?.tag ?? "");
  const [slug, setSlug] = useState(inicial?.slug ?? "");
  const [status, setStatus] = useState(inicial?.status ?? "draft");
  const [corpo, setCorpo] = useState(inicial?.body_html ?? "");
  const [titulos, setTitulos] = useState<Titulo[]>([]);

  const [salvando, setSalvando] = useState(false);
  /* Publicar é diferente de salvar. O salvamento automático corre sozinho o
     tempo todo, e desligar o botão junto com ele fazia o clique se perder
     exatamente quando a pessoa acabava de escrever e queria publicar. */
  const [publicando, setPublicando] = useState(false);
  const [salvoEm, setSalvoEm] = useState<string>("");
  const [erro, setErro] = useState("");
  const [enviandoImagem, setEnviandoImagem] = useState(false);
  const [painelDeLink, setPainelDeLink] = useState<"link" | "botao" | "">("");
  const [enderecoDoLink, setEnderecoDoLink] = useState("");
  const [rotuloDoBotao, setRotuloDoBotao] = useState("");

  /* O conteúdo entra uma vez só. Reescrever a folha a cada tecla apagaria o
     cursor de quem está digitando. */
  /* Salva sozinho depois que a digitação para. Sem isto, fechar a aba no meio
     de um texto longo custaria o texto. */
  const relogio = useRef<ReturnType<typeof setTimeout> | null>(null);

  const [carregado, setCarregado] = useState(false);
  useEffect(() => {
    if (carregado || !folha.current) return;
    folha.current.innerHTML = inicial?.body_html ?? "";
    setCarregado(true);
    setTitulos(lerTitulos());
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [carregado]);

  function lerTitulos(): Titulo[] {
    if (!folha.current) return [];
    const achados: Titulo[] = [];
    folha.current.querySelectorAll("h2, h3").forEach((no, indice) => {
      const texto = (no.textContent || "").trim();
      if (!texto) return;
      const marcador = `titulo-${indice}`;
      no.setAttribute("data-sumario", marcador);
      achados.push({ id: marcador, texto, nivel: no.tagName === "H3" ? 3 : 2 });
    });
    return achados;
  }

  const salvar = useCallback(
    async (publicar?: boolean): Promise<string | null> => {
      if (!title.trim()) {
        setErro("O boletim precisa de um título.");
        return null;
      }

      /* Um salvamento por vez. O que chegar durante outro espera o primeiro
         terminar, para só então gravar com o id que acabou de nascer. */
      if (salvandoRef.current) {
        await salvandoRef.current.catch(() => null);
      }
      /* Quem salva agora cancela o automático que estava marcado: senão ele
         dispararia logo depois e desfaria o status recém-escolhido. */
      if (relogio.current) {
        clearTimeout(relogio.current);
        relogio.current = null;
      }

      const tarefa = (async (): Promise<string | null> => {
      setSalvando(true);
      if (publicar !== undefined) setPublicando(true);
      setErro("");
      try {
        const corpoAtual = folha.current?.innerHTML ?? corpo;
        const payload: Record<string, unknown> = {
          title: title.trim(),
          subtitle: subtitle.trim() || null,
          tag: tag.trim() || null,
          slug: slug.trim() || faxinarSlug(title),
          body_html: corpoAtual,
        };
        if (publicar !== undefined) payload.status = publicar ? "published" : "draft";

        const idAtual = idRef.current;
        const resposta = await fetch("/api/bulletins", {
          method: idAtual ? "PATCH" : "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify(idAtual ? { ...payload, id: idAtual } : payload),
        });
        const retorno = (await resposta.json().catch(() => null)) as
          | { error?: string; id?: string; slug?: string; status?: string }
          | null;
        if (!resposta.ok) throw new Error(retorno?.error || "Não foi possível salvar.");

        if (!idAtual && retorno?.id) {
          idRef.current = retorno.id;
          setId(retorno.id);
          /* Troca o endereço da barra sem recarregar: quem começou em "novo"
             passa a estar editando, e um F5 não cria um segundo boletim. */
          window.history.replaceState(null, "", `/boletins/${retorno.id}`);
        }
        if (retorno?.slug) setSlug(retorno.slug);
        if (retorno?.status) setStatus(retorno.status);
        if (publicar !== undefined) setStatus(publicar ? "published" : "draft");
        setSalvoEm(new Date().toLocaleTimeString("pt-BR", { hour: "2-digit", minute: "2-digit" }));
        return retorno?.id || idRef.current;
      } catch (falha) {
        setErro(falha instanceof Error ? falha.message : "Não foi possível salvar.");
        return null;
      } finally {
        setSalvando(false);
        if (publicar !== undefined) setPublicando(false);
      }
      })();

      salvandoRef.current = tarefa;
      try {
        return await tarefa;
      } finally {
        if (salvandoRef.current === tarefa) salvandoRef.current = null;
      }
    },
    [title, subtitle, tag, slug, corpo]
  );

  const agendarSalvamento = useCallback(() => {
    if (relogio.current) clearTimeout(relogio.current);
    relogio.current = setTimeout(() => {
      if (title.trim()) void salvar();
    }, ESPERA_PARA_SALVAR);
  }, [salvar, title]);

  useEffect(() => {
    return () => {
      if (relogio.current) clearTimeout(relogio.current);
    };
  }, []);

  function aoDigitar() {
    setCorpo(folha.current?.innerHTML ?? "");
    setTitulos(lerTitulos());
    agendarSalvamento();
  }

  function guardarSelecao() {
    const selecao = window.getSelection();
    if (selecao && selecao.rangeCount > 0) selecaoGuardada.current = selecao.getRangeAt(0).cloneRange();
  }

  function devolverSelecao() {
    const guardada = selecaoGuardada.current;
    if (!guardada) return;
    const selecao = window.getSelection();
    selecao?.removeAllRanges();
    selecao?.addRange(guardada);
  }

  function comando(nome: string, valor?: string) {
    folha.current?.focus();
    devolverSelecao();
    document.execCommand(nome, false, valor);
    aoDigitar();
  }

  function inserir(html: string) {
    folha.current?.focus();
    devolverSelecao();
    document.execCommand("insertHTML", false, html);
    aoDigitar();
  }

  async function enviarImagem(ficheiro: File) {
    setEnviandoImagem(true);
    setErro("");
    try {
      const supabase = getSupabaseClient();
      const extensao = (ficheiro.name.split(".").pop() || "png").toLowerCase();
      const caminho = `boletins/${Math.random().toString(36).slice(2)}_${Date.now()}.${extensao}`;
      const { error } = await supabase.storage.from("products").upload(caminho, ficheiro, {
        upsert: true,
        contentType: ficheiro.type || undefined,
      });
      if (error) throw error;
      const { data } = supabase.storage.from("products").getPublicUrl(caminho);
      const endereco = data?.publicUrl || "";
      if (!endereco) throw new Error("Falha ao gerar o endereço da imagem.");
      inserir(`<figure class="boletim-figura"><img src="${endereco}" alt="" /><figcaption>Legenda</figcaption></figure><p><br /></p>`);
    } catch (falha) {
      setErro(falha instanceof Error ? falha.message : "Falha ao enviar a imagem.");
    } finally {
      setEnviandoImagem(false);
    }
  }

  function aplicarPainel() {
    const endereco = enderecoDoLink.trim();
    if (!endereco) return;
    if (painelDeLink === "botao") {
      const rotulo = rotuloDoBotao.trim() || "Saiba mais";
      inserir(
        `<div class="boletim-botao"><a href="${endereco}" target="_blank">${rotulo}</a></div><p><br /></p>`
      );
    } else {
      comando("createLink", endereco);
    }
    setPainelDeLink("");
    setEnderecoDoLink("");
    setRotuloDoBotao("");
  }

  const palavras = useMemo(() => contarPalavras(corpo), [corpo]);
  const minutos = Math.max(1, Math.round(palavras / 200));
  const publicado = status === "published";
  const enderecoFinal = `${base}/${slug || faxinarSlug(title) || "..."}`;

  const ferramenta = "inline-flex h-8 min-w-8 items-center justify-center gap-1.5 rounded-lg px-2 text-slate-600 transition hover:bg-slate-100 hover:text-slate-900";

  return (
    <div className="min-h-screen bg-white font-sans">
      {/* -------------------------------------------------- barra de cima */}
      <div className="flex flex-wrap items-center gap-3 border-b border-slate-200 px-5 py-2.5">
        <Link href="/boletins" className="inline-flex items-center gap-1.5 text-sm font-medium text-slate-400 hover:text-slate-900">
          <ArrowLeft size={15} />
          Boletins
        </Link>
        <span className="text-slate-300">/</span>
        <span className="max-w-[320px] truncate text-sm font-semibold text-slate-900">{title || "Sem título"}</span>
        <span
          className={[
            "rounded-md border px-2 py-0.5 text-[11px] font-bold",
            publicado ? "border-emerald-200 bg-emerald-50 text-emerald-700" : "border-amber-200 bg-amber-50 text-amber-800",
          ].join(" ")}
        >
          {publicado ? "Publicado" : "Rascunho"}
        </span>

        <div className="ml-auto flex items-center gap-2">
          <span className="text-xs text-slate-400">
            {salvando ? "Salvando…" : salvoEm ? `Salvo às ${salvoEm}` : "Sem alterações"}
          </span>
          {publicado && slug ? (
            <a
              href={enderecoFinal}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex h-9 items-center gap-1.5 rounded-lg px-3 text-sm font-medium text-slate-600 transition hover:bg-slate-100"
            >
              <ExternalLink size={14} />
              Ver publicado
            </a>
          ) : null}
          <button
            type="button"
            onClick={() => void salvar(!publicado)}
            disabled={publicando}
            className={[
              "h-9 rounded-lg px-4 text-sm font-bold text-white transition disabled:opacity-50",
              publicado ? "bg-slate-700 hover:bg-slate-600" : "bg-indigo-600 hover:bg-indigo-500",
            ].join(" ")}
          >
            {publicado ? "Despublicar" : "Publicar"}
          </button>
        </div>
      </div>

      <div className="grid min-h-[calc(100vh-52px)] lg:grid-cols-[248px_minmax(0,1fr)]">
        {/* ------------------------------------------------ sumário */}
        <aside className="hidden border-r border-slate-200 bg-slate-50/60 p-5 lg:block">
          <h4 className="mb-3 text-[11px] font-bold uppercase tracking-[0.1em] text-slate-400">Neste boletim</h4>
          {titulos.length === 0 ? (
            <p className="px-2 text-[13px] leading-relaxed text-slate-400">
              Os títulos que você escrever aparecem aqui.
            </p>
          ) : (
            titulos.map((titulo) => (
              <button
                key={titulo.id}
                type="button"
                onClick={() => {
                  folha.current?.querySelector(`[data-sumario="${titulo.id}"]`)?.scrollIntoView({ behavior: "smooth", block: "center" });
                }}
                className={[
                  "block w-full truncate border-l-2 border-transparent py-1.5 pr-2 text-left text-[13.5px] text-slate-600 transition hover:text-slate-900",
                  titulo.nivel === 3 ? "pl-6 text-[13px] text-slate-400" : "pl-3",
                ].join(" ")}
              >
                {titulo.texto}
              </button>
            ))
          )}

          <div className="my-5 h-px bg-slate-200" />
          <h4 className="mb-3 text-[11px] font-bold uppercase tracking-[0.1em] text-slate-400">Ajustes</h4>

          <label className="block px-1 pb-3">
            <span className="text-xs font-semibold text-slate-500">Endereço</span>
            <input
              value={slug}
              onChange={(e) => setSlug(faxinarSlug(e.target.value))}
              onBlur={() => agendarSalvamento()}
              placeholder={faxinarSlug(title) || "endereco-do-aviso"}
              className="mt-1 w-full rounded-lg border border-slate-200 bg-white px-2.5 py-1.5 text-[13px] font-semibold text-indigo-700 outline-none focus:border-slate-400"
            />
            <span className="mt-1 block break-all text-[11px] text-slate-400">{enderecoFinal}</span>
          </label>

          <label className="block px-1 pb-3">
            <span className="text-xs font-semibold text-slate-500">Etiqueta da capa</span>
            <input
              value={tag}
              onChange={(e) => setTag(e.target.value)}
              onBlur={() => agendarSalvamento()}
              placeholder="Novidade"
              className="mt-1 w-full rounded-lg border border-slate-200 bg-white px-2.5 py-1.5 text-[13px] outline-none focus:border-slate-400"
            />
          </label>
        </aside>

        {/* ------------------------------------------------ folha */}
        <div className="min-w-0">
          <div className="sticky top-0 z-10 flex flex-wrap items-center gap-0.5 border-b border-slate-200 bg-white/92 px-4 py-1.5 backdrop-blur">
            <select
              onChange={(e) => {
                comando("formatBlock", e.target.value);
                e.target.value = "p";
              }}
              defaultValue="p"
              className="mr-1 h-8 rounded-lg border border-slate-200 bg-white px-2 text-[13px] font-semibold text-slate-800 outline-none"
            >
              <option value="p">Texto normal</option>
              <option value="h2">Título de seção</option>
              <option value="h3">Subtítulo</option>
            </select>

            <span className="mx-1.5 h-5 w-px bg-slate-200" />
            <button type="button" className={ferramenta} title="Negrito" onClick={() => comando("bold")}><Bold size={15} /></button>
            <button type="button" className={ferramenta} title="Itálico" onClick={() => comando("italic")}><Italic size={15} /></button>
            <button type="button" className={ferramenta} title="Riscado" onClick={() => comando("strikeThrough")}><Strikethrough size={15} /></button>
            <button
              type="button"
              className={ferramenta}
              title="Link"
              onClick={() => {
                guardarSelecao();
                setPainelDeLink("link");
              }}
            >
              <Link2 size={15} />
            </button>

            <span className="mx-1.5 h-5 w-px bg-slate-200" />
            <button type="button" className={ferramenta} title="Lista" onClick={() => comando("insertUnorderedList")}><List size={15} /></button>
            <button type="button" className={ferramenta} title="Lista numerada" onClick={() => comando("insertOrderedList")}><ListOrdered size={15} /></button>
            <button type="button" className={ferramenta} title="Citação" onClick={() => comando("formatBlock", "blockquote")}><Quote size={15} /></button>

            <span className="mx-1.5 h-5 w-px bg-slate-200" />
            <button
              type="button"
              className={`${ferramenta} text-[13px] font-semibold`}
              title="Imagem"
              onClick={() => {
                guardarSelecao();
                arquivo.current?.click();
              }}
              disabled={enviandoImagem}
            >
              <IconeImagem size={15} />
              {enviandoImagem ? "Enviando…" : "Imagem"}
            </button>
            <button
              type="button"
              className={`${ferramenta} text-[13px] font-semibold`}
              title="Botão"
              onClick={() => {
                guardarSelecao();
                setPainelDeLink("botao");
              }}
            >
              <SquareArrowOutUpRight size={15} />
              Botão
            </button>
            <button
              type="button"
              className={`${ferramenta} text-[13px] font-semibold`}
              title="Divisória"
              onClick={() => inserir("<hr /><p><br /></p>")}
            >
              <Minus size={15} />
              Divisória
            </button>

            <span className="mx-1.5 h-5 w-px bg-slate-200" />
            <button
              type="button"
              className={`${ferramenta} text-[13px] font-semibold`}
              title="Destaque"
              onClick={() => inserir(ANDAIME_DESTAQUE)}
            >
              <Quote size={15} />
              Destaque
            </button>
            <button
              type="button"
              className={`${ferramenta} text-[13px] font-semibold`}
              title="Cartões de preço"
              onClick={() => inserir(ANDAIME_PRECOS)}
            >
              <Tag size={15} />
              Preços
            </button>
            <button
              type="button"
              className={`${ferramenta} text-[13px] font-semibold`}
              title="Tabela de comparação"
              onClick={() => inserir(ANDAIME_TABELA)}
            >
              <Table size={15} />
              Tabela
            </button>
            <button
              type="button"
              className={`${ferramenta} text-[13px] font-semibold`}
              title="Gráfico de barras"
              onClick={() => inserir(ANDAIME_BARRAS)}
            >
              <BarChart3 size={15} />
              Barras
            </button>

            <input
              ref={arquivo}
              type="file"
              accept="image/*"
              className="hidden"
              onChange={(e) => {
                const escolhido = e.target.files?.[0] || null;
                e.target.value = "";
                if (escolhido) void enviarImagem(escolhido);
              }}
            />
          </div>

          {painelDeLink ? (
            <div className="flex flex-wrap items-end gap-2 border-b border-slate-200 bg-slate-50 px-4 py-3">
              {painelDeLink === "botao" ? (
                <label className="block">
                  <span className="text-xs font-semibold text-slate-500">Texto do botão</span>
                  <input
                    value={rotuloDoBotao}
                    onChange={(e) => setRotuloDoBotao(e.target.value)}
                    placeholder="Saiba mais"
                    className="mt-1 h-9 w-48 rounded-lg border border-slate-200 bg-white px-2.5 text-sm outline-none focus:border-slate-400"
                  />
                </label>
              ) : null}
              <label className="block flex-1 min-w-[240px]">
                <span className="text-xs font-semibold text-slate-500">Endereço</span>
                <input
                  value={enderecoDoLink}
                  onChange={(e) => setEnderecoDoLink(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      e.preventDefault();
                      aplicarPainel();
                    }
                  }}
                  autoFocus
                  placeholder="https://..."
                  className="mt-1 h-9 w-full rounded-lg border border-slate-200 bg-white px-2.5 text-sm outline-none focus:border-slate-400"
                />
              </label>
              <button type="button" onClick={aplicarPainel} className="h-9 rounded-lg bg-slate-900 px-4 text-sm font-bold text-white">
                Aplicar
              </button>
              <button
                type="button"
                onClick={() => setPainelDeLink("")}
                className="h-9 rounded-lg border border-slate-200 bg-white px-4 text-sm font-medium text-slate-600"
              >
                Cancelar
              </button>
            </div>
          ) : null}

          {erro ? (
            <div className="border-b border-rose-200 bg-rose-50 px-4 py-2.5 text-sm text-rose-700">{erro}</div>
          ) : null}

          <div className="mx-auto max-w-[768px] px-6 pb-24 pt-11">
            <textarea
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              onBlur={() => agendarSalvamento()}
              rows={1}
              placeholder="Título do boletim"
              className="w-full resize-none overflow-hidden border-0 text-[38px] font-extrabold leading-[1.1] tracking-[-0.032em] text-slate-900 outline-none placeholder:text-slate-300"
              style={{ height: "auto", minHeight: "44px" }}
              onInput={(e) => {
                const campo = e.currentTarget;
                campo.style.height = "auto";
                campo.style.height = `${campo.scrollHeight}px`;
              }}
            />
            <input
              value={subtitle}
              onChange={(e) => setSubtitle(e.target.value)}
              onBlur={() => agendarSalvamento()}
              placeholder="Uma linha explicando o assunto"
              className="mt-3 w-full border-0 text-[17px] leading-[1.55] text-slate-400 outline-none placeholder:text-slate-300"
            />
            <div className="my-7 h-px bg-slate-200" />

            <div
              ref={folha}
              contentEditable
              suppressContentEditableWarning
              onInput={aoDigitar}
              onBlur={guardarSelecao}
              onKeyUp={guardarSelecao}
              onMouseUp={guardarSelecao}
              data-vazio={corpo.trim() ? undefined : "1"}
              className="boletim-folha min-h-[320px] outline-none"
            />
          </div>

          <div className="sticky bottom-0 flex flex-wrap items-center gap-4 border-t border-slate-200 bg-white/94 px-4 py-2.5 text-xs text-slate-400 backdrop-blur">
            <span>
              <b className="font-bold text-slate-600">{palavras}</b> palavras
            </span>
            <span>
              <b className="font-bold text-slate-600">{minutos} min</b> de leitura
            </span>
            <span className="ml-auto break-all">{enderecoFinal}</span>
          </div>
        </div>
      </div>
    </div>
  );
}
