"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  ArrowLeft,
  ArrowRight,
  Bell,
  BadgePercent,
  CalendarClock,
  Check,
  ChevronDown,
  Info,
  Megaphone,
  Save,
  ShieldCheck,
  SmilePlus,
  Sparkles,
  TriangleAlert,
  type LucideIcon,
} from "lucide-react";

type ThemeConfig = {
  background?: string;
  text?: string;
  accent?: string;
  inline_icon?: string;
  watermark_icon?: string;
  cta_label?: string;
  cta_url?: string;
  cta_new_tab?: boolean;
};

type SystemNotice = {
  id: string;
  scope: string;
  title: string | null;
  message: string;
  variant: string;
  dismiss_mode: string;
  active: boolean;
  position: number;
  start_at: string | null;
  end_at: string | null;
  show_on_paths: string[] | null;
  hide_on_paths: string[] | null;
  theme: ThemeConfig;
  created_at?: string | null;
  updated_at?: string | null;
};

const ICON_OPTIONS: Array<{ value: string; label: string; icon: LucideIcon }> = [
  { value: "none", label: "Sem ícone", icon: Info },
  { value: "megaphone", label: "Megafone", icon: Megaphone },
  { value: "bell", label: "Sino", icon: Bell },
  { value: "sparkles", label: "Destaque", icon: Sparkles },
  { value: "shield-check", label: "Segurança", icon: ShieldCheck },
  { value: "badge-percent", label: "Oferta", icon: BadgePercent },
  { value: "calendar-clock", label: "Agenda", icon: CalendarClock },
  { value: "triangle-alert", label: "Alerta", icon: TriangleAlert },
  { value: "info", label: "Informação", icon: Info },
];

function getIconComponent(name: string | null | undefined) {
  const found = ICON_OPTIONS.find((item) => item.value === String(name || "").trim());
  return found?.icon || null;
}

const EMOJI_OPTIONS = ["😀", "😍", "🔥", "🚀", "🎉", "📢", "⚠️", "✅", "💥", "💡", "🛠️", "⏰", "💸", "📦", "❤️", "👉"];

function formatDate(value: string | null | undefined) {
  if (!value) return "";
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return "";
  return d.toISOString().slice(0, 10);
}

function splitPrefixes(text: string) {
  const raw = String(text || "")
    .split(",")
    .map((v) => v.trim())
    .filter(Boolean)
    .map((v) => (v.startsWith("/") ? v : `/${v.replace(/^\/+/, "")}`));
  return raw.length ? raw : null;
}

function variantDefaults(variant: string) {
  if (variant === "success") return { background: "#ECFDF5", text: "#065F46", accent: "#10B981" };
  if (variant === "warning") return { background: "#FFFBEB", text: "#92400E", accent: "#F59E0B" };
  if (variant === "danger") return { background: "#FFF1F2", text: "#9F1239", accent: "#F43F5E" };
  return { background: "#EFF6FF", text: "#1D4ED8", accent: "#3B82F6" };
}

export default function SystemNoticeFormClient({
  mode,
  initial,
}: {
  mode: "create" | "edit";
  initial: SystemNotice | null;
}) {
  const router = useRouter();
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const titleRef = useRef<HTMLInputElement | null>(null);
  const textareaRef = useRef<HTMLTextAreaElement | null>(null);
  const [emojiTarget, setEmojiTarget] = useState<"title" | "message" | null>(null);
  const [watermarkOpen, setWatermarkOpen] = useState(false);

  const base = useMemo<Partial<SystemNotice>>(() => {
    if (initial) {
      return {
        ...initial,
        theme: initial.theme || {},
        show_on_paths: initial.show_on_paths || null,
        hide_on_paths: initial.hide_on_paths || null,
      };
    }

    return {
      scope: "owner",
      title: "",
      message: "",
      variant: "info",
      dismiss_mode: "dismissible",
      active: true,
      position: 0,
      start_at: null,
      end_at: null,
      show_on_paths: null,
      hide_on_paths: null,
      theme: {},
    };
  }, [initial]);

  const [draft, setDraft] = useState<Partial<SystemNotice>>(base);
  const [showOnPathsText, setShowOnPathsText] = useState("");
  const [hideOnPathsText, setHideOnPathsText] = useState("");

  useEffect(() => {
    setDraft(base);
    setShowOnPathsText((base.show_on_paths || []).join(", "));
    setHideOnPathsText((base.hide_on_paths || []).join(", "));
    setMessage(null);
  }, [base]);

  const canSave = Boolean(String(draft.message || "").trim()) && Boolean(String(draft.scope || "").trim());

  const computedTheme = useMemo(() => {
    const defaults = variantDefaults(String(draft.variant || "info"));
    const custom = (draft.theme || {}) as ThemeConfig;
    return {
      background: custom.background || defaults.background,
      text: custom.text || defaults.text,
      accent: custom.accent || defaults.accent,
      watermark_icon: custom.watermark_icon || "",
      cta_label: custom.cta_label || "",
      cta_url: custom.cta_url || "",
      cta_new_tab: Boolean(custom.cta_new_tab),
    };
  }, [draft.theme, draft.variant]);

  const WatermarkIcon = getIconComponent(computedTheme.watermark_icon);
  const selectedWatermark =
    ICON_OPTIONS.find((option) => option.value === String((draft.theme as ThemeConfig | undefined)?.watermark_icon || "none")) || ICON_OPTIONS[0];
  const SelectedWatermarkIcon = selectedWatermark.icon;

  function insertEmoji(target: "title" | "message", emoji: string) {
    const input = target === "title" ? titleRef.current : textareaRef.current;
    const currentValue = String(target === "title" ? draft.title || "" : draft.message || "");
    if (!input) {
      if (target === "title") setDraft((prev) => ({ ...prev, title: `${currentValue}${emoji}` }));
      else setDraft((prev) => ({ ...prev, message: `${currentValue}${emoji}` }));
      return;
    }

    const start = input.selectionStart ?? currentValue.length;
    const end = input.selectionEnd ?? currentValue.length;
    const nextValue = `${currentValue.slice(0, start)}${emoji}${currentValue.slice(end)}`;

    if (target === "title") setDraft((prev) => ({ ...prev, title: nextValue }));
    else setDraft((prev) => ({ ...prev, message: nextValue }));

    requestAnimationFrame(() => {
      input.focus();
      const nextCursor = start + emoji.length;
      input.setSelectionRange(nextCursor, nextCursor);
    });
  }

  return (
    <div className="min-h-screen bg-slate-50/50 p-6 sm:p-8 font-sans">
      <div className="mx-auto flex max-w-[1600px] flex-col gap-6">
        <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
          <div className="space-y-1">
            <div className="flex items-center gap-3">
              <Link
                href="/tarjas-informativas"
                className="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-white shadow-sm ring-1 ring-slate-200 transition hover:bg-slate-50 active:scale-95"
                aria-label="Voltar"
                title="Voltar"
              >
                <ArrowLeft className="h-4.5 w-4.5 text-slate-700" />
              </Link>
              <div>
                <h1 className="text-2xl font-bold tracking-tight text-slate-900">
                  {mode === "create" ? "Nova tarja informativa" : "Editar tarja informativa"}
                </h1>
                <p className="text-slate-500">A tarja aparece quando o usuário abre o sistema, de acordo com as regras configuradas.</p>
              </div>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <Link
              href="/tarjas-informativas"
              className="inline-flex h-11 items-center justify-center rounded-xl bg-white px-4 text-sm font-semibold text-slate-700 shadow-sm ring-1 ring-slate-200 transition hover:bg-slate-50 disabled:opacity-60"
            >
              Cancelar
            </Link>
            <button
              type="button"
              disabled={!canSave || saving}
              onClick={async () => {
                if (!canSave) return;
                setSaving(true);
                setMessage(null);
                try {
                  const method = mode === "edit" ? "PATCH" : "POST";
                  const res = await fetch("/api/system-notices", {
                    method,
                    headers: { "content-type": "application/json" },
                    body: JSON.stringify({
                      id: initial?.id,
                      scope: String(draft.scope || "owner"),
                      title: String(draft.title || "").trim() || null,
                      message: String(draft.message || "").trim(),
                      variant: String(draft.variant || "info"),
                      dismiss_mode: String(draft.dismiss_mode || "dismissible"),
                      active: Boolean(draft.active),
                      position: Number(draft.position || 0),
                      start_at: draft.start_at || null,
                      end_at: draft.end_at || null,
                      show_on_paths: splitPrefixes(showOnPathsText),
                      hide_on_paths: splitPrefixes(hideOnPathsText),
                      theme: {
                        background: String((draft.theme as ThemeConfig | undefined)?.background || "").trim() || undefined,
                        text: String((draft.theme as ThemeConfig | undefined)?.text || "").trim() || undefined,
                        accent: String((draft.theme as ThemeConfig | undefined)?.accent || "").trim() || undefined,
                        watermark_icon: String((draft.theme as ThemeConfig | undefined)?.watermark_icon || "").trim() || undefined,
                        cta_label: String((draft.theme as ThemeConfig | undefined)?.cta_label || "").trim() || undefined,
                        cta_url: String((draft.theme as ThemeConfig | undefined)?.cta_url || "").trim() || undefined,
                        cta_new_tab: Boolean((draft.theme as ThemeConfig | undefined)?.cta_new_tab),
                      },
                    }),
                  });
                  const json = (await res.json().catch(() => null)) as { error?: string } | null;
                  if (!res.ok) {
                    setMessage({ type: "error", text: json?.error || "Não foi possível salvar." });
                    return;
                  }
                  setMessage({ type: "success", text: "Tarja salva com sucesso." });
                  window.setTimeout(() => router.push("/tarjas-informativas"), 220);
                } finally {
                  setSaving(false);
                }
              }}
              className="inline-flex h-11 items-center justify-center gap-2 rounded-xl bg-slate-900 px-5 text-sm font-semibold text-white shadow-sm transition hover:bg-slate-800 disabled:opacity-60"
            >
              <Save className="h-4.5 w-4.5" />
              {saving ? "Salvando..." : "Salvar"}
            </button>
          </div>
        </div>

        <div className="grid gap-6 lg:grid-cols-[1.05fr_0.95fr]">
          <div className="space-y-4">
            <div className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
              <div className="grid gap-4">
                <label className="space-y-2">
                  <div className="flex items-center justify-between gap-3">
                    <div className="text-sm font-semibold text-slate-900">Título (opcional)</div>
                    <div className="relative">
                      <button
                        type="button"
                        onClick={() => setEmojiTarget((prev) => (prev === "title" ? null : "title"))}
                        className="inline-flex h-9 items-center gap-2 rounded-xl border border-slate-200 bg-white px-3 text-xs font-semibold text-slate-700 transition hover:bg-slate-50"
                      >
                        <SmilePlus className="h-4 w-4" />
                        Emojis
                      </button>
                      {emojiTarget === "title" ? (
                        <div className="absolute right-0 top-11 z-20 w-[248px] rounded-2xl border border-slate-200 bg-white p-3 shadow-xl">
                          <div className="mb-2 text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Inserir emoji</div>
                          <div className="grid grid-cols-8 gap-2">
                            {EMOJI_OPTIONS.map((emoji) => (
                              <button
                                key={`title-${emoji}`}
                                type="button"
                                onClick={() => insertEmoji("title", emoji)}
                                className="inline-flex h-9 w-9 items-center justify-center rounded-xl bg-slate-50 text-lg transition hover:bg-slate-100"
                              >
                                {emoji}
                              </button>
                            ))}
                          </div>
                        </div>
                      ) : null}
                    </div>
                  </div>
                  <input
                    ref={titleRef}
                    value={String(draft.title || "")}
                    onChange={(e) => setDraft((prev) => ({ ...prev, title: e.target.value }))}
                    onFocus={() => setEmojiTarget((prev) => (prev === "message" ? null : prev))}
                    placeholder="Ex: Manutenção programada"
                    className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-800 outline-none placeholder:text-slate-400"
                  />
                </label>

                <label className="space-y-2">
                  <div className="flex items-center justify-between gap-3">
                    <div className="text-sm font-semibold text-slate-900">Mensagem</div>
                    <div className="relative">
                      <button
                        type="button"
                        onClick={() => setEmojiTarget((prev) => (prev === "message" ? null : "message"))}
                        className="inline-flex h-9 items-center gap-2 rounded-xl border border-slate-200 bg-white px-3 text-xs font-semibold text-slate-700 transition hover:bg-slate-50"
                      >
                        <SmilePlus className="h-4 w-4" />
                        Emojis
                      </button>
                      {emojiTarget === "message" ? (
                        <div className="absolute right-0 top-11 z-20 w-[248px] rounded-2xl border border-slate-200 bg-white p-3 shadow-xl">
                          <div className="mb-2 text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Inserir emoji</div>
                          <div className="grid grid-cols-8 gap-2">
                            {EMOJI_OPTIONS.map((emoji) => (
                              <button
                                key={`message-${emoji}`}
                                type="button"
                                onClick={() => insertEmoji("message", emoji)}
                                className="inline-flex h-9 w-9 items-center justify-center rounded-xl bg-slate-50 text-lg transition hover:bg-slate-100"
                              >
                                {emoji}
                              </button>
                            ))}
                          </div>
                        </div>
                      ) : null}
                    </div>
                  </div>
                  <textarea
                    ref={textareaRef}
                    value={String(draft.message || "")}
                    onChange={(e) => setDraft((prev) => ({ ...prev, message: e.target.value }))}
                    onFocus={() => setEmojiTarget((prev) => (prev === "title" ? null : prev))}
                    placeholder="Escreva o texto principal da tarja..."
                    rows={5}
                    className="w-full resize-none rounded-xl border border-slate-200 bg-white px-3 py-3 text-sm text-slate-800 outline-none placeholder:text-slate-400"
                  />
                </label>

                <div className="grid gap-4 md:grid-cols-2">
                  <label className="space-y-2">
                    <div className="text-sm font-semibold text-slate-900">Escopo</div>
                    <select
                      value={String(draft.scope || "owner")}
                      onChange={(e) => setDraft((prev) => ({ ...prev, scope: e.target.value }))}
                      className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 outline-none"
                    >
                      <option value="all">Todos os apps</option>
                      <option value="admin">Admin</option>
                      <option value="owner">Owner</option>
                      <option value="public">Catálogo público</option>
                    </select>
                  </label>

                  <label className="space-y-2">
                    <div className="text-sm font-semibold text-slate-900">Nível</div>
                    <select
                      value={String(draft.variant || "info")}
                      onChange={(e) => setDraft((prev) => ({ ...prev, variant: e.target.value }))}
                      className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 outline-none"
                    >
                      <option value="info">Info</option>
                      <option value="success">Sucesso</option>
                      <option value="warning">Atenção</option>
                      <option value="danger">Urgente</option>
                    </select>
                  </label>

                  <label className="space-y-2">
                    <div className="text-sm font-semibold text-slate-900">Comportamento</div>
                    <select
                      value={String(draft.dismiss_mode || "dismissible")}
                      onChange={(e) => setDraft((prev) => ({ ...prev, dismiss_mode: e.target.value }))}
                      className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 outline-none"
                    >
                      <option value="dismissible">Fechável</option>
                      <option value="session">Fechar (sessão)</option>
                      <option value="sticky">Sem fechar</option>
                    </select>
                  </label>

                  <label className="space-y-2">
                    <div className="text-sm font-semibold text-slate-900">Status</div>
                    <select
                      value={draft.active ? "ativo" : "inativo"}
                      onChange={(e) => setDraft((prev) => ({ ...prev, active: e.target.value === "ativo" }))}
                      className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 outline-none"
                    >
                      <option value="ativo">Ativa</option>
                      <option value="inativo">Inativa</option>
                    </select>
                  </label>
                </div>
              </div>
            </div>

            <div className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
              <div className="text-sm font-semibold text-slate-900">Regras</div>
              <div className="mt-4 grid gap-4 md:grid-cols-2">
                <label className="space-y-2">
                  <div className="text-sm font-semibold text-slate-900">Ordem</div>
                  <input
                    value={String(draft.position ?? 0)}
                    onChange={(e) => setDraft((prev) => ({ ...prev, position: Number(e.target.value || 0) }))}
                    inputMode="numeric"
                    className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-800 outline-none"
                    placeholder="0"
                  />
                </label>

                <label className="space-y-2">
                  <div className="text-sm font-semibold text-slate-900">Início (opcional)</div>
                  <input
                    type="date"
                    value={formatDate(draft.start_at || null)}
                    onChange={(e) =>
                      setDraft((prev) => ({
                        ...prev,
                        start_at: e.target.value ? new Date(`${e.target.value}T00:00:00.000Z`).toISOString() : null,
                      }))
                    }
                    className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-800 outline-none"
                  />
                </label>

                <label className="space-y-2">
                  <div className="text-sm font-semibold text-slate-900">Fim (opcional)</div>
                  <input
                    type="date"
                    value={formatDate(draft.end_at || null)}
                    onChange={(e) =>
                      setDraft((prev) => ({
                        ...prev,
                        end_at: e.target.value ? new Date(`${e.target.value}T23:59:59.999Z`).toISOString() : null,
                      }))
                    }
                    className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-800 outline-none"
                  />
                </label>

                <div className="rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-xs text-slate-600 md:col-span-2">
                  Dica: use “Mostrar em” para limitar a tarja a rotas específicas (prefixo). Ex: <span className="font-semibold">/dashboard</span>
                </div>

                <label className="space-y-2 md:col-span-2">
                  <div className="text-sm font-semibold text-slate-900">Mostrar em (prefixos, separado por vírgula)</div>
                  <input
                    value={showOnPathsText}
                    onChange={(e) => setShowOnPathsText(e.target.value)}
                    placeholder="/dashboard, /dashboard/fornecedores"
                    className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-800 outline-none placeholder:text-slate-400"
                  />
                </label>

                <label className="space-y-2 md:col-span-2">
                  <div className="text-sm font-semibold text-slate-900">Ocultar em (prefixos, separado por vírgula)</div>
                  <input
                    value={hideOnPathsText}
                    onChange={(e) => setHideOnPathsText(e.target.value)}
                    placeholder="/dashboard/settings"
                    className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-800 outline-none placeholder:text-slate-400"
                  />
                </label>
              </div>
            </div>

            {message ? (
              <div
                className={[
                  "rounded-2xl border px-4 py-3 text-sm font-semibold",
                  message.type === "success" ? "border-emerald-200 bg-emerald-50 text-emerald-800" : "border-rose-200 bg-rose-50 text-rose-700",
                ].join(" ")}
              >
                {message.text}
              </div>
            ) : null}
          </div>

          <div className="space-y-4">
            <div className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
              <div className="text-sm font-semibold text-slate-900">Personalização</div>
              <div className="mt-4 grid gap-4">
                <div className="grid gap-4 md:grid-cols-3">
                  <label className="space-y-2">
                    <div className="text-sm font-semibold text-slate-900">Fundo</div>
                    <input
                      type="color"
                      value={String((draft.theme as ThemeConfig | undefined)?.background || variantDefaults(String(draft.variant || "info")).background)}
                      onChange={(e) => setDraft((prev) => ({ ...prev, theme: { ...(prev.theme as ThemeConfig | undefined), background: e.target.value } }))}
                      className="h-11 w-full rounded-xl border border-slate-200 bg-white px-2"
                    />
                  </label>

                  <label className="space-y-2">
                    <div className="text-sm font-semibold text-slate-900">Texto</div>
                    <input
                      type="color"
                      value={String((draft.theme as ThemeConfig | undefined)?.text || variantDefaults(String(draft.variant || "info")).text)}
                      onChange={(e) => setDraft((prev) => ({ ...prev, theme: { ...(prev.theme as ThemeConfig | undefined), text: e.target.value } }))}
                      className="h-11 w-full rounded-xl border border-slate-200 bg-white px-2"
                    />
                  </label>

                  <label className="space-y-2">
                    <div className="text-sm font-semibold text-slate-900">Acento</div>
                    <input
                      type="color"
                      value={String((draft.theme as ThemeConfig | undefined)?.accent || variantDefaults(String(draft.variant || "info")).accent)}
                      onChange={(e) => setDraft((prev) => ({ ...prev, theme: { ...(prev.theme as ThemeConfig | undefined), accent: e.target.value } }))}
                      className="h-11 w-full rounded-xl border border-slate-200 bg-white px-2"
                    />
                  </label>
                </div>

                <div className="grid gap-4 md:grid-cols-2">
                  <div className="space-y-2">
                    <div className="text-sm font-semibold text-slate-900">Emojis no texto</div>
                    <div className="rounded-2xl border border-slate-200 bg-slate-50/80 px-4 py-3 text-sm text-slate-600">
                      Use a carinha ao lado de <span className="font-semibold">Título</span> e <span className="font-semibold">Mensagem</span> para inserir emojis onde quiser no texto.
                    </div>
                  </div>

                  <div className="space-y-2">
                    <div className="text-sm font-semibold text-slate-900">Ícone marca d&apos;água</div>
                    <div className="relative">
                      <button
                        type="button"
                        onClick={() => setWatermarkOpen((prev) => !prev)}
                        className="flex h-11 w-full items-center justify-between rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700"
                      >
                        <span className="flex items-center gap-3">
                          <span className="inline-flex h-8 w-8 items-center justify-center rounded-xl bg-slate-50 text-slate-600">
                            <SelectedWatermarkIcon className="h-4.5 w-4.5" />
                          </span>
                          <span>{selectedWatermark.label}</span>
                        </span>
                        <ChevronDown className={`h-4 w-4 text-slate-400 transition ${watermarkOpen ? "rotate-180" : ""}`} />
                      </button>

                      {watermarkOpen ? (
                        <div className="absolute left-0 right-0 top-12 z-20 rounded-2xl border border-slate-200 bg-white p-2 shadow-xl">
                          <div className="grid gap-1">
                            {ICON_OPTIONS.map((option) => {
                              const Icon = option.icon;
                              const isActive = option.value === selectedWatermark.value;
                              return (
                                <button
                                  key={option.value}
                                  type="button"
                                  onClick={() => {
                                    setDraft((prev) => ({ ...prev, theme: { ...(prev.theme as ThemeConfig | undefined), watermark_icon: option.value } }));
                                    setWatermarkOpen(false);
                                  }}
                                  className={`flex items-center justify-between rounded-xl px-3 py-2 text-sm transition ${
                                    isActive ? "bg-slate-900 text-white" : "text-slate-700 hover:bg-slate-50"
                                  }`}
                                >
                                  <span className="flex items-center gap-3">
                                    <span className={`inline-flex h-9 w-9 items-center justify-center rounded-xl ${isActive ? "bg-white/12" : "bg-slate-50"}`}>
                                      <Icon className="h-4.5 w-4.5" />
                                    </span>
                                    <span>{option.label}</span>
                                  </span>
                                  {isActive ? <Check className="h-4 w-4" /> : null}
                                </button>
                              );
                            })}
                          </div>
                        </div>
                      ) : null}
                    </div>
                  </div>
                </div>

                <div className="rounded-2xl border border-slate-200 bg-slate-50/80 p-4">
                  <div className="text-sm font-semibold text-slate-900">Botão com link</div>
                  <div className="mt-4 grid gap-4 md:grid-cols-2">
                    <label className="space-y-2">
                      <div className="text-sm font-semibold text-slate-900">Texto do botão</div>
                      <input
                        value={String((draft.theme as ThemeConfig | undefined)?.cta_label || "")}
                        onChange={(e) => setDraft((prev) => ({ ...prev, theme: { ...(prev.theme as ThemeConfig | undefined), cta_label: e.target.value } }))}
                        placeholder="Ex: Saiba mais"
                        className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-800 outline-none placeholder:text-slate-400"
                      />
                    </label>

                    <label className="space-y-2">
                      <div className="text-sm font-semibold text-slate-900">URL do botão</div>
                      <input
                        value={String((draft.theme as ThemeConfig | undefined)?.cta_url || "")}
                        onChange={(e) => setDraft((prev) => ({ ...prev, theme: { ...(prev.theme as ThemeConfig | undefined), cta_url: e.target.value } }))}
                        placeholder="https://..."
                        className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-800 outline-none placeholder:text-slate-400"
                      />
                    </label>
                  </div>

                  <label className="mt-4 inline-flex items-center gap-3 text-sm font-medium text-slate-700">
                    <input
                      type="checkbox"
                      checked={Boolean((draft.theme as ThemeConfig | undefined)?.cta_new_tab)}
                      onChange={(e) => setDraft((prev) => ({ ...prev, theme: { ...(prev.theme as ThemeConfig | undefined), cta_new_tab: e.target.checked } }))}
                      className="h-4 w-4 rounded border-slate-300 text-slate-900 focus:ring-slate-300"
                    />
                    Abrir o botão em nova aba
                  </label>
                </div>

                <button
                  type="button"
                  onClick={() => setDraft((prev) => ({ ...prev, theme: {} }))}
                  className="inline-flex h-11 items-center justify-center rounded-xl bg-white px-4 text-sm font-semibold text-slate-700 shadow-sm ring-1 ring-slate-200 transition hover:bg-slate-50 active:scale-95"
                >
                  Resetar cores
                </button>
              </div>
            </div>

            <div className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
              <div className="text-sm font-semibold text-slate-900">Preview</div>
              <div className="mt-4">
                <div
                  className="relative overflow-hidden rounded-2xl border px-4 py-4"
                  style={{
                    borderColor: `${computedTheme.accent}33`,
                    background: computedTheme.background,
                    color: computedTheme.text,
                  }}
                >
                  {WatermarkIcon ? (
                    <div className="pointer-events-none absolute -right-3 -top-6 opacity-[0.14]">
                      <WatermarkIcon size={88} style={{ color: computedTheme.text, transform: "rotate(32deg)" }} />
                    </div>
                  ) : null}

                  <div className="relative flex items-start justify-between gap-4">
                    <div className="min-w-0">
                      <div className="text-xs font-semibold uppercase tracking-[0.18em]" style={{ color: computedTheme.accent }}>
                        {String(draft.variant || "info")}
                      </div>
                      <div className="mt-1 text-base font-semibold tracking-[-0.02em]">{String(draft.title || "").trim() ? String(draft.title) : "Título opcional"}</div>
                      <div className="mt-2 text-sm leading-6 opacity-90">{String(draft.message || "").trim() || "Mensagem da tarja..."}</div>
                      <div className="mt-3 flex flex-wrap items-center gap-2">
                        {computedTheme.cta_label && computedTheme.cta_url ? (
                          <span
                            className="inline-flex h-8 items-center gap-1 rounded-full border px-3 text-xs font-semibold"
                            style={{ borderColor: `${computedTheme.accent}40`, background: `${computedTheme.accent}18`, color: computedTheme.text }}
                          >
                            {computedTheme.cta_label}
                            <ArrowRight className="h-3.5 w-3.5" />
                          </span>
                        ) : null}
                        <span className="text-xs opacity-70">
                          Escopo: {String(draft.scope || "owner")} • {String(draft.dismiss_mode || "dismissible")}
                        </span>
                      </div>
                    </div>
                    {String(draft.dismiss_mode || "dismissible") !== "sticky" ? (
                      <div
                        className="flex h-8 w-8 items-center justify-center rounded-full"
                        style={{ background: `${computedTheme.accent}22`, color: computedTheme.text }}
                      >
                        <span className="text-sm font-bold">×</span>
                      </div>
                    ) : null}
                  </div>
                </div>
              </div>
            </div>

            <div className="rounded-2xl border border-slate-200 bg-white px-4 py-4 shadow-sm">
              <div className="text-sm font-semibold text-slate-900">Como aparece</div>
              <div className="mt-2 text-sm text-slate-600">
                A tarja é exibida automaticamente no topo. Se estiver “Fechável”, o usuário pode dispensar e o sistema lembra disso no dispositivo.
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
