"use client";

import React, { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";

import {
  Type,
  SquareMousePointer,
  Image as ImageIcon,
  Minus,
  Columns2,
  Smartphone,
  Monitor,
  Code,
  ArrowUp,
  ArrowDown,
  Copy,
  Trash2,
  Upload,
  Sparkles,
  Eye,
  Save,
  Send,
  Plus,
  Palette,
  Layers,
  FileCode,
  CheckCircle2,
  SlidersHorizontal,
  AlignLeft,
  AlignCenter,
  AlignRight,
  AlignJustify,
  ArrowLeft,
  Loader2,
  ArrowRight,
  List,
  ExternalLink,
  MoveVertical,
  Share2,
  PlayCircle,
  Braces,
  X as XIcon,
  Square,
  Circle,
} from "lucide-react";

import {
  useCampaignEditorStore,
  EditorBlock,
  ButtonBlockContent,
  ImageBlockContent,
  TextBlockContent,
  DividerBlockContent,
  SpacerBlockContent,
  SocialBlockContent,
  SocialPlatform,
  VideoBlockContent,
  HtmlSnippetBlockContent,
  SOCIAL_PLATFORM_META,
} from "../hooks/use-campaign-editor-store";
import { useSendersStore } from "@/modules/senders/hooks/use-senders-store";
import { getSendersByUserAction } from "@/modules/senders/actions/get-senders-by-user-action";
import { sendTestAction } from "../actions/send-test-action";
import { createCampaignAction } from "../actions/create-campaign-action";
import { Button } from "@/shared/components/ui/button";
import { Input } from "@/shared/components/ui/input";
import { Label } from "@/shared/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/shared/components/ui/select";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/shared/components/ui/tabs";
import { Badge } from "@/shared/components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/shared/components/ui/dialog";

// Preset Color Swatches for quick styling
const COLOR_SWATCHES = [
  "#2563eb", // ActiveCampaign Blue
  "#0284c7", // Sky Blue
  "#10b981", // Emerald
  "#8b5cf6", // Purple
  "#ec4899", // Pink
  "#f43f5e", // Rose
  "#f59e0b", // Amber
  "#0f172a", // Slate Dark
  "#ffffff", // White
];

interface CampaignEditorViewProps {
  userEmail?: string | null;
}

export function CampaignEditorView({ userEmail }: CampaignEditorViewProps) {
  const router = useRouter();

  const {
    title,
    subject,
    senderId,
    htmlBody,
    blocks,
    selectedBlockId,
    activeTab,
    previewDevice,
    editorMode,
    isImageModalOpen,
    pendingImageBlockId,
    setSenderId,
    setHtmlBody,
    setPreviewDevice,
    setActiveTab,
    setEditorMode,
    selectBlock,
    addBlock,
    updateBlock,
    removeBlock,
    moveBlock,
    duplicateBlock,
    openImageModal,
    closeImageModal,
  } = useCampaignEditorStore();
  const { senders, setSenders } = useSendersStore();

  // Local state for image upload modal tab & inputs
  const [imageModalTab, setImageModalTab] = useState<"file" | "url">("file");
  const [modalImageSrc, setModalImageSrc] = useState("");
  const [modalImageAlt, setModalImageAlt] = useState("");
  const [modalImageWidth, setModalImageWidth] = useState("100%");
  const [modalImageHeight, setModalImageHeight] = useState("auto");
  const [modalImageLink, setModalImageLink] = useState("");

  // Saving state & Save Preview Modal state
  const [isSaving, setIsSaving] = useState(false);
  const [isPreviewSavedModalOpen, setIsPreviewSavedModalOpen] = useState(false);
  const [savedCampaignData, setSavedCampaignData] = useState<{
    id: string;
    title: string;
    subject: string;
    htmlBody: string;
    senderName: string;
  } | null>(null);

  // Raw HTML edit mode state
  const [rawHtmlCode, setRawHtmlCode] = useState(htmlBody);

  // Test Send Modal state
  const [isTestSendModalOpen, setIsTestSendModalOpen] = useState(false);
  const [testSendEmail, setTestSendEmail] = useState("");
  const [isSendingTest, setIsSendingTest] = useState(false);

  useEffect(() => {
    // Fetch available senders if empty
    getSendersByUserAction()
      .then(({ senders: data }) => {
        if (data.length > 0) {
          setSenders(data);
          if (!senderId) {
            setSenderId(data[0].id);
          }
        }
      })
      .catch(() => {
        // Fallback to store default senders
      });
  }, [senderId, setSenderId, setSenders]);

  useEffect(() => {
    // Pre-fill the test send modal with the logged-in user's own e-mail
    if (userEmail) {
      setTestSendEmail((current) => current || userEmail);
    }
  }, [userEmail]);

  useEffect(() => {
    setRawHtmlCode(htmlBody);
  }, [htmlBody]);

  const selectedBlock = blocks.find((b) => b.id === selectedBlockId);

  // Safe HTML body for iframe preview: injects <base target="_blank"> so all link clicks open safely in a new tab!
  const iframeSafeHtml = htmlBody.includes("<head>")
    ? htmlBody.replace("<head>", '<head><base target="_blank">')
    : `<base target="_blank">${htmlBody}`;

  // Handle local file upload in Image Modal
  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (event) => {
        if (event.target?.result) {
          setModalImageSrc(event.target.result as string);
          toast.success("Imagem carregada com sucesso!");
        }
      };
      reader.readAsDataURL(file);
    }
  };

  // Confirm image insertion from modal
  const handleApplyImageModal = () => {
    if (!modalImageSrc) {
      toast.error("Por favor, selecione um arquivo de imagem ou informe a URL.");
      return;
    }

    if (pendingImageBlockId) {
      updateBlock(pendingImageBlockId, {
        src: modalImageSrc,
        alt: modalImageAlt,
        width: modalImageWidth,
        height: modalImageHeight,
        linkUrl: modalImageLink,
      });
      toast.success("Bloco de imagem atualizado!");
    } else {
      const newId = addBlock("image");
      updateBlock(newId, {
        src: modalImageSrc,
        alt: modalImageAlt,
        width: modalImageWidth,
        height: modalImageHeight,
        linkUrl: modalImageLink,
      });
      toast.success("Nova imagem inserida no e-mail!");
    }

    closeImageModal();
    setModalImageSrc("");
    setModalImageAlt("");
    setModalImageLink("");
  };

  // Save Campaign to Database and Open Preview Modal
  const handleSaveDraft = async () => {
    const finalTitle = title.trim() || "Nova Campanha de E-mail";
    const finalSubject = subject.trim() || "Confira as nossas novidades";

    setIsSaving(true);
    try {
      const activeSender = senders.find((s) => s.id === senderId) || senders[0];
      const campaign = await createCampaignAction({
        title: finalTitle,
        subject: finalSubject,
        htmlBody,
        senderId: senderId || senders[0]?.id || "",
      });

      setSavedCampaignData({
        id: campaign.id,
        title: campaign.title || title,
        subject: campaign.subject || subject,
        htmlBody: campaign.htmlBody || htmlBody,
        senderName: activeSender?.name || "Remetente Principal",
      });

      toast.success(`Campanha "${campaign.title}" salva com sucesso no banco de dados!`);
      setIsPreviewSavedModalOpen(true);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Erro ao salvar campanha no servidor.");
    } finally {
      setIsSaving(false);
    }
  };

  const handleOpenPreviewInNewTab = () => {
    const blob = new Blob([iframeSafeHtml], { type: "text/html" });
    const url = URL.createObjectURL(blob);
    window.open(url, "_blank", "noopener,noreferrer");
    setTimeout(() => URL.revokeObjectURL(url), 30000);
  };

  const handleSendTest = () => {
    setIsTestSendModalOpen(true);
  };

  const handleConfirmSendTest = async () => {
    const recipient = testSendEmail.trim();
    if (!recipient) {
      toast.error("Informe um e-mail de destino para o teste.");
      return;
    }

    const finalSubject = subject.trim() || "Confira as nossas novidades";

    setIsSendingTest(true);
    try {
      await sendTestAction({
        subject: finalSubject,
        htmlBody,
        senderId: senderId || senders[0]?.id || "",
        testEmail: recipient,
      });

      toast.success(`E-mail de teste enviado para ${recipient}!`, {
        description: "Verifique a caixa de entrada em instantes.",
      });
      setIsTestSendModalOpen(false);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Não foi possível enviar o e-mail de teste.");
    } finally {
      setIsSendingTest(false);
    }
  };

  // Shared canvas content rendered both in the plain card view (desktop) and inside the iPhone mockup frame (mobile presentation view)
  const emailCanvasContent = (
    <>
      {/* Visual Header bar indicator */}
      <div className="border-b border-slate-100 pb-3 mb-6 flex flex-col sm:flex-row sm:items-center justify-between gap-1.5 text-slate-400 text-xs">
        <span className="font-bold text-slate-500 uppercase tracking-wider text-[10px] flex items-center gap-1.5">
          <span className="w-2 h-2 rounded-full bg-emerald-500 animate-ping inline-block" />
          {editorMode === "custom-html" ? "Arte HTML Personalizada (Live Render)" : "Pré-visualização do E-mail"}
        </span>
        <span className="text-[11px] text-slate-400 font-mono truncate">De: {senders.find((s) => s.id === senderId)?.fromEmail || "suaempresa@email.com"}</span>
      </div>

      {/* IF CUSTOM HTML MODE: Render exact pasted HTML artwork inside an iframe safely with target="_blank" */}
      {editorMode === "custom-html" ? (
        <div className="w-full min-h-[500px] flex flex-col animate-in fade-in-50 duration-300">
          <div className="mb-3 flex flex-col sm:flex-row sm:items-center justify-between gap-2 text-xs text-blue-700 bg-blue-50/90 border border-blue-200 p-3 rounded-xl shadow-xs">
            <span className="flex items-center gap-2 font-medium">
              <CheckCircle2 className="w-4 h-4 text-blue-600 shrink-0" />
              Exibindo a arte exata do seu HTML colado em tempo real
            </span>
            <div className="flex items-center gap-3 shrink-0">
              <button
                type="button"
                onClick={handleOpenPreviewInNewTab}
                className="flex items-center gap-1.5 text-[11px] font-semibold text-blue-700 hover:text-blue-900 bg-white border border-blue-200 hover:border-blue-300 px-2.5 py-1.5 rounded-lg transition-colors shadow-xs"
              >
                <ExternalLink className="w-3.5 h-3.5" />
                Visualizar Newsletter
              </button>
              <button
                type="button"
                onClick={() => setActiveTab("html")}
                className="underline text-[11px] font-semibold text-blue-700 hover:text-blue-900"
              >
                Editar Código
              </button>
            </div>
          </div>
          <iframe
            srcDoc={iframeSafeHtml}
            title="Arte HTML do E-mail"
            className="w-full min-h-[480px] border-0 rounded-xl shadow-inner bg-white"
            sandbox="allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"
          />
        </div>
      ) : (
        /* IF BLOCKS MODE: Render interactive blocks tree */
        <div>
          {blocks.length === 0 ? (
            <div className="h-64 border-2 border-dashed border-slate-300 rounded-2xl flex flex-col items-center justify-center p-6 text-center text-slate-400">
              <Plus className="w-8 h-8 mb-2 text-slate-400 animate-bounce" />
              <p className="text-sm font-semibold text-slate-700">Arraste ou clique nos blocos do painel direito para começar</p>
              <p className="text-xs text-slate-400 mt-1">Botões, Imagens, Textos e Divisores dinâmicos</p>
            </div>
          ) : (
            <div className="space-y-4">
              {blocks.map((block) => {
                const isSelected = selectedBlockId === block.id;
                const bContent = block.content as Record<string, unknown>;

                return (
                  <div
                    key={block.id}
                    onClick={() => {
                      selectBlock(block.id);
                      setActiveTab("styles");
                    }}
                    className={`group relative transition-all duration-200 rounded-xl p-2.5 cursor-pointer border-2 ${
                      isSelected
                        ? "border-blue-600 bg-blue-50/50 shadow-lg ring-4 ring-blue-500/20 scale-[1.008]"
                        : "border-transparent hover:border-slate-300 hover:bg-slate-50/80"
                    }`}
                  >
                    {/* Floating Block Actions Bar on Hover / Selection */}
                    <div
                      className={`absolute -top-4 right-3 z-20 flex items-center gap-1 bg-slate-900 text-white rounded-lg px-2 py-1 shadow-xl transition-all duration-200 ${
                        isSelected ? "opacity-100 scale-100" : "opacity-0 group-hover:opacity-100 scale-95"
                      }`}
                      onClick={(e) => e.stopPropagation()}
                    >
                      <button
                        title="Mover para cima"
                        onClick={() => moveBlock(block.id, "up")}
                        className="p-1 hover:bg-slate-800 rounded-md text-slate-300 hover:text-white transition-colors"
                      >
                        <ArrowUp className="w-3.5 h-3.5" />
                      </button>
                      <button
                        title="Mover para baixo"
                        onClick={() => moveBlock(block.id, "down")}
                        className="p-1 hover:bg-slate-800 rounded-md text-slate-300 hover:text-white transition-colors"
                      >
                        <ArrowDown className="w-3.5 h-3.5" />
                      </button>
                      <button
                        title="Duplicar bloco"
                        onClick={() => duplicateBlock(block.id)}
                        className="p-1 hover:bg-slate-800 rounded-md text-slate-300 hover:text-white transition-colors"
                      >
                        <Copy className="w-3.5 h-3.5" />
                      </button>
                      <button
                        title="Excluir bloco"
                        onClick={() => removeBlock(block.id)}
                        className="p-1 hover:bg-red-900/80 rounded-md text-red-400 hover:text-red-100 transition-colors"
                      >
                        <Trash2 className="w-3.5 h-3.5" />
                      </button>
                    </div>

                    {/* Render Content per Type with Dynamic Two-Way Editable Elements */}
                    {block.type === "button" && (
                      <div style={{ textAlign: (bContent.align as "left" | "center" | "right") || "center", padding: `${(bContent.paddingY as number) || 10}px 0` }}>
                        <button
                          type="button"
                          onClick={(e) => {
                            e.preventDefault();
                            e.stopPropagation();
                            selectBlock(block.id);
                            setActiveTab("styles");
                          }}
                          style={{
                            backgroundColor: (bContent.backgroundColor as string) || "#2563eb",
                            color: (bContent.textColor as string) || "#ffffff",
                            borderRadius: `${(bContent.borderRadius as number) || 8}px`,
                            padding: `${(bContent.paddingY as number) || 10}px ${(bContent.paddingX as number) || 24}px`,
                            fontSize: `${(bContent.fontSize as number) || 15}px`,
                            textTransform: bContent.uppercase ? "uppercase" : "none",
                            letterSpacing: `${(bContent.letterSpacing as number) || 0}px`,
                            width: bContent.fullWidth ? "100%" : undefined,
                            display: bContent.fullWidth ? "block" : "inline-block",
                          }}
                          className="font-bold shadow-md transition-all hover:brightness-110 active:scale-95 outline-none cursor-pointer border-0"
                        >
                          <span
                            contentEditable
                            suppressContentEditableWarning
                            onBlur={(e) => {
                              updateBlock(block.id, { text: e.currentTarget.innerText });
                            }}
                          >
                            {(bContent.text as string) || "Botão"}
                          </span>
                        </button>
                      </div>
                    )}

                    {block.type === "image" && (
                      <div style={{ textAlign: (bContent.align as "left" | "center" | "right") || "center", padding: "8px 0" }}>
                        {/* eslint-disable-next-line @next/next/no-img-element */}
                        <img
                          src={(bContent.src as string) || ""}
                          alt={(bContent.alt as string) || "Imagem de e-mail"}
                          style={{
                            width: (bContent.width as string) || "100%",
                            height: (bContent.height as string) || "auto",
                            borderRadius: `${(bContent.borderRadius as number) || 0}px`,
                            boxShadow: bContent.shadow ? "0 8px 24px rgba(0,0,0,0.15)" : undefined,
                          }}
                          className="inline-block object-cover max-w-full transition-all hover:scale-[1.01]"
                        />
                      </div>
                    )}

                    {block.type === "text" && (
                      <div
                        style={{
                          textAlign: (bContent.align as "left" | "center" | "right" | "justify") || "left",
                          color: (bContent.color as string) || "#334155",
                          fontSize: `${(bContent.fontSize as number) || 16}px`,
                          fontWeight: (bContent.fontWeight as "normal" | "medium" | "semibold" | "bold") || "normal",
                          lineHeight: (bContent.lineHeight as number) || 1.5,
                          letterSpacing: `${(bContent.letterSpacing as number) || 0}px`,
                          backgroundColor: (bContent.backgroundColor as string) || "transparent",
                          padding: bContent.backgroundColor ? "14px 16px" : undefined,
                          borderRadius: bContent.backgroundColor ? "8px" : undefined,
                        }}
                        className="py-1 focus:outline-none focus:ring-1 focus:ring-blue-400/30 rounded px-1 transition-all"
                        contentEditable
                        suppressContentEditableWarning
                        onBlur={(e) => {
                          updateBlock(block.id, { content: e.currentTarget.innerText });
                        }}
                      >
                        {(bContent.content as string) || ""}
                      </div>
                    )}

                    {block.type === "divider" && (
                      <div style={{ padding: `${(bContent.paddingY as number) || 12}px 0` }}>
                        <hr
                          style={{
                            borderColor: (bContent.color as string) || "#e2e8f0",
                            borderWidth: `${(bContent.height as number) || 1}px`,
                            borderStyle: (bContent.style as "solid" | "dashed" | "dotted") || "solid",
                            width: `${(bContent.widthPercent as number) || 100}%`,
                            margin: "0 auto",
                          }}
                        />
                      </div>
                    )}

                    {block.type === "spacer" && (
                      <div
                        style={{ height: `${(bContent.height as number) || 24}px` }}
                        className="relative flex items-center justify-center"
                      >
                        <div className="w-full border-t border-dashed border-slate-200" />
                        <span className="absolute bg-white px-2 text-[10px] text-slate-400 font-mono">
                          {(bContent.height as number) || 24}px
                        </span>
                      </div>
                    )}

                    {block.type === "social" && (
                      <div
                        style={{ textAlign: (bContent.align as "left" | "center" | "right") || "center" }}
                        className="py-2"
                      >
                        {((bContent.links as { platform: SocialPlatform; url: string }[]) || []).map((link, i) => {
                          const meta = SOCIAL_PLATFORM_META[link.platform];
                          const size = (bContent.iconSize as number) || 36;
                          return (
                            <span
                              key={i}
                              style={{
                                display: "inline-flex",
                                alignItems: "center",
                                justifyContent: "center",
                                width: size,
                                height: size,
                                backgroundColor: (bContent.iconColor as string) || meta.color,
                                color: "#fff",
                                borderRadius: bContent.iconShape === "square" ? "8px" : "50%",
                                fontSize: Math.round(size * 0.4),
                                fontWeight: 700,
                                margin: "0 6px",
                              }}
                            >
                              {meta.label}
                            </span>
                          );
                        })}
                      </div>
                    )}

                    {block.type === "video" && (
                      <div style={{ textAlign: (bContent.align as "left" | "center" | "right") || "center" }} className="py-2">
                        <div className="relative inline-block max-w-full">
                          {/* eslint-disable-next-line @next/next/no-img-element */}
                          <img
                            src={(bContent.thumbnailSrc as string) || ""}
                            alt={(bContent.alt as string) || "Vídeo"}
                            style={{
                              width: (bContent.width as string) || "100%",
                              borderRadius: `${(bContent.borderRadius as number) || 0}px`,
                            }}
                            className="max-w-full object-cover shadow-md"
                          />
                          <span className="absolute inset-0 flex items-center justify-center">
                            <span className="w-14 h-14 rounded-full bg-black/60 flex items-center justify-center">
                              <span className="ml-1 w-0 h-0 border-y-[10px] border-y-transparent border-l-[16px] border-l-white" />
                            </span>
                          </span>
                        </div>
                      </div>
                    )}

                    {block.type === "html-snippet" && (
                      <div className="py-1">
                        <div className="mb-1.5 flex items-center gap-1.5 text-[10px] font-bold text-teal-600 uppercase tracking-wide">
                          <Braces className="w-3 h-3" />
                          HTML Personalizado
                        </div>
                        <div
                          className="rounded-lg border border-dashed border-teal-300/70 bg-teal-50/40 p-2"
                          dangerouslySetInnerHTML={{ __html: (bContent.html as string) || "" }}
                        />
                      </div>
                    )}

                    {block.type === "two-column" && (
                      <div className="grid grid-cols-2 gap-4 py-2 border border-dashed border-slate-300 p-3 rounded-xl bg-slate-50/70">
                        <div className="p-2 border border-slate-200 rounded-lg bg-white min-h-16">
                          <span className="text-[10px] text-slate-400 font-bold uppercase block mb-1">Coluna 1</span>
                          {((bContent.leftBlocks as EditorBlock[]) || []).map((lb) => (
                            <div key={lb.id} className="text-xs text-slate-700 font-medium">
                              {lb.type === "text" ? (lb.content as TextBlockContent).content : lb.type}
                            </div>
                          ))}
                        </div>
                        <div className="p-2 border border-slate-200 rounded-lg bg-white min-h-16">
                          <span className="text-[10px] text-slate-400 font-bold uppercase block mb-1">Coluna 2</span>
                          {((bContent.rightBlocks as EditorBlock[]) || []).map((rb) => (
                            <div key={rb.id} className="text-xs text-slate-700 font-medium">
                              {rb.type === "button" ? (rb.content as ButtonBlockContent).text : rb.type}
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}
    </>
  );

  return (
    <div className="flex flex-col min-h-screen bg-[#0a0e1a] text-slate-100 antialiased font-sans">
      {/* ------------------------------------------------------------- */}
      {/* TOP HEADER & CAMPAIGN CONFIGURATION FORM (ActiveCampaign Style) */}
      {/* ------------------------------------------------------------- */}
      <header className="sticky top-0 z-30 border-b border-white/5 bg-[#0a0e1a]/85 backdrop-blur-2xl px-3 sm:px-4 lg:px-6 py-3 sm:py-3.5 shadow-2xl shadow-black/40">
        <div className="flex flex-col xl:flex-row xl:items-center justify-between gap-3 sm:gap-4">
          <div className="flex items-center gap-2.5 sm:gap-3 min-w-0">
            {/* Back Button to previous screen */}
            <Button
              variant="outline"
              size="sm"
              onClick={() => router.push("/")}
              className="shrink-0 border-white/10 bg-white/5 text-slate-300 hover:bg-white/10 hover:text-white text-xs h-9 font-semibold rounded-xl"
            >
              <ArrowLeft className="w-4 h-4 sm:mr-1.5" />
              <span className="hidden sm:inline">Voltar</span>
            </Button>

            <div className="shrink-0 p-2 rounded-xl bg-gradient-to-br from-blue-600 via-indigo-600 to-purple-600 shadow-lg shadow-blue-500/25 text-white">
              <Sparkles className="w-5 h-5" />
            </div>
            <div className="min-w-0">
              <h1 className="text-base sm:text-lg font-extrabold text-white tracking-tight truncate">Editor Visual de E-mails</h1>
            </div>
          </div>

          {/* Quick Actions & Preview Switcher */}
          <div className="flex items-center gap-2 sm:gap-3 flex-wrap w-full xl:w-auto">
            <div className="flex items-center bg-white/[0.04] border border-white/10 rounded-xl p-1 shadow-inner">
              <Button
                variant="ghost"
                size="sm"
                className={`h-8 px-2.5 sm:px-3 text-xs font-semibold rounded-lg transition-all ${
                  previewDevice === "desktop"
                    ? "bg-gradient-to-r from-blue-600 to-indigo-600 text-white shadow-md shadow-blue-600/30"
                    : "text-slate-400 hover:text-slate-200"
                }`}
                onClick={() => setPreviewDevice("desktop")}
              >
                <Monitor className="w-3.5 h-3.5 sm:mr-1.5" />
                <span className="hidden sm:inline">Desktop</span>
              </Button>
              <Button
                variant="ghost"
                size="sm"
                className={`h-8 px-2.5 sm:px-3 text-xs font-semibold rounded-lg transition-all ${
                  previewDevice === "mobile"
                    ? "bg-gradient-to-r from-blue-600 to-indigo-600 text-white shadow-md shadow-blue-600/30"
                    : "text-slate-400 hover:text-slate-200"
                }`}
                onClick={() => setPreviewDevice("mobile")}
              >
                <Smartphone className="w-3.5 h-3.5 sm:mr-1.5" />
                <span className="hidden sm:inline">Mobile</span>
              </Button>
            </div>

            <Button
              variant="outline"
              size="sm"
              onClick={handleSendTest}
              className="border-white/10 bg-white/5 text-slate-300 hover:bg-white/10 hover:text-white text-xs h-9 font-medium transition-all rounded-xl"
            >
              <Send className="w-3.5 h-3.5 sm:mr-1.5 text-blue-400" />
              <span className="hidden sm:inline">Testar Envio</span>
            </Button>

            <Button
              size="sm"
              disabled={isSaving}
              onClick={handleSaveDraft}
              className="flex-1 xl:flex-none bg-gradient-to-r from-blue-600 via-indigo-600 to-blue-500 hover:from-blue-500 hover:to-indigo-500 text-white font-semibold text-xs h-9 shadow-lg shadow-blue-600/30 transition-all hover:scale-[1.02] active:scale-95 cursor-pointer rounded-xl"
            >
              {isSaving ? (
                <>
                  <Loader2 className="w-3.5 h-3.5 mr-1.5 animate-spin" />
                  Salvando...
                </>
              ) : (
                <>
                  <Save className="w-3.5 h-3.5 mr-1.5" />
                  Salvar Campanha
                </>
              )}
            </Button>
          </div>
        </div>
      </header>

      {/* ------------------------------------------------------------- */}
      {/* MAIN TWO-COLUMN VISUAL BUILDER WORKSPACE                      */}
      {/* ------------------------------------------------------------- */}
      <div className="flex-1 flex flex-col lg:flex-row overflow-hidden min-h-[calc(100vh-65px)]">
        {/* LEFT / CENTER PANEL: CANVA DE PINTURA (LIVE RENDER WITH DOT GRID) */}
        <main className="flex-1 bg-[#0a0e1a] bg-[radial-gradient(#1e293b_1px,transparent_1px)] [background-size:20px_20px] p-3 sm:p-4 md:p-8 flex flex-col items-center overflow-y-auto relative">
          <div className="w-full flex flex-col sm:flex-row items-center justify-between max-w-4xl mb-4 gap-3 text-xs text-slate-400">
            <div className="flex items-center gap-2">
              <Eye className="w-4 h-4 text-blue-400 animate-pulse" />
              <span className="font-semibold text-slate-300">Canvas Visual ActiveCampaign</span>
            </div>

            {/* Mode Switcher: Visual Blocks vs Pasted Raw HTML Artwork */}
            <div className="flex items-center w-full sm:w-auto bg-white/[0.04] border border-white/10 rounded-xl p-1 shadow-md">
              <button
                type="button"
                onClick={() => setEditorMode("blocks")}
                className={`flex-1 sm:flex-none px-3 py-1.5 rounded-lg text-xs font-semibold transition-all flex items-center justify-center gap-1.5 ${
                  editorMode === "blocks"
                    ? "bg-gradient-to-r from-blue-600 to-indigo-600 text-white shadow-md shadow-blue-600/30"
                    : "text-slate-400 hover:text-slate-200"
                }`}
              >
                <Layers className="w-3.5 h-3.5" />
                <span className="truncate">Construtor de Blocos</span>
              </button>
              <button
                type="button"
                onClick={() => setEditorMode("custom-html")}
                className={`flex-1 sm:flex-none px-3 py-1.5 rounded-lg text-xs font-semibold transition-all flex items-center justify-center gap-1.5 ${
                  editorMode === "custom-html"
                    ? "bg-gradient-to-r from-blue-600 to-indigo-600 text-white shadow-md shadow-blue-600/30"
                    : "text-slate-400 hover:text-slate-200"
                }`}
              >
                <FileCode className="w-3.5 h-3.5" />
                <span className="truncate">Arte HTML Colada</span>
              </button>
            </div>
          </div>

          {/* Email Preview Card Container with smooth responsive transition */}
          {previewDevice === "mobile" ? (
            /* ------------------------------------------------------------- */
            /* IPHONE MOCKUP FRAME — Presentation-ready mobile preview        */
            /* ------------------------------------------------------------- */
            <div className="relative mx-auto my-auto w-[380px] max-w-full shrink-0">
              <div className="relative bg-slate-950 rounded-[3.5rem] p-4 shadow-2xl shadow-black/60 border-[4px] border-slate-800">
                {/* Decorative side buttons */}
                <div className="absolute -left-1 top-32 w-1 h-8 bg-slate-700 rounded-l-sm" />
                <div className="absolute -left-1 top-44 w-1 h-14 bg-slate-700 rounded-l-sm" />
                <div className="absolute -left-1 top-60 w-1 h-14 bg-slate-700 rounded-l-sm" />
                <div className="absolute -right-1 top-40 w-1 h-16 bg-slate-700 rounded-r-sm" />

                {/* Screen */}
                <div className="relative bg-white rounded-[2.75rem] overflow-hidden h-[760px] flex flex-col">
                  {/* Dynamic Island */}
                  <div className="absolute top-3 left-1/2 -translate-x-1/2 w-28 h-7 bg-black rounded-full z-20" />

                  {/* Status Bar */}
                  <div className="shrink-0 h-12 flex items-end justify-between px-8 pb-2 text-xs font-bold text-slate-900">
                    <span>9:41</span>
                    <div className="flex items-center gap-1">
                      <span className="inline-block w-4 h-3 rounded-[1px] border border-slate-900 relative">
                        <span className="absolute inset-[1px] bg-slate-900 rounded-[0.5px]" />
                      </span>
                    </div>
                  </div>

                  {/* Scrollable e-mail content */}
                  <div className="flex-1 overflow-y-auto p-5 text-slate-900">{emailCanvasContent}</div>

                  {/* Home indicator */}
                  <div className="shrink-0 py-2 flex justify-center bg-white">
                    <div className="w-32 h-1 bg-slate-900/80 rounded-full" />
                  </div>
                </div>
              </div>
              <p className="mt-3 text-center text-[10px] text-slate-500 font-semibold flex items-center justify-center gap-1.5">
                <Smartphone className="w-3 h-3" />
                Simulação de iPhone para apresentação
              </p>
            </div>
          ) : (
            <div className="transition-all duration-300 ease-out bg-white rounded-2xl shadow-2xl shadow-black/50 overflow-hidden border border-slate-200/60 ring-1 ring-black/5 w-full max-w-[620px] min-h-[580px] p-4 sm:p-6 text-slate-900 relative my-auto">
              {emailCanvasContent}
            </div>
          )}
        </main>

        {/* ------------------------------------------------------------- */}
        {/* RIGHT SIDEBAR: TOOLBAR & INSPECTOR WITH SHADCN TABS            */}
        {/* ------------------------------------------------------------- */}
        <aside className="w-full lg:w-96 xl:w-[26rem] shrink-0 border-t lg:border-t-0 lg:border-l border-white/5 bg-[#0d1220]/95 flex flex-col h-auto lg:h-full max-h-[75vh] lg:max-h-none shadow-2xl backdrop-blur-md">
          <Tabs value={activeTab} onValueChange={(val) => setActiveTab(val as "blocks" | "styles" | "html")} className="flex-1 flex flex-col min-h-0">
            <div className="p-3 sm:p-4 border-b border-white/5 bg-black/20">
              <TabsList className="inline-flex justify-start w-fit max-w-full bg-white/[0.03] border border-white/10 p-1 rounded-xl gap-1">
                <TabsTrigger value="blocks" className="text-xs font-semibold py-2 px-3 data-[state=active]:bg-gradient-to-r data-[state=active]:from-blue-600 data-[state=active]:to-indigo-600 data-[state=active]:text-white transition-all rounded-lg flex items-center gap-1.5">
                  <Plus className="w-3.5 h-3.5" />
                  <span>Blocos</span>
                </TabsTrigger>
                <TabsTrigger value="styles" className="text-xs font-semibold py-2 px-3 data-[state=active]:bg-gradient-to-r data-[state=active]:from-blue-600 data-[state=active]:to-indigo-600 data-[state=active]:text-white transition-all rounded-lg flex items-center gap-1.5">
                  <Palette className="w-3.5 h-3.5" />
                  <span>Estilos</span>
                </TabsTrigger>
                <TabsTrigger value="html" className="text-xs font-semibold py-2 px-3 data-[state=active]:bg-gradient-to-r data-[state=active]:from-blue-600 data-[state=active]:to-indigo-600 data-[state=active]:text-white transition-all rounded-lg flex items-center gap-1.5">
                  <Code className="w-3.5 h-3.5" />
                  <span>HTML</span>
                </TabsTrigger>
              </TabsList>
            </div>

            {/* TAB 1: BLOCOS (DRAG / CLICK TO ADD) */}
            <TabsContent value="blocks" className="flex-1 p-4 space-y-4 overflow-y-auto">
              <div className="text-xs text-slate-400 font-semibold mb-2 flex items-center justify-between">
                <span>Elementos Disponíveis:</span>
                <span className="text-[10px] text-blue-400 font-normal">1-Clique para Inserir</span>
              </div>

              <div className="grid grid-cols-1 min-[420px]:grid-cols-2 gap-3">
                <button
                  type="button"
                  onClick={() => addBlock("button")}
                  className="flex flex-col items-center justify-center p-4 bg-white/[0.03] hover:bg-white/[0.06] border border-white/10 hover:border-blue-500/50 rounded-2xl transition-all duration-200 group text-left cursor-pointer hover:scale-[1.02] shadow-sm"
                >
                  <div className="p-3 rounded-xl bg-blue-500/10 text-blue-400 group-hover:scale-110 group-hover:bg-blue-600 group-hover:text-white transition-all mb-2">
                    <SquareMousePointer className="w-5 h-5" />
                  </div>
                  <span className="text-xs font-bold text-slate-100">Botão</span>
                  <span className="text-[10px] text-slate-400 mt-0.5">Call to Action</span>
                </button>

                <button
                  type="button"
                  onClick={() => openImageModal()}
                  className="flex flex-col items-center justify-center p-4 bg-white/[0.03] hover:bg-white/[0.06] border border-white/10 hover:border-emerald-500/50 rounded-2xl transition-all duration-200 group text-left cursor-pointer hover:scale-[1.02] shadow-sm"
                >
                  <div className="p-3 rounded-xl bg-emerald-500/10 text-emerald-400 group-hover:scale-110 group-hover:bg-emerald-600 group-hover:text-white transition-all mb-2">
                    <ImageIcon className="w-5 h-5" />
                  </div>
                  <span className="text-xs font-bold text-slate-100">Imagem</span>
                  <span className="text-[10px] text-slate-400 mt-0.5">Upload ou URL</span>
                </button>

                <button
                  type="button"
                  onClick={() => addBlock("text")}
                  className="flex flex-col items-center justify-center p-4 bg-white/[0.03] hover:bg-white/[0.06] border border-white/10 hover:border-indigo-500/50 rounded-2xl transition-all duration-200 group text-left cursor-pointer hover:scale-[1.02] shadow-sm"
                >
                  <div className="p-3 rounded-xl bg-indigo-500/10 text-indigo-400 group-hover:scale-110 group-hover:bg-indigo-600 group-hover:text-white transition-all mb-2">
                    <Type className="w-5 h-5" />
                  </div>
                  <span className="text-xs font-bold text-slate-100">Texto</span>
                  <span className="text-[10px] text-slate-400 mt-0.5">Parágrafo / Título</span>
                </button>

                <button
                  type="button"
                  onClick={() => addBlock("divider")}
                  className="flex flex-col items-center justify-center p-4 bg-white/[0.03] hover:bg-white/[0.06] border border-white/10 hover:border-amber-500/50 rounded-2xl transition-all duration-200 group text-left cursor-pointer hover:scale-[1.02] shadow-sm"
                >
                  <div className="p-3 rounded-xl bg-amber-500/10 text-amber-400 group-hover:scale-110 group-hover:bg-amber-600 group-hover:text-white transition-all mb-2">
                    <Minus className="w-5 h-5" />
                  </div>
                  <span className="text-xs font-bold text-slate-100">Divisor</span>
                  <span className="text-[10px] text-slate-400 mt-0.5">Linha de separação</span>
                </button>

                <button
                  type="button"
                  onClick={() => addBlock("spacer")}
                  className="flex flex-col items-center justify-center p-4 bg-white/[0.03] hover:bg-white/[0.06] border border-white/10 hover:border-cyan-500/50 rounded-2xl transition-all duration-200 group text-left cursor-pointer hover:scale-[1.02] shadow-sm"
                >
                  <div className="p-3 rounded-xl bg-cyan-500/10 text-cyan-400 group-hover:scale-110 group-hover:bg-cyan-600 group-hover:text-white transition-all mb-2">
                    <MoveVertical className="w-5 h-5" />
                  </div>
                  <span className="text-xs font-bold text-slate-100">Espaçador</span>
                  <span className="text-[10px] text-slate-400 mt-0.5">Respiro entre blocos</span>
                </button>

                <button
                  type="button"
                  onClick={() => addBlock("social")}
                  className="flex flex-col items-center justify-center p-4 bg-white/[0.03] hover:bg-white/[0.06] border border-white/10 hover:border-pink-500/50 rounded-2xl transition-all duration-200 group text-left cursor-pointer hover:scale-[1.02] shadow-sm"
                >
                  <div className="p-3 rounded-xl bg-pink-500/10 text-pink-400 group-hover:scale-110 group-hover:bg-pink-600 group-hover:text-white transition-all mb-2">
                    <Share2 className="w-5 h-5" />
                  </div>
                  <span className="text-xs font-bold text-slate-100">Redes Sociais</span>
                  <span className="text-[10px] text-slate-400 mt-0.5">Ícones com links</span>
                </button>

                <button
                  type="button"
                  onClick={() => addBlock("video")}
                  className="flex flex-col items-center justify-center p-4 bg-white/[0.03] hover:bg-white/[0.06] border border-white/10 hover:border-rose-500/50 rounded-2xl transition-all duration-200 group text-left cursor-pointer hover:scale-[1.02] shadow-sm"
                >
                  <div className="p-3 rounded-xl bg-rose-500/10 text-rose-400 group-hover:scale-110 group-hover:bg-rose-600 group-hover:text-white transition-all mb-2">
                    <PlayCircle className="w-5 h-5" />
                  </div>
                  <span className="text-xs font-bold text-slate-100">Vídeo</span>
                  <span className="text-[10px] text-slate-400 mt-0.5">Thumbnail com play</span>
                </button>

                <button
                  type="button"
                  onClick={() => addBlock("html-snippet")}
                  className="flex flex-col items-center justify-center p-4 bg-white/[0.03] hover:bg-white/[0.06] border border-white/10 hover:border-teal-500/50 rounded-2xl transition-all duration-200 group text-left cursor-pointer hover:scale-[1.02] shadow-sm"
                >
                  <div className="p-3 rounded-xl bg-teal-500/10 text-teal-400 group-hover:scale-110 group-hover:bg-teal-600 group-hover:text-white transition-all mb-2">
                    <Braces className="w-5 h-5" />
                  </div>
                  <span className="text-xs font-bold text-slate-100">HTML Custom</span>
                  <span className="text-[10px] text-slate-400 mt-0.5">Cole um trecho de código</span>
                </button>

                <button
                  type="button"
                  onClick={() => addBlock("two-column")}
                  className="min-[420px]:col-span-2 flex items-center gap-3 p-4 bg-white/[0.03] hover:bg-white/[0.06] border border-white/10 hover:border-purple-500/50 rounded-2xl transition-all duration-200 group text-left cursor-pointer hover:scale-[1.01] shadow-sm"
                >
                  <div className="p-3 rounded-xl bg-purple-500/10 text-purple-400 group-hover:scale-110 group-hover:bg-purple-600 group-hover:text-white transition-all">
                    <Columns2 className="w-5 h-5" />
                  </div>
                  <div>
                    <span className="text-xs font-bold text-slate-100 block">Bloco 2 Colunas</span>
                    <span className="text-[10px] text-slate-400">Layout lado a lado para imagens e chamadas</span>
                  </div>
                </button>
              </div>
            </TabsContent>

            {/* TAB 2: ESTILOS & PROPRIEDADES DO BLOCO SELECIONADO (DYNAMIC REACTIVE CONTROLS) */}
            <TabsContent value="styles" className="flex-1 p-4 overflow-y-auto space-y-4">
              {!selectedBlock ? (
                <div className="h-56 flex flex-col items-center justify-center text-center p-6 border border-dashed border-white/10 rounded-2xl text-slate-400 bg-black/20">
                  <SlidersHorizontal className="w-8 h-8 mb-2 text-slate-500 animate-pulse" />
                  <p className="text-xs font-bold text-slate-200">Nenhum bloco selecionado</p>
                  <p className="text-[11px] text-slate-500 mt-1">Clique em qualquer bloco na tela de pintura para ajustar cores, tamanhos e bordas em tempo real.</p>
                </div>
              ) : (
                <div className="space-y-5 animate-in fade-in-50 duration-200">
                  <div className="flex items-center justify-between border-b border-white/10 pb-3">
                    <div className="flex items-center gap-2">
                      <Badge className="bg-blue-600 text-white uppercase text-[10px] font-bold px-2 py-0.5 shadow-sm">
                        {selectedBlock.type}
                      </Badge>
                      <span className="text-xs font-extrabold text-slate-100">Configurador Dinâmico</span>
                    </div>
                    <span className="text-[10px] text-slate-400 font-mono">ID: {selectedBlock.id.slice(0, 10)}</span>
                  </div>

                  {/* CONFIGURADOR DE BOTÃO DYNAMIC & FLUID */}
                  {selectedBlock.type === "button" && (
                    <div className="space-y-4">
                      <div>
                        <Label className="text-xs text-slate-300 mb-1 block font-semibold">Texto do Botão</Label>
                        <Input
                          value={(selectedBlock.content as ButtonBlockContent).text}
                          onChange={(e) => updateBlock(selectedBlock.id, { text: e.target.value })}
                          className="bg-black/20 border-white/10 text-xs text-slate-100 focus:border-blue-500 font-medium"
                        />
                      </div>

                      <div>
                        <div className="flex items-center justify-between mb-1">
                          <Label className="text-xs text-slate-300 font-semibold">Link de Destino (URL)</Label>
                          {(selectedBlock.content as ButtonBlockContent).url && (
                            <a
                              href={(selectedBlock.content as ButtonBlockContent).url}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="text-[11px] text-blue-400 hover:underline flex items-center gap-1 font-medium"
                              title="Testar em nova aba"
                            >
                              Testar ↗
                            </a>
                          )}
                        </div>
                        <Input
                          value={(selectedBlock.content as ButtonBlockContent).url}
                          onChange={(e) => updateBlock(selectedBlock.id, { url: e.target.value })}
                          placeholder="https://suaempresa.com"
                          className="bg-black/20 border-white/10 text-xs text-slate-100 focus:border-blue-500 font-mono text-[11px]"
                        />
                      </div>

                      {/* Color Picker with Preset Swatches */}
                      <div>
                        <Label className="text-xs text-slate-300 mb-1.5 block font-semibold">Cor de Fundo do Botão</Label>
                        <div className="flex items-center gap-2 mb-2">
                          <input
                            type="color"
                            value={(selectedBlock.content as ButtonBlockContent).backgroundColor}
                            onChange={(e) => updateBlock(selectedBlock.id, { backgroundColor: e.target.value })}
                            className="w-9 h-9 rounded-lg border border-slate-700 bg-transparent cursor-pointer"
                          />
                          <Input
                            value={(selectedBlock.content as ButtonBlockContent).backgroundColor}
                            onChange={(e) => updateBlock(selectedBlock.id, { backgroundColor: e.target.value })}
                            className="bg-black/20 border-white/10 text-xs text-slate-100 uppercase font-mono font-semibold"
                          />
                        </div>
                        {/* Swatches */}
                        <div className="flex items-center gap-1.5 flex-wrap">
                          {COLOR_SWATCHES.map((hex) => (
                            <button
                              key={hex}
                              type="button"
                              onClick={() => updateBlock(selectedBlock.id, { backgroundColor: hex })}
                              style={{ backgroundColor: hex }}
                              className="w-5 h-5 rounded-full border border-slate-700 hover:scale-125 transition-transform cursor-pointer shadow-xs"
                              title={hex}
                            />
                          ))}
                        </div>
                      </div>

                      {/* Text Color Picker */}
                      <div>
                        <Label className="text-xs text-slate-300 mb-1 block font-semibold">Cor do Texto do Botão</Label>
                        <div className="flex items-center gap-2">
                          <input
                            type="color"
                            value={(selectedBlock.content as ButtonBlockContent).textColor}
                            onChange={(e) => updateBlock(selectedBlock.id, { textColor: e.target.value })}
                            className="w-9 h-9 rounded-lg border border-slate-700 bg-transparent cursor-pointer"
                          />
                          <Input
                            value={(selectedBlock.content as ButtonBlockContent).textColor}
                            onChange={(e) => updateBlock(selectedBlock.id, { textColor: e.target.value })}
                            className="bg-black/20 border-white/10 text-xs text-slate-100 uppercase font-mono font-semibold"
                          />
                        </div>
                      </div>

                      {/* Border Radius Slider */}
                      <div className="bg-black/20 p-3 rounded-xl border border-white/10">
                        <div className="flex justify-between items-center mb-1.5">
                          <Label className="text-xs text-slate-300 font-semibold">Arredondamento das Bordas</Label>
                          <span className="text-xs text-blue-400 font-bold font-mono bg-blue-500/10 px-2 py-0.5 rounded-md border border-blue-500/20">
                            {(selectedBlock.content as ButtonBlockContent).borderRadius}px
                          </span>
                        </div>
                        <input
                          type="range"
                          min="0"
                          max="40"
                          value={(selectedBlock.content as ButtonBlockContent).borderRadius}
                          onChange={(e) => updateBlock(selectedBlock.id, { borderRadius: Number(e.target.value) })}
                          className="w-full accent-blue-500 bg-slate-900 h-2 rounded-lg cursor-pointer"
                        />
                      </div>

                      {/* Alignment Segmented Control */}
                      <div>
                        <Label className="text-xs text-slate-300 mb-1.5 block font-semibold">Alinhamento</Label>
                        <div className="flex bg-black/20 p-1 rounded-xl border border-white/10">
                          {(["left", "center", "right"] as const).map((align) => (
                            <button
                              key={align}
                              type="button"
                              onClick={() => updateBlock(selectedBlock.id, { align })}
                              className={`flex-1 py-1.5 text-xs font-semibold rounded-lg transition-all flex items-center justify-center ${
                                (selectedBlock.content as ButtonBlockContent).align === align
                                  ? "bg-blue-600 text-white shadow-md"
                                  : "text-slate-400 hover:text-slate-200"
                              }`}
                            >
                              {align === "left" && <AlignLeft className="w-3.5 h-3.5" />}
                              {align === "center" && <AlignCenter className="w-3.5 h-3.5" />}
                              {align === "right" && <AlignRight className="w-3.5 h-3.5" />}
                            </button>
                          ))}
                        </div>
                      </div>

                      {/* Font Size Slider */}
                      <div className="bg-black/20 p-3 rounded-xl border border-white/10">
                        <div className="flex justify-between items-center mb-1.5">
                          <Label className="text-xs text-slate-300 font-semibold">Tamanho da Fonte</Label>
                          <span className="text-xs text-blue-400 font-bold font-mono bg-blue-500/10 px-2 py-0.5 rounded-md border border-blue-500/20">
                            {(selectedBlock.content as ButtonBlockContent).fontSize}px
                          </span>
                        </div>
                        <input
                          type="range"
                          min="12"
                          max="32"
                          value={(selectedBlock.content as ButtonBlockContent).fontSize}
                          onChange={(e) => updateBlock(selectedBlock.id, { fontSize: Number(e.target.value) })}
                          className="w-full accent-blue-500 bg-slate-900 h-2 rounded-lg cursor-pointer"
                        />
                      </div>

                      {/* Extra Style Toggles: Full Width & Uppercase */}
                      <div className="grid grid-cols-2 gap-3">
                        <button
                          type="button"
                          onClick={() =>
                            updateBlock(selectedBlock.id, { fullWidth: !(selectedBlock.content as ButtonBlockContent).fullWidth })
                          }
                          className={`flex items-center justify-center gap-1.5 py-2 rounded-xl text-xs font-semibold border transition-all ${
                            (selectedBlock.content as ButtonBlockContent).fullWidth
                              ? "bg-blue-600 border-blue-500 text-white"
                              : "bg-black/20 border-white/10 text-slate-400 hover:text-slate-200"
                          }`}
                        >
                          Largura Total
                        </button>
                        <button
                          type="button"
                          onClick={() =>
                            updateBlock(selectedBlock.id, { uppercase: !(selectedBlock.content as ButtonBlockContent).uppercase })
                          }
                          className={`flex items-center justify-center gap-1.5 py-2 rounded-xl text-xs font-semibold border transition-all uppercase ${
                            (selectedBlock.content as ButtonBlockContent).uppercase
                              ? "bg-blue-600 border-blue-500 text-white"
                              : "bg-black/20 border-white/10 text-slate-400 hover:text-slate-200"
                          }`}
                        >
                          Maiúsculas
                        </button>
                      </div>

                      {/* Letter Spacing Slider */}
                      <div className="bg-black/20 p-3 rounded-xl border border-white/10">
                        <div className="flex justify-between items-center mb-1.5">
                          <Label className="text-xs text-slate-300 font-semibold">Espaçamento de Letras</Label>
                          <span className="text-xs text-blue-400 font-bold font-mono bg-blue-500/10 px-2 py-0.5 rounded-md border border-blue-500/20">
                            {(selectedBlock.content as ButtonBlockContent).letterSpacing || 0}px
                          </span>
                        </div>
                        <input
                          type="range"
                          min="0"
                          max="4"
                          step="0.5"
                          value={(selectedBlock.content as ButtonBlockContent).letterSpacing || 0}
                          onChange={(e) => updateBlock(selectedBlock.id, { letterSpacing: Number(e.target.value) })}
                          className="w-full accent-blue-500 bg-slate-900 h-2 rounded-lg cursor-pointer"
                        />
                      </div>
                    </div>
                  )}

                  {/* CONFIGURADOR DE IMAGEM DYNAMIC */}
                  {selectedBlock.type === "image" && (
                    <div className="space-y-4">
                      <div>
                        <Label className="text-xs text-slate-300 mb-1 block font-semibold">Fonte da Imagem</Label>
                        <Button
                          type="button"
                          onClick={() => openImageModal(selectedBlock.id)}
                          className="w-full bg-slate-950 border border-slate-800 hover:bg-slate-800 text-slate-200 text-xs h-10 justify-center font-semibold rounded-xl"
                        >
                          <Upload className="w-4 h-4 mr-2 text-emerald-400" />
                          Carregar Foto ou Alterar URL
                        </Button>
                      </div>

                      <div>
                        <Label className="text-xs text-slate-300 mb-1 block font-semibold">URL Direta da Imagem</Label>
                        <Input
                          value={(selectedBlock.content as ImageBlockContent).src}
                          onChange={(e) => updateBlock(selectedBlock.id, { src: e.target.value })}
                          className="bg-black/20 border-white/10 text-xs text-slate-100 font-mono text-[11px]"
                        />
                      </div>

                      <div className="grid grid-cols-2 gap-3">
                        <div>
                          <Label className="text-xs text-slate-300 mb-1 block font-semibold">Largura</Label>
                          <Input
                            value={(selectedBlock.content as ImageBlockContent).width}
                            onChange={(e) => updateBlock(selectedBlock.id, { width: e.target.value })}
                            placeholder="100% ou 300px"
                            className="bg-black/20 border-white/10 text-xs text-slate-100"
                          />
                        </div>
                        <div>
                          <Label className="text-xs text-slate-300 mb-1 block font-semibold">Altura</Label>
                          <Input
                            value={(selectedBlock.content as ImageBlockContent).height}
                            onChange={(e) => updateBlock(selectedBlock.id, { height: e.target.value })}
                            placeholder="auto ou 200px"
                            className="bg-black/20 border-white/10 text-xs text-slate-100"
                          />
                        </div>
                      </div>

                      <div>
                        <Label className="text-xs text-slate-300 mb-1 block font-semibold">Texto Alternativo (Alt Text)</Label>
                        <Input
                          value={(selectedBlock.content as ImageBlockContent).alt || ""}
                          onChange={(e) => updateBlock(selectedBlock.id, { alt: e.target.value })}
                          placeholder="Descrição para leitores de tela"
                          className="bg-black/20 border-white/10 text-xs text-slate-100"
                        />
                      </div>

                      <div>
                        <Label className="text-xs text-slate-300 mb-1 block font-semibold">Link ao Clicar (opcional)</Label>
                        <Input
                          value={(selectedBlock.content as ImageBlockContent).linkUrl || ""}
                          onChange={(e) => updateBlock(selectedBlock.id, { linkUrl: e.target.value })}
                          placeholder="https://suaempresa.com"
                          className="bg-black/20 border-white/10 text-xs text-slate-100 font-mono text-[11px]"
                        />
                      </div>

                      <button
                        type="button"
                        onClick={() => updateBlock(selectedBlock.id, { shadow: !(selectedBlock.content as ImageBlockContent).shadow })}
                        className={`w-full flex items-center justify-center gap-1.5 py-2 rounded-xl text-xs font-semibold border transition-all ${
                          (selectedBlock.content as ImageBlockContent).shadow
                            ? "bg-blue-600 border-blue-500 text-white"
                            : "bg-black/20 border-white/10 text-slate-400 hover:text-slate-200"
                        }`}
                      >
                        Sombra Elevada
                      </button>
                    </div>
                  )}

                  {/* CONFIGURADOR DE TEXTO DYNAMIC */}
                  {selectedBlock.type === "text" && (
                    <div className="space-y-4">
                      <div>
                        <Label className="text-xs text-slate-300 mb-1 block font-semibold">Conteúdo do Texto</Label>
                        <textarea
                          rows={4}
                          value={(selectedBlock.content as TextBlockContent).content}
                          onChange={(e) => updateBlock(selectedBlock.id, { content: e.target.value })}
                          className="w-full bg-slate-950 border border-slate-800 rounded-xl p-3 text-xs text-slate-100 focus:border-blue-500 focus:outline-none leading-relaxed"
                        />
                      </div>

                      {/* Font Size Slider */}
                      <div className="bg-black/20 p-3 rounded-xl border border-white/10">
                        <div className="flex justify-between items-center mb-1.5">
                          <Label className="text-xs text-slate-300 font-semibold">Tamanho da Fonte</Label>
                          <span className="text-xs text-blue-400 font-bold font-mono bg-blue-500/10 px-2 py-0.5 rounded-md border border-blue-500/20">
                            {(selectedBlock.content as TextBlockContent).fontSize}px
                          </span>
                        </div>
                        <input
                          type="range"
                          min="12"
                          max="48"
                          value={(selectedBlock.content as TextBlockContent).fontSize}
                          onChange={(e) => updateBlock(selectedBlock.id, { fontSize: Number(e.target.value) })}
                          className="w-full accent-blue-500 bg-slate-900 h-2 rounded-lg cursor-pointer"
                        />
                      </div>

                      {/* Alignment */}
                      <div>
                        <Label className="text-xs text-slate-300 mb-1.5 block font-semibold">Alinhamento</Label>
                        <div className="flex bg-black/20 p-1 rounded-xl border border-white/10">
                          {(["left", "center", "right", "justify"] as const).map((align) => (
                            <button
                              key={align}
                              type="button"
                              onClick={() => updateBlock(selectedBlock.id, { align })}
                              className={`flex-1 py-1.5 text-xs font-semibold rounded-lg transition-all flex items-center justify-center ${
                                (selectedBlock.content as TextBlockContent).align === align
                                  ? "bg-blue-600 text-white shadow-md"
                                  : "text-slate-400 hover:text-slate-200"
                              }`}
                            >
                              {align === "left" && <AlignLeft className="w-3.5 h-3.5" />}
                              {align === "center" && <AlignCenter className="w-3.5 h-3.5" />}
                              {align === "right" && <AlignRight className="w-3.5 h-3.5" />}
                              {align === "justify" && <AlignJustify className="w-3.5 h-3.5" />}
                            </button>
                          ))}
                        </div>
                      </div>

                      {/* Color */}
                      <div>
                        <Label className="text-xs text-slate-300 mb-1 block font-semibold">Cor do Texto</Label>
                        <div className="flex items-center gap-2">
                          <input
                            type="color"
                            value={(selectedBlock.content as TextBlockContent).color}
                            onChange={(e) => updateBlock(selectedBlock.id, { color: e.target.value })}
                            className="w-9 h-9 rounded-lg border border-slate-700 bg-transparent cursor-pointer"
                          />
                          <Input
                            value={(selectedBlock.content as TextBlockContent).color}
                            onChange={(e) => updateBlock(selectedBlock.id, { color: e.target.value })}
                            className="bg-black/20 border-white/10 text-xs text-slate-100 uppercase font-mono font-semibold"
                          />
                        </div>
                      </div>

                      {/* Background Color (optional highlight box) */}
                      <div>
                        <div className="flex items-center justify-between mb-1">
                          <Label className="text-xs text-slate-300 font-semibold">Cor de Fundo (destaque)</Label>
                          {(selectedBlock.content as TextBlockContent).backgroundColor && (
                            <button
                              type="button"
                              onClick={() => updateBlock(selectedBlock.id, { backgroundColor: "" })}
                              className="text-[10px] text-slate-400 hover:text-red-400 font-semibold"
                            >
                              Remover
                            </button>
                          )}
                        </div>
                        <div className="flex items-center gap-2">
                          <input
                            type="color"
                            value={(selectedBlock.content as TextBlockContent).backgroundColor || "#ffffff"}
                            onChange={(e) => updateBlock(selectedBlock.id, { backgroundColor: e.target.value })}
                            className="w-9 h-9 rounded-lg border border-slate-700 bg-transparent cursor-pointer"
                          />
                          <Input
                            value={(selectedBlock.content as TextBlockContent).backgroundColor || ""}
                            onChange={(e) => updateBlock(selectedBlock.id, { backgroundColor: e.target.value })}
                            placeholder="Nenhuma (transparente)"
                            className="bg-black/20 border-white/10 text-xs text-slate-100 uppercase font-mono font-semibold"
                          />
                        </div>
                      </div>

                      {/* Letter Spacing */}
                      <div className="bg-black/20 p-3 rounded-xl border border-white/10">
                        <div className="flex justify-between items-center mb-1.5">
                          <Label className="text-xs text-slate-300 font-semibold">Espaçamento de Letras</Label>
                          <span className="text-xs text-blue-400 font-bold font-mono bg-blue-500/10 px-2 py-0.5 rounded-md border border-blue-500/20">
                            {(selectedBlock.content as TextBlockContent).letterSpacing || 0}px
                          </span>
                        </div>
                        <input
                          type="range"
                          min="0"
                          max="4"
                          step="0.5"
                          value={(selectedBlock.content as TextBlockContent).letterSpacing || 0}
                          onChange={(e) => updateBlock(selectedBlock.id, { letterSpacing: Number(e.target.value) })}
                          className="w-full accent-blue-500 bg-slate-900 h-2 rounded-lg cursor-pointer"
                        />
                      </div>
                    </div>
                  )}

                  {/* CONFIGURADOR DE DIVISOR DYNAMIC */}
                  {selectedBlock.type === "divider" && (
                    <div className="space-y-4">
                      <div>
                        <Label className="text-xs text-slate-300 mb-1 block font-semibold">Cor da Linha</Label>
                        <div className="flex items-center gap-2">
                          <input
                            type="color"
                            value={(selectedBlock.content as DividerBlockContent).color}
                            onChange={(e) => updateBlock(selectedBlock.id, { color: e.target.value })}
                            className="w-9 h-9 rounded-lg border border-slate-700 bg-transparent cursor-pointer"
                          />
                          <Input
                            value={(selectedBlock.content as DividerBlockContent).color}
                            onChange={(e) => updateBlock(selectedBlock.id, { color: e.target.value })}
                            className="bg-black/20 border-white/10 text-xs text-slate-100 uppercase font-mono font-semibold"
                          />
                        </div>
                      </div>

                      <div className="grid grid-cols-2 gap-3">
                        <div>
                          <Label className="text-xs text-slate-300 mb-1 block font-semibold">Espessura (px)</Label>
                          <Input
                            type="number"
                            value={(selectedBlock.content as DividerBlockContent).height}
                            onChange={(e) => updateBlock(selectedBlock.id, { height: Number(e.target.value) })}
                            className="bg-black/20 border-white/10 text-xs text-slate-100"
                          />
                        </div>
                        <div>
                          <Label className="text-xs text-slate-300 mb-1 block font-semibold">Estilo</Label>
                          <Select
                            value={(selectedBlock.content as DividerBlockContent).style}
                            onValueChange={(val) => updateBlock(selectedBlock.id, { style: val as "solid" | "dashed" | "dotted" })}
                          >
                            <SelectTrigger className="bg-black/20 border-white/10 text-xs">
                              <SelectValue placeholder="Selecione">
                                {(val) => {
                                  const labels: Record<string, string> = {
                                    solid: "Sólido",
                                    dashed: "Tracejado",
                                    dotted: "Pontilhado",
                                  };
                                  return labels[val as string] || val;
                                }}
                              </SelectValue>
                            </SelectTrigger>
                            <SelectContent className="bg-slate-900 border-slate-800 text-slate-200">
                              <SelectItem value="solid">Sólido</SelectItem>
                              <SelectItem value="dashed">Tracejado</SelectItem>
                              <SelectItem value="dotted">Pontilhado</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                      </div>

                      {/* Divider Width Slider */}
                      <div className="bg-black/20 p-3 rounded-xl border border-white/10">
                        <div className="flex justify-between items-center mb-1.5">
                          <Label className="text-xs text-slate-300 font-semibold">Largura da Linha</Label>
                          <span className="text-xs text-blue-400 font-bold font-mono bg-blue-500/10 px-2 py-0.5 rounded-md border border-blue-500/20">
                            {(selectedBlock.content as DividerBlockContent).widthPercent || 100}%
                          </span>
                        </div>
                        <input
                          type="range"
                          min="10"
                          max="100"
                          value={(selectedBlock.content as DividerBlockContent).widthPercent || 100}
                          onChange={(e) => updateBlock(selectedBlock.id, { widthPercent: Number(e.target.value) })}
                          className="w-full accent-blue-500 bg-slate-900 h-2 rounded-lg cursor-pointer"
                        />
                      </div>
                    </div>
                  )}

                  {/* CONFIGURADOR DE ESPAÇADOR DYNAMIC */}
                  {selectedBlock.type === "spacer" && (
                    <div className="space-y-4">
                      <div className="bg-black/20 p-3 rounded-xl border border-white/10">
                        <div className="flex justify-between items-center mb-1.5">
                          <Label className="text-xs text-slate-300 font-semibold">Altura do Espaço</Label>
                          <span className="text-xs text-blue-400 font-bold font-mono bg-blue-500/10 px-2 py-0.5 rounded-md border border-blue-500/20">
                            {(selectedBlock.content as SpacerBlockContent).height}px
                          </span>
                        </div>
                        <input
                          type="range"
                          min="4"
                          max="120"
                          value={(selectedBlock.content as SpacerBlockContent).height}
                          onChange={(e) => updateBlock(selectedBlock.id, { height: Number(e.target.value) })}
                          className="w-full accent-blue-500 bg-slate-900 h-2 rounded-lg cursor-pointer"
                        />
                      </div>
                    </div>
                  )}

                  {/* CONFIGURADOR DE REDES SOCIAIS DYNAMIC */}
                  {selectedBlock.type === "social" && (
                    <div className="space-y-4">
                      <div>
                        <Label className="text-xs text-slate-300 mb-1.5 block font-semibold">Ícones e Links</Label>
                        <div className="space-y-2">
                          {(selectedBlock.content as SocialBlockContent).links.map((link, i) => (
                            <div key={i} className="flex items-center gap-2">
                              <Select
                                value={link.platform}
                                onValueChange={(val) => {
                                  const links = [...(selectedBlock.content as SocialBlockContent).links];
                                  links[i] = { ...links[i], platform: val as SocialPlatform };
                                  updateBlock(selectedBlock.id, { links });
                                }}
                              >
                                <SelectTrigger className="bg-black/20 border-white/10 text-xs w-28 shrink-0">
                                  <SelectValue placeholder="Plataforma">
                                    {(val) => val ? String(val).charAt(0).toUpperCase() + String(val).slice(1) : val}
                                  </SelectValue>
                                </SelectTrigger>
                                <SelectContent className="bg-slate-900 border-white/10 text-slate-200">
                                  {(Object.keys(SOCIAL_PLATFORM_META) as SocialPlatform[]).map((p) => (
                                    <SelectItem key={p} value={p} className="text-xs capitalize focus:bg-slate-800">
                                      {p}
                                    </SelectItem>
                                  ))}
                                </SelectContent>
                              </Select>
                              <Input
                                value={link.url}
                                onChange={(e) => {
                                  const links = [...(selectedBlock.content as SocialBlockContent).links];
                                  links[i] = { ...links[i], url: e.target.value };
                                  updateBlock(selectedBlock.id, { links });
                                }}
                                placeholder="https://..."
                                className="bg-black/20 border-white/10 text-xs text-slate-100 font-mono text-[11px]"
                              />
                              <button
                                type="button"
                                onClick={() => {
                                  const links = (selectedBlock.content as SocialBlockContent).links.filter((_, idx) => idx !== i);
                                  updateBlock(selectedBlock.id, { links });
                                }}
                                className="shrink-0 p-1.5 rounded-lg text-red-400 hover:bg-red-900/40 transition-colors"
                              >
                                <XIcon className="w-3.5 h-3.5" />
                              </button>
                            </div>
                          ))}
                        </div>
                        <button
                          type="button"
                          onClick={() => {
                            const links = [
                              ...(selectedBlock.content as SocialBlockContent).links,
                              { platform: "facebook" as SocialPlatform, url: "https://" },
                            ];
                            updateBlock(selectedBlock.id, { links });
                          }}
                          className="mt-2 w-full flex items-center justify-center gap-1.5 py-2 rounded-xl text-xs font-semibold border border-dashed border-white/15 text-slate-400 hover:text-slate-200 hover:border-blue-500/50 transition-all"
                        >
                          <Plus className="w-3.5 h-3.5" />
                          Adicionar Rede Social
                        </button>
                      </div>

                      {/* Icon Shape Toggle */}
                      <div>
                        <Label className="text-xs text-slate-300 mb-1.5 block font-semibold">Formato do Ícone</Label>
                        <div className="flex bg-black/20 p-1 rounded-xl border border-white/10">
                          {(["circle", "square"] as const).map((shape) => (
                            <button
                              key={shape}
                              type="button"
                              onClick={() => updateBlock(selectedBlock.id, { iconShape: shape })}
                              className={`flex-1 py-1.5 text-xs font-semibold rounded-lg transition-all flex items-center justify-center gap-1.5 ${
                                (selectedBlock.content as SocialBlockContent).iconShape === shape
                                  ? "bg-blue-600 text-white shadow-md"
                                  : "text-slate-400 hover:text-slate-200"
                              }`}
                            >
                              {shape === "circle" ? <Circle className="w-3.5 h-3.5" /> : <Square className="w-3.5 h-3.5" />}
                            </button>
                          ))}
                        </div>
                      </div>

                      {/* Icon Size Slider */}
                      <div className="bg-black/20 p-3 rounded-xl border border-white/10">
                        <div className="flex justify-between items-center mb-1.5">
                          <Label className="text-xs text-slate-300 font-semibold">Tamanho do Ícone</Label>
                          <span className="text-xs text-blue-400 font-bold font-mono bg-blue-500/10 px-2 py-0.5 rounded-md border border-blue-500/20">
                            {(selectedBlock.content as SocialBlockContent).iconSize}px
                          </span>
                        </div>
                        <input
                          type="range"
                          min="24"
                          max="56"
                          value={(selectedBlock.content as SocialBlockContent).iconSize}
                          onChange={(e) => updateBlock(selectedBlock.id, { iconSize: Number(e.target.value) })}
                          className="w-full accent-blue-500 bg-slate-900 h-2 rounded-lg cursor-pointer"
                        />
                      </div>

                      {/* Alignment */}
                      <div>
                        <Label className="text-xs text-slate-300 mb-1.5 block font-semibold">Alinhamento</Label>
                        <div className="flex bg-black/20 p-1 rounded-xl border border-white/10">
                          {(["left", "center", "right"] as const).map((align) => (
                            <button
                              key={align}
                              type="button"
                              onClick={() => updateBlock(selectedBlock.id, { align })}
                              className={`flex-1 py-1.5 text-xs font-semibold rounded-lg transition-all flex items-center justify-center ${
                                (selectedBlock.content as SocialBlockContent).align === align
                                  ? "bg-blue-600 text-white shadow-md"
                                  : "text-slate-400 hover:text-slate-200"
                              }`}
                            >
                              {align === "left" && <AlignLeft className="w-3.5 h-3.5" />}
                              {align === "center" && <AlignCenter className="w-3.5 h-3.5" />}
                              {align === "right" && <AlignRight className="w-3.5 h-3.5" />}
                            </button>
                          ))}
                        </div>
                      </div>
                    </div>
                  )}

                  {/* CONFIGURADOR DE VÍDEO DYNAMIC */}
                  {selectedBlock.type === "video" && (
                    <div className="space-y-4">
                      <div>
                        <Label className="text-xs text-slate-300 mb-1 block font-semibold">URL da Thumbnail</Label>
                        <Input
                          value={(selectedBlock.content as VideoBlockContent).thumbnailSrc}
                          onChange={(e) => updateBlock(selectedBlock.id, { thumbnailSrc: e.target.value })}
                          className="bg-black/20 border-white/10 text-xs text-slate-100 font-mono text-[11px]"
                        />
                      </div>

                      <div>
                        <Label className="text-xs text-slate-300 mb-1 block font-semibold">Link do Vídeo (YouTube, Vimeo...)</Label>
                        <Input
                          value={(selectedBlock.content as VideoBlockContent).videoUrl}
                          onChange={(e) => updateBlock(selectedBlock.id, { videoUrl: e.target.value })}
                          placeholder="https://youtube.com/watch?v=..."
                          className="bg-black/20 border-white/10 text-xs text-slate-100 font-mono text-[11px]"
                        />
                      </div>

                      <div>
                        <Label className="text-xs text-slate-300 mb-1 block font-semibold">Texto Alternativo (Alt Text)</Label>
                        <Input
                          value={(selectedBlock.content as VideoBlockContent).alt || ""}
                          onChange={(e) => updateBlock(selectedBlock.id, { alt: e.target.value })}
                          className="bg-black/20 border-white/10 text-xs text-slate-100"
                        />
                      </div>

                      {/* Border Radius Slider */}
                      <div className="bg-black/20 p-3 rounded-xl border border-white/10">
                        <div className="flex justify-between items-center mb-1.5">
                          <Label className="text-xs text-slate-300 font-semibold">Arredondamento das Bordas</Label>
                          <span className="text-xs text-blue-400 font-bold font-mono bg-blue-500/10 px-2 py-0.5 rounded-md border border-blue-500/20">
                            {(selectedBlock.content as VideoBlockContent).borderRadius}px
                          </span>
                        </div>
                        <input
                          type="range"
                          min="0"
                          max="40"
                          value={(selectedBlock.content as VideoBlockContent).borderRadius}
                          onChange={(e) => updateBlock(selectedBlock.id, { borderRadius: Number(e.target.value) })}
                          className="w-full accent-blue-500 bg-slate-900 h-2 rounded-lg cursor-pointer"
                        />
                      </div>

                      {/* Alignment */}
                      <div>
                        <Label className="text-xs text-slate-300 mb-1.5 block font-semibold">Alinhamento</Label>
                        <div className="flex bg-black/20 p-1 rounded-xl border border-white/10">
                          {(["left", "center", "right"] as const).map((align) => (
                            <button
                              key={align}
                              type="button"
                              onClick={() => updateBlock(selectedBlock.id, { align })}
                              className={`flex-1 py-1.5 text-xs font-semibold rounded-lg transition-all flex items-center justify-center ${
                                (selectedBlock.content as VideoBlockContent).align === align
                                  ? "bg-blue-600 text-white shadow-md"
                                  : "text-slate-400 hover:text-slate-200"
                              }`}
                            >
                              {align === "left" && <AlignLeft className="w-3.5 h-3.5" />}
                              {align === "center" && <AlignCenter className="w-3.5 h-3.5" />}
                              {align === "right" && <AlignRight className="w-3.5 h-3.5" />}
                            </button>
                          ))}
                        </div>
                      </div>
                    </div>
                  )}

                  {/* CONFIGURADOR DE HTML PERSONALIZADO DYNAMIC */}
                  {selectedBlock.type === "html-snippet" && (
                    <div className="space-y-4">
                      <div>
                        <Label className="text-xs text-slate-300 mb-1 block font-semibold">Trecho de Código HTML</Label>
                        <textarea
                          rows={8}
                          value={(selectedBlock.content as HtmlSnippetBlockContent).html}
                          onChange={(e) => updateBlock(selectedBlock.id, { html: e.target.value })}
                          className="w-full bg-black/20 border border-white/10 rounded-xl p-3 text-[11px] font-mono text-emerald-400 focus:border-blue-500 focus:outline-none leading-relaxed"
                        />
                      </div>
                      <p className="text-[10px] text-amber-400 font-semibold flex items-center gap-1.5">
                        <Braces className="w-3 h-3" />
                        Este trecho é inserido exatamente como escrito — use com cuidado.
                      </p>
                    </div>
                  )}
                </div>
              )}
            </TabsContent>

            {/* TAB 3: CÓDIGO HTML BRUTO (SINCRONIZAÇÃO EM TEMPO REAL COM A ARTE) */}
            <TabsContent value="html" className="flex-1 p-4 flex flex-col">
              <div className="flex items-center justify-between mb-2">
                <Label className="text-xs text-slate-300 font-semibold">Cole ou Edite seu Código HTML</Label>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => {
                    navigator.clipboard.writeText(htmlBody);
                    toast.success("Código HTML copiado!");
                  }}
                  className="h-7 text-[11px] text-blue-400 hover:text-blue-300 font-semibold"
                >
                  <Copy className="w-3 h-3 mr-1" />
                  Copiar
                </Button>
              </div>

              <textarea
                value={rawHtmlCode}
                onChange={(e) => {
                  const newHtml = e.target.value;
                  setRawHtmlCode(newHtml);
                  setHtmlBody(newHtml);
                  setEditorMode("custom-html"); // Ativa a renderização em tempo real da arte colada!
                }}
                placeholder="Cole o código HTML do seu e-mail aqui..."
                className="flex-1 w-full bg-slate-950 border border-slate-800 rounded-xl p-3 font-mono text-[11px] leading-relaxed text-emerald-400 focus:outline-none focus:border-blue-500 resize-none min-h-[350px]"
              />
              <p className="text-[10px] text-blue-400 mt-2 font-semibold flex items-center gap-1">
                <Sparkles className="w-3 h-3 text-blue-400" />
                Ao colar seu HTML aqui, a arte completa é atualizada instantaneamente no canvas visual!
              </p>
            </TabsContent>
          </Tabs>
        </aside>
      </div>

      {/* ------------------------------------------------------------- */}
      {/* SHADCN DIALOG MODAL FOR PHOTO UPLOADS & URL INTEGRATION        */}
      {/* ------------------------------------------------------------- */}
      <Dialog open={isImageModalOpen} onOpenChange={closeImageModal}>
        <DialogContent className="bg-slate-900 border-white/10 text-slate-100 w-[calc(100%-2rem)] sm:w-full max-w-md rounded-2xl">
          <DialogHeader>
            <DialogTitle className="text-base font-bold text-slate-100 flex items-center gap-2">
              <Upload className="w-5 h-5 text-emerald-400" />
              Upload & Inserção de Fotos
            </DialogTitle>
            <DialogDescription className="text-xs text-slate-400">
              Carregue uma imagem do seu computador ou insira uma URL pública direta.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-2">
            <Tabs value={imageModalTab} onValueChange={(val) => setImageModalTab(val as "file" | "url")}>
              <TabsList className="inline-flex justify-start w-fit max-w-full bg-black/20 p-1 rounded-xl border border-white/10 gap-1">
                <TabsTrigger
                  value="file"
                  className="text-xs font-semibold py-1.5 px-3 data-[state=active]:bg-blue-600 data-[state=active]:text-white transition-colors rounded-lg"
                >
                  Upload de Arquivo
                </TabsTrigger>
                <TabsTrigger
                  value="url"
                  className="text-xs font-semibold py-1.5 px-3 data-[state=active]:bg-blue-600 data-[state=active]:text-white transition-colors rounded-lg"
                >
                  URL Direta
                </TabsTrigger>
              </TabsList>

              <TabsContent value="file" className="mt-4 focus-visible:outline-none">
                <div className="border-2 border-dashed border-slate-800 hover:border-blue-500/60 rounded-2xl p-6 flex flex-col items-center justify-center bg-slate-950/50 transition-colors">
                  <ImageIcon className="w-10 h-10 text-slate-500 mb-2" />
                  <p className="text-xs font-semibold text-slate-300 mb-1">Selecione ou solte a imagem aqui</p>
                  <p className="text-[10px] text-slate-500 mb-4">PNG, JPG, GIF ou WEBP (Max 5MB)</p>
                  <Input
                    type="file"
                    accept="image/*"
                    onChange={handleFileUpload}
                    className="hidden"
                    id="image-file-input"
                  />
                  <Label
                    htmlFor="image-file-input"
                    className="bg-blue-600 hover:bg-blue-500 text-white text-xs font-semibold px-4 py-2 rounded-xl cursor-pointer transition-colors inline-flex items-center gap-1.5 shadow-md shadow-blue-600/20"
                  >
                    <Upload className="w-3.5 h-3.5" />
                    Procurar Arquivo
                  </Label>
                </div>
              </TabsContent>

              <TabsContent value="url" className="mt-4 focus-visible:outline-none">
                <div>
                  <Label className="text-xs text-slate-300 mb-1 block font-semibold">URL da Imagem</Label>
                  <Input
                    value={modalImageSrc}
                    onChange={(e) => setModalImageSrc(e.target.value)}
                    placeholder="https://suaempresa.com/imagens/banner.png"
                    className="bg-black/20 border-white/10 text-xs text-slate-100 font-mono text-[11px]"
                  />
                </div>
              </TabsContent>
            </Tabs>

            {/* Live Image Preview inside Modal */}
            {modalImageSrc && (
              <div className="p-3 bg-slate-950 rounded-xl border border-slate-800 flex flex-col items-center">
                <span className="text-[10px] text-slate-400 mb-2 self-start font-semibold">Pré-visualização:</span>
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={modalImageSrc} alt="Preview" className="max-h-36 rounded-lg object-contain border border-slate-800" />
              </div>
            )}

            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label className="text-xs text-slate-300 mb-1 block font-semibold">Largura (Width)</Label>
                <Input
                  value={modalImageWidth}
                  onChange={(e) => setModalImageWidth(e.target.value)}
                  placeholder="100%"
                  className="bg-black/20 border-white/10 text-xs text-slate-100"
                />
              </div>
              <div>
                <Label className="text-xs text-slate-300 mb-1 block font-semibold">Altura (Height)</Label>
                <Input
                  value={modalImageHeight}
                  onChange={(e) => setModalImageHeight(e.target.value)}
                  placeholder="auto"
                  className="bg-black/20 border-white/10 text-xs text-slate-100"
                />
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" size="sm" onClick={closeImageModal} className="border-slate-800 text-slate-300 hover:bg-slate-800 font-medium">
              Cancelar
            </Button>
            <Button size="sm" onClick={handleApplyImageModal} className="bg-blue-600 hover:bg-blue-500 text-white font-semibold shadow-md shadow-blue-600/20">
              Aplicar Imagem
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* ------------------------------------------------------------- */}
      {/* SHADCN DIALOG MODAL FOR PREVIEW OF SAVED NEWSLETTER          */}
      {/* ------------------------------------------------------------- */}
      <Dialog open={isPreviewSavedModalOpen} onOpenChange={setIsPreviewSavedModalOpen}>
        <DialogContent className="bg-slate-900 border-white/10 text-slate-100 w-[calc(100%-2rem)] sm:w-full max-w-3xl max-h-[90vh] flex flex-col p-4 sm:p-6 rounded-2xl">
          <DialogHeader>
            <DialogTitle className="text-lg font-bold text-slate-100 flex items-center justify-between">
              <span className="flex items-center gap-2 text-emerald-400">
                <CheckCircle2 className="w-5 h-5 text-emerald-400" />
                Campanha Salva com Sucesso!
              </span>
              <Badge className="bg-emerald-500/10 text-emerald-400 border-emerald-500/30 text-xs font-semibold">
                Status: Rascunho / Pronto
              </Badge>
            </DialogTitle>
            <DialogDescription className="text-xs text-slate-400">
              Confira a pré-visualização completa da sua newsletter salva no banco de dados.
            </DialogDescription>
          </DialogHeader>

          {savedCampaignData && (
            <div className="flex-1 flex flex-col overflow-hidden space-y-4 my-2">
              {/* Info Header */}
              <div className="bg-slate-950 p-3.5 rounded-xl border border-slate-800 text-xs grid grid-cols-1 sm:grid-cols-3 gap-3 text-slate-300">
                <div>
                  <span className="text-[10px] text-slate-500 uppercase block font-semibold">Título</span>
                  <span className="font-bold text-slate-100 truncate block">{savedCampaignData.title}</span>
                </div>
                <div>
                  <span className="text-[10px] text-slate-500 uppercase block font-semibold">Assunto</span>
                  <span className="font-medium text-slate-200 truncate block">{savedCampaignData.subject}</span>
                </div>
                <div>
                  <span className="text-[10px] text-slate-500 uppercase block font-semibold">Remetente</span>
                  <span className="font-medium text-blue-400 truncate block">{savedCampaignData.senderName}</span>
                </div>
              </div>

              {/* Newsletter Preview Frame */}
              <div className="flex-1 bg-slate-950 p-3 rounded-2xl border border-slate-800 flex flex-col items-center overflow-y-auto">
                <div className="w-full max-w-[580px] bg-white rounded-xl shadow-2xl overflow-hidden border border-slate-200 p-4">
                  <iframe
                    srcDoc={
                      savedCampaignData.htmlBody.includes("<head>")
                        ? savedCampaignData.htmlBody.replace("<head>", '<head><base target="_blank">')
                        : `<base target="_blank">${savedCampaignData.htmlBody}`
                    }
                    title="Pré-visualização da Newsletter Salva"
                    className="w-full min-h-[380px] border-0 bg-white"
                    sandbox="allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"
                  />
                </div>
              </div>
            </div>
          )}

          <DialogFooter className="flex-col sm:flex-row gap-2 pt-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setIsPreviewSavedModalOpen(false)}
              className="border-slate-800 text-slate-300 hover:bg-slate-800 text-xs font-semibold"
            >
              Continuar Editando
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => router.push("/")}
              className="border-slate-800 bg-slate-950 text-slate-200 hover:bg-slate-800 text-xs font-semibold"
            >
              <List className="w-3.5 h-3.5 mr-1.5 text-blue-400" />
              Lista de Campanhas
            </Button>
            {savedCampaignData && (
              <Button
                size="sm"
                onClick={() => router.push(`/campaigns/${savedCampaignData.id}`)}
                className="bg-blue-600 hover:bg-blue-500 text-white text-xs font-semibold shadow-md shadow-blue-600/20"
              >
                Ver Detalhes & Enviar
                <ArrowRight className="w-3.5 h-3.5 ml-1.5" />
              </Button>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* ------------------------------------------------------------- */}
      {/* SHADCN DIALOG MODAL FOR TEST SEND                              */}
      {/* ------------------------------------------------------------- */}
      <Dialog open={isTestSendModalOpen} onOpenChange={setIsTestSendModalOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Send className="w-5 h-5 text-[#4338CA]" />
              Enviar E-mail de Teste
            </DialogTitle>
            <DialogDescription>
              Envie uma cópia real desta newsletter para qualquer endereço — útil para revisar o
              layout em diferentes clientes de e-mail antes do disparo para sua lista.
            </DialogDescription>
          </DialogHeader>

          <div className="field-container py-2">
            <Label htmlFor="test-email-input">Enviar para</Label>
            <Input
              id="test-email-input"
              type="email"
              value={testSendEmail}
              onChange={(e) => setTestSendEmail(e.target.value)}
              placeholder="seuemail@exemplo.com"
            />
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsTestSendModalOpen(false)}
            >
              Cancelar
            </Button>
            <Button
              disabled={isSendingTest}
              onClick={handleConfirmSendTest}
            >
              {isSendingTest ? (
                <>
                  <Loader2 className="w-3.5 h-3.5 mr-1.5 animate-spin" />
                  Enviando...
                </>
              ) : (
                <>
                  <Send className="w-3.5 h-3.5 mr-1.5" />
                  Enviar Teste
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
