"use client";

import React, { useEffect, useRef, useState } from "react";
import { QRCodeSVG } from "qrcode.react";
import { QR_STAND_PRESETS, type QrStandPreset } from "@menulio/shared";

const LOCAL_STORAGE_KEY = "menulio_qr_templates_v2";

// Popüler Google Fonts Listesi
export const POPULAR_GOOGLE_FONTS = [
  // 👑 Lüks & Klasik Serif
  { name: "Playfair Display", category: "Lüks Serif", family: "'Playfair Display', serif" },
  { name: "Cinzel", category: "Lüks Serif", family: "'Cinzel', serif" },
  { name: "Cormorant Garamond", category: "Lüks Serif", family: "'Cormorant Garamond', serif" },
  { name: "Bodoni Moda", category: "Lüks Serif", family: "'Bodoni Moda', serif" },
  { name: "Italiana", category: "Lüks Serif", family: "'Italiana', serif" },
  { name: "Prata", category: "Lüks Serif", family: "'Prata', serif" },
  { name: "Marcellus", category: "Lüks Serif", family: "'Marcellus', serif" },
  { name: "Cinzel Decorative", category: "Lüks Serif", family: "'Cinzel Decorative', serif" },
  { name: "Abril Fatface", category: "Lüks Serif", family: "'Abril Fatface', serif" },

  // ✨ Modern & Minimalist Sans
  { name: "Plus Jakarta Sans", category: "Modern Sans", family: "'Plus Jakarta Sans', sans-serif" },
  { name: "Inter", category: "Modern Sans", family: "'Inter', sans-serif" },
  { name: "Montserrat", category: "Modern Sans", family: "'Montserrat', sans-serif" },
  { name: "Outfit", category: "Modern Sans", family: "'Outfit', sans-serif" },
  { name: "Space Grotesk", category: "Modern Sans", family: "'Space Grotesk', sans-serif" },
  { name: "Poppins", category: "Modern Sans", family: "'Poppins', sans-serif" },
  { name: "Oswald", category: "Modern Sans", family: "'Oswald', sans-serif" },
  { name: "Syne", category: "Modern Sans", family: "'Syne', sans-serif" },

  // ✍️ El Yazısı / Kaligrafi
  { name: "Great Vibes", category: "Kaligrafi", family: "'Great Vibes', cursive" },
  { name: "Caveat", category: "Kaligrafi", family: "'Caveat', cursive" },
  { name: "Alex Brush", category: "Kaligrafi", family: "'Alex Brush', cursive" },
  { name: "Dancing Script", category: "Kaligrafi", family: "'Dancing Script', cursive" },
  { name: "Pacifico", category: "Kaligrafi", family: "'Pacifico', cursive" },
];

// Hızlı Renk Paletleri
export const QUICK_COLOR_PALETTES = [
  { name: "Altın", value: "#D4AF37" },
  { name: "Krem Altın", value: "#E5C378" },
  { name: "Saf Beyaz", value: "#FFFFFF" },
  { name: "Gece Siyahı", value: "#0C0C0E" },
  { name: "Gümüş Gri", value: "#94A3B8" },
  { name: "Zümrüt Yeşili", value: "#10B981" },
  { name: "Yakut Kırmızı", value: "#EF4444" },
  { name: "Sıcak Amber", value: "#F59E0B" },
  { name: "Buz Mavisi", value: "#38BDF8" },
  { name: "Bronz", value: "#CD7F32" },
];

interface EditableTemplate extends QrStandPreset {
  isActive: boolean;
  bgType?: "gradient" | "image" | "svg";
  bgImageUrl?: string;
  qrConfig: {
    xPercent: number;
    yPercent: number;
    size: number;
    borderRadius: number;
    borderWidth?: number;
    borderColor: string;
    bgBoxColor: string;
    padding?: number;
  };
  layers: Array<{
    id: string;
    text: string;
    yPercent: number;
    fontSize: number;
    fontFamily: string;
    color: string;
    fontWeight: string;
    letterSpacing?: number;
    curveDegree?: number;
  }>;
}

const CurvedTextWeb: React.FC<{
  text: string;
  fontSize: number;
  color: string;
  fontFamily: string;
  fontWeight?: string;
  letterSpacing?: number;
  curveDegree: number;
}> = ({ text, fontSize, color, fontFamily, fontWeight = "700", letterSpacing = 0.5, curveDegree }) => {
  const isUp = curveDegree > 0;
  const absDegree = Math.abs(curveDegree);
  const radius = Math.max(40, 420 - absDegree * 3.5);
  const charWidth = fontSize * 0.52 + (letterSpacing || 0);
  const numChars = text.length;
  const arcLength = numChars * charWidth;
  const totalAngleRad = arcLength / radius;
  const stepRad = numChars > 1 ? totalAngleRad / (numChars - 1) : 0;
  const startAngleRad = -totalAngleRad / 2;

  const maxOffsetY = Math.abs(-radius * (Math.cos(totalAngleRad / 2) - 1));
  const containerHeight = fontSize + maxOffsetY + 10;
  const containerWidth = Math.max(numChars * charWidth, radius * 2 * Math.sin(totalAngleRad / 2)) + 16;

  return (
    <div
      style={{
        position: "relative",
        width: `${containerWidth}px`,
        height: `${containerHeight}px`,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        pointerEvents: "none",
      }}
    >
      {text.split("").map((ch, i) => {
        const angleRad = startAngleRad + i * stepRad;
        const angleDeg = angleRad * (180 / Math.PI);
        const charX = radius * Math.sin(angleRad);
        const charY = isUp
          ? -radius * (Math.cos(angleRad) - 1)
          : radius * (Math.cos(angleRad) - 1);
        const charRotate = isUp ? angleDeg : -angleDeg;

        return (
          <span
            key={i}
            style={{
              position: "absolute",
              fontSize: `${fontSize}px`,
              color,
              fontFamily,
              fontWeight,
              letterSpacing: `${letterSpacing}px`,
              transform: `translate(${charX}px, ${charY}px) rotate(${charRotate}deg)`,
              whiteSpace: "pre",
              lineHeight: 1,
            }}
          >
            {ch === " " ? "\u00A0" : ch}
          </span>
        );
      })}
    </div>
  );
};

const FALLBACK_DEFAULT: EditableTemplate = {
  key: "qr-1",
  name: "Lumière Restaurant (QR-1)",
  categoryName: "Özel Masa Kartı",
  svgTemplateUrl: "/qr-1.svg",
  aspectRatio: "1/1",
  bgType: "gradient",
  bgGradient: "radial-gradient(circle at 50% 50%, #132034 0%, #0b0d13 100%)",
  plaqueColor: "#132034",
  borderAccent: "#d4af37",
  accentText: "#d4af37",
  headerText: "#FFFFFF",
  subText: "#e5c378",
  dividerColor: "rgba(212, 175, 55, 0.3)",
  isActive: true,
  qrConfig: {
    xPercent: 50,
    yPercent: 38,
    size: 115,
    borderRadius: 14,
    borderColor: "#D4AF37",
    bgBoxColor: "#FFFFFF",
  },
  layers: [
    {
      id: "rName",
      text: "{{RESTAURANT_NAME}}",
      yPercent: 16,
      fontSize: 18,
      fontFamily: "'Playfair Display', serif",
      color: "#D4AF37",
      fontWeight: "800",
    },
    {
      id: "sub",
      text: "RESTAURANT & BAR",
      yPercent: 26,
      fontSize: 10,
      fontFamily: "'Plus Jakarta Sans', sans-serif",
      color: "#E5C378",
      fontWeight: "600",
      letterSpacing: 1.5,
    },
    {
      id: "cta",
      text: "MENÜYÜ GÖRMEK İÇİN OKUTUN",
      yPercent: 80,
      fontSize: 11,
      fontFamily: "'Playfair Display', serif",
      color: "#FFFFFF",
      fontWeight: "700",
      letterSpacing: 1,
    },
    {
      id: "table",
      text: "MASA NO: 01  •  WIFI: Bistro",
      yPercent: 90,
      fontSize: 9,
      fontFamily: "'Plus Jakarta Sans', sans-serif",
      color: "#A1A1AA",
      fontWeight: "600",
    },
  ],
};

function presetToEditable(p: QrStandPreset): EditableTemplate {
  const isSquare = p.aspectRatio === "1/1";
  return {
    ...p,
    isActive: true,
    bgType: "gradient",
    qrConfig: {
      xPercent: 50,
      yPercent: isSquare ? 38 : 36,
      size: isSquare ? 115 : 125,
      borderRadius: 14,
      borderColor: p.borderAccent || "#D4AF37",
      bgBoxColor: "#FFFFFF",
    },
    layers: [
      {
        id: "rName",
        text: "{{RESTAURANT_NAME}}",
        yPercent: isSquare ? 16 : 14,
        fontSize: 18,
        fontFamily: "'Playfair Display', serif",
        color: p.accentText || "#D4AF37",
        fontWeight: "800",
        letterSpacing: 2,
      },
      {
        id: "sub",
        text: "RESTAURANT & BAR",
        yPercent: isSquare ? 26 : 22,
        fontSize: 10,
        fontFamily: "'Plus Jakarta Sans', sans-serif",
        color: p.subText || "#E5C378",
        fontWeight: "600",
        letterSpacing: 1.5,
      },
      {
        id: "cta",
        text: "MENÜYÜ GÖRMEK İÇİN OKUTUN",
        yPercent: isSquare ? 80 : 82,
        fontSize: 11,
        fontFamily: "'Playfair Display', serif",
        color: p.headerText || "#FFFFFF",
        fontWeight: "700",
        letterSpacing: 1,
      },
      {
        id: "table",
        text: "MASA NO: 01  •  WIFI: Bistro",
        yPercent: isSquare ? 90 : 91,
        fontSize: 9,
        fontFamily: "'Plus Jakarta Sans', sans-serif",
        color: p.subText || "#A1A1AA",
        fontWeight: "600",
      },
    ],
  };
}

export function TemplateStudioAdminClient() {
  const [templates, setTemplates] = useState<EditableTemplate[]>(() => {
    const list = Object.values(QR_STAND_PRESETS).map(presetToEditable);
    return list.length > 0 ? list : [FALLBACK_DEFAULT];
  });

  const [selectedKey, setSelectedKey] = useState<string>(templates[0]?.key || "qr-1");
  const [searchQuery, setSearchQuery] = useState<string>("");
  const [testRestaurantName, setTestRestaurantName] = useState<string>("OZZY KEBAP");
  const [jsonModalOpen, setJsonModalOpen] = useState<boolean>(false);
  const [jsonInput, setJsonInput] = useState<string>("");
  const [saveToast, setSaveToast] = useState<string | null>(null);
  const [isSaving, setIsSaving] = useState<boolean>(false);
  const [activeTab, setActiveTab] = useState<"visual" | "json">("visual");

  // Özel Google Font Giriş State'i
  const [customFontInput, setCustomFontInput] = useState<string>("");

  // Mouse ile Tuval Üzerinde Sürükleme State'leri
  const [activeDragItem, setActiveDragItem] = useState<{
    type: "qr" | "layer";
    id?: string;
  } | null>(null);

  const [selectedCanvasElement, setSelectedCanvasElement] = useState<string | "qr" | null>("rName");

  const canvasContainerRef = useRef<HTMLDivElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // 1. Google Fonts Dinamik Yükleyici
  useEffect(() => {
    const fontNames = new Set<string>();

    POPULAR_GOOGLE_FONTS.forEach((f) => fontNames.add(f.name));

    templates.forEach((t) => {
      (t.layers || []).forEach((l) => {
        if (l.fontFamily) {
          const rawName = (l.fontFamily || "").split(",")[0]?.replace(/['"]/g, "").trim();
          if (rawName && rawName !== "sans-serif" && rawName !== "serif" && rawName !== "cursive") {
            fontNames.add(rawName);
          }
        }
      });
    });

    fontNames.forEach((font) => {
      const cleanId = `gfont-${font.replace(/[^a-zA-Z0-9]/g, "-").toLowerCase()}`;
      if (!document.getElementById(cleanId)) {
        const link = document.createElement("link");
        link.id = cleanId;
        link.rel = "stylesheet";
        link.href = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(font)}:ital,wght@0,400;0,600;0,700;0,800;0,900;1,400;1,700&display=swap`;
        document.head.appendChild(link);
      }
    });
  }, [templates]);

  // 2. Önce localStorage, sonra API / DB'den yükle
  useEffect(() => {
    try {
      const cached = localStorage.getItem(LOCAL_STORAGE_KEY);
      if (cached) {
        const parsed = JSON.parse(cached);
        if (Array.isArray(parsed) && parsed.length > 0) {
          setTemplates(parsed);
          setSelectedKey(parsed[0].key);
        }
      }
    } catch {}

    async function loadFromApi() {
      try {
        const res = await fetch("/api/qr-templates");
        if (res && res.ok) {
          const data = await res.json();
          if (data.templates && data.templates.length > 0) {
            const mapped = data.templates.map((t: any) => ({
              ...t,
              qrConfig: t.defaultQrConfig || t.qrConfig || {
                xPercent: 50,
                yPercent: 38,
                size: 115,
                borderRadius: 14,
                borderColor: "#D4AF37",
                bgBoxColor: "#FFFFFF",
              },
              layers: t.defaultLayers || t.layers || [
                {
                  id: "rName",
                  text: "{{RESTAURANT_NAME}}",
                  yPercent: 16,
                  fontSize: 18,
                  fontFamily: "'Playfair Display', serif",
                  color: t.accentText || "#D4AF37",
                  fontWeight: "800",
                },
                {
                  id: "sub",
                  text: "RESTAURANT & BAR",
                  yPercent: 26,
                  fontSize: 10,
                  fontFamily: "'Plus Jakarta Sans', sans-serif",
                  color: t.subText || "#E5C378",
                  fontWeight: "600",
                  letterSpacing: 1.5,
                },
                {
                  id: "cta",
                  text: "MENÜYÜ GÖRMEK İÇİN OKUTUN",
                  yPercent: 80,
                  fontSize: 11,
                  fontFamily: "'Playfair Display', serif",
                  color: t.headerText || "#FFFFFF",
                  fontWeight: "700",
                  letterSpacing: 1,
                },
                {
                  id: "table",
                  text: "MASA NO: 01  •  WIFI: Bistro",
                  yPercent: 90,
                  fontSize: 9,
                  fontFamily: "'Plus Jakarta Sans', sans-serif",
                  color: t.subText || "#A1A1AA",
                  fontWeight: "600",
                },
              ],
            }));
            setTemplates(mapped);
            if (!mapped.some((m: any) => m.key === selectedKey)) {
              setSelectedKey(mapped[0]?.key || "qr-1");
            }
          }
        }
      } catch {}
    }
    loadFromApi();
  }, []);

  const currentTemplate: EditableTemplate =
    templates.find((t) => t.key === selectedKey) || templates[0] || FALLBACK_DEFAULT;

  const filteredTemplates = templates.filter(
    (t) =>
      t.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      t.key.toLowerCase().includes(searchQuery.toLowerCase())
  );

  // Güncelleme Yardımcısı
  const updateCurrent = (updates: Partial<EditableTemplate>) => {
    setTemplates((prev) => {
      const next = prev.map((t) => (t.key === currentTemplate.key ? { ...t, ...updates } : t));
      try {
        localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(next));
      } catch {}
      return next;
    });
  };

  // Katman Rengi Güncelleme (Anında hem katmana hem genel template alanına yansır)
  const handleLayerColorChange = (layerId: string, newColor: string) => {
    const updatedLayers = (currentTemplate.layers || []).map((l) =>
      l.id === layerId ? { ...l, color: newColor } : l
    );

    const extraUpdates: Partial<EditableTemplate> = { layers: updatedLayers };
    if (layerId === "rName") extraUpdates.accentText = newColor;
    if (layerId === "sub") extraUpdates.subText = newColor;
    if (layerId === "cta") extraUpdates.headerText = newColor;
    if (layerId === "table") extraUpdates.subText = newColor;

    updateCurrent(extraUpdates);
  };

  // Katman Metin İçeriğini Güncelle
  const handleLayerTextChange = (layerId: string, newText: string) => {
    const updatedLayers = (currentTemplate.layers || []).map((l) =>
      l.id === layerId ? { ...l, text: newText } : l
    );
    updateCurrent({ layers: updatedLayers });
  };

  // Section 2'deki Metin Vurgu Rengi Değişimi
  const handleAccentTextColorChange = (newColor: string) => {
    const updatedLayers = (currentTemplate.layers || []).map((l) =>
      l.id === "rName" ? { ...l, color: newColor } : l
    );
    updateCurrent({
      accentText: newColor,
      layers: updatedLayers,
    });
  };

  // Özel Google Font Ekle
  const handleAddCustomGoogleFont = () => {
    const trimmed = customFontInput.trim();
    if (!trimmed) return;

    const cleanId = `gfont-${trimmed.replace(/[^a-zA-Z0-9]/g, "-").toLowerCase()}`;
    if (!document.getElementById(cleanId)) {
      const link = document.createElement("link");
      link.id = cleanId;
      link.rel = "stylesheet";
      link.href = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(trimmed)}:wght@400;600;700;800;900&display=swap`;
      document.head.appendChild(link);
    }

    const targetLayerId = selectedCanvasElement && selectedCanvasElement !== "qr" ? selectedCanvasElement : "rName";
    const updatedLayers = (currentTemplate.layers || []).map((l) =>
      l.id === targetLayerId ? { ...l, fontFamily: `'${trimmed}', serif` } : l
    );
    updateCurrent({ layers: updatedLayers });

    setCustomFontInput("");
    showToast(`"${trimmed}" fontu yüklendi ve uygulandı! ✨`);
  };

  // Mouse Drag Handler (Tuval üzerinde QR veya Metin Taşıma)
  const handleCanvasMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
    if (!activeDragItem || !canvasContainerRef.current) return;
    const rect = canvasContainerRef.current.getBoundingClientRect();
    const mouseX = e.clientX - rect.left;
    const mouseY = e.clientY - rect.top;

    let xPercent = Math.max(10, Math.min(90, Math.round((mouseX / rect.width) * 100)));
    let yPercent = Math.max(8, Math.min(92, Math.round((mouseY / rect.height) * 100)));

    if (Math.abs(xPercent - 50) <= 3) {
      xPercent = 50;
    }

    if (activeDragItem.type === "qr") {
      updateCurrent({
        qrConfig: {
          ...currentTemplate.qrConfig,
          xPercent,
          yPercent,
        },
      });
    } else if (activeDragItem.type === "layer" && activeDragItem.id) {
      const updatedLayers = (currentTemplate.layers || []).map((l) =>
        l.id === activeDragItem.id ? { ...l, yPercent } : l
      );
      updateCurrent({ layers: updatedLayers });
    }
  };

  const handleCanvasMouseUp = () => {
    setActiveDragItem(null);
  };

  // Dosya Yükleme (SVG / PNG / JPG)
  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (event) => {
      const result = event.target?.result as string;
      if (result) {
        updateCurrent({
          bgType: "image",
          bgImageUrl: result,
        });
        showToast("Arka plan görseli yüklendi!");
      }
    };
    reader.readAsDataURL(file);
  };

  // Yeni Şablon Oluştur
  const handleCreateNew = () => {
    const newKey = `qr-${Date.now().toString().slice(-4)}`;
    const newTpl: EditableTemplate = {
      key: newKey,
      name: `Yeni Lüks Şablon (${newKey.toUpperCase()})`,
      categoryName: "Özel Tasarım",
      svgTemplateUrl: `/${newKey}.svg`,
      aspectRatio: "1/1",
      bgType: "gradient",
      bgGradient: "radial-gradient(circle at 50% 50%, #1e1b4b 0%, #0f172a 100%)",
      plaqueColor: "#0f172a",
      borderAccent: "#D4AF37",
      accentText: "#D4AF37",
      headerText: "#FFFFFF",
      subText: "#94A3B8",
      dividerColor: "rgba(212, 175, 55, 0.3)",
      isActive: true,
      qrConfig: {
        xPercent: 50,
        yPercent: 38,
        size: 115,
        borderRadius: 14,
        borderColor: "#D4AF37",
        bgBoxColor: "#FFFFFF",
      },
      layers: [
        {
          id: "rName",
          text: "{{RESTAURANT_NAME}}",
          yPercent: 16,
          fontSize: 18,
          fontFamily: "'Playfair Display', serif",
          color: "#D4AF37",
          fontWeight: "800",
        },
        {
          id: "cta",
          text: "MENÜYÜ GÖRMEK İÇİN OKUTUN",
          yPercent: 82,
          fontSize: 11,
          fontFamily: "'Playfair Display', serif",
          color: "#FFFFFF",
          fontWeight: "700",
        },
      ],
    };

    const nextList = [newTpl, ...templates];
    setTemplates(nextList);
    setSelectedKey(newKey);
    try {
      localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(nextList));
    } catch {}
    showToast("Yeni şablon taslağı oluşturuldu!");
  };

  // Şablon Klonla
  const handleClone = (tpl: EditableTemplate) => {
    const cloneKey = `${tpl.key}-copy-${Date.now().toString().slice(-3)}`;
    const cloned: EditableTemplate = {
      ...tpl,
      key: cloneKey,
      name: `${tpl.name} (Kopya)`,
    };
    const nextList = [cloned, ...templates];
    setTemplates(nextList);
    setSelectedKey(cloneKey);
    try {
      localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(nextList));
    } catch {}
    showToast("Şablon başarıyla çoğaltıldı!");
  };

  // Şablon Sil
  const handleDelete = async (key: string) => {
    if (templates.length <= 1) {
      alert("En az bir şablon kalmalıdır.");
      return;
    }
    if (confirm("Bu şablonu silmek istediğinize emin misiniz?")) {
      const remaining = templates.filter((t) => t.key !== key);
      setTemplates(remaining);
      setSelectedKey(remaining[0]?.key || "");
      try {
        localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(remaining));
      } catch {}

      try {
        const res = await fetch(`/api/qr-templates?key=${encodeURIComponent(key)}`, { method: "DELETE" });
        if (res.ok) {
          showToast("Şablon veritabanından ve yayından silindi! 🗑️");
        } else {
          showToast("Şablon silindi.");
        }
      } catch {
        showToast("Şablon silindi.");
      }
    }
  };

  // Toast Bildirimi
  const showToast = (msg: string) => {
    setSaveToast(msg);
    setTimeout(() => setSaveToast(null), 3000);
  };

  // Kaydet ve API'ye / DB'ye Yayınla
  const handleSaveAndPublish = async () => {
    setIsSaving(true);
    try {
      localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(templates));
    } catch {}

    try {
      const payload = {
        ...currentTemplate,
        defaultQrConfig: currentTemplate.qrConfig,
        defaultLayers: currentTemplate.layers,
      };

      const res = await fetch("/api/qr-templates", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      if (res.ok) {
        showToast("Şablon, renkler ve fontlar kaydedildi ve yayınlandı! 🎉");
      } else {
        showToast("Şablon yerel olarak kaydedildi.");
      }
    } catch {
      showToast("Şablon yerel olarak kaydedildi.");
    } finally {
      setIsSaving(false);
    }
  };

  // JSON Dışa Aktar
  const handleExportJson = () => {
    const jsonStr = JSON.stringify(templates, null, 2);
    navigator.clipboard.writeText(jsonStr);
    showToast("Tüm şablon JSON verisi panoya kopyalandı!");
  };

  // JSON İçe Aktar
  const handleImportJson = () => {
    try {
      const parsed = JSON.parse(jsonInput);
      let nextList = templates;
      if (Array.isArray(parsed)) {
        nextList = parsed;
        setTemplates(parsed);
        setSelectedKey(parsed[0]?.key || "");
      } else if (parsed.key) {
        nextList = [parsed, ...templates.filter((t) => t.key !== parsed.key)];
        setTemplates(nextList);
        setSelectedKey(parsed.key);
      }
      try {
        localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(nextList));
      } catch {}
      setJsonModalOpen(false);
      setJsonInput("");
      showToast("JSON başarıyla içe aktarıldı ve kaydedildi!");
    } catch {
      alert("Geçersiz JSON formatı.");
    }
  };

  // Aspect ratio hesaplama
  const [aspectW, aspectH] = (currentTemplate.aspectRatio || "1/1").split("/").map(Number);
  const previewRatio = aspectW && aspectH ? aspectW / aspectH : 1;
  const previewWidth = 320;
  const previewHeight = Math.round(previewWidth / previewRatio);

  const activeEditingLayer =
    (currentTemplate.layers || []).find((l) => l.id === selectedCanvasElement) ||
    currentTemplate.layers?.[0] || {
      id: "rName",
      text: "{{RESTAURANT_NAME}}",
      yPercent: 16,
      fontSize: 18,
      fontFamily: "'Playfair Display', serif",
      color: "#D4AF37",
      fontWeight: "800",
    };

  return (
    <div className="space-y-6 select-none">
      {/* Toast Mesajı */}
      {saveToast && (
        <div className="fixed bottom-6 right-6 z-50 bg-[#D4AF37] text-black font-extrabold px-5 py-3 rounded-xl shadow-2xl shadow-black flex items-center gap-2 animate-bounce">
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.5" d="M5 13l4 4L19 7" />
          </svg>
          {saveToast}
        </div>
      )}

      {/* Gizli Dosya Seçici */}
      <input
        ref={fileInputRef}
        type="file"
        accept=".svg,.png,.jpg,.jpeg,.webp"
        onChange={handleFileUpload}
        className="hidden"
      />

      {/* Üst Eylem ve Arama Çubuğu */}
      <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 bg-[#121215] p-4 rounded-2xl border border-white/10">
        <div className="flex items-center gap-3">
          <div className="relative">
            <svg className="w-4 h-4 text-zinc-400 absolute left-3 top-1/2 -translate-y-1/2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
            </svg>
            <input
              type="text"
              placeholder="Şablon ara (örn: Lumière, qr-1)..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="bg-black/40 border border-white/10 rounded-xl pl-9 pr-4 py-2 text-xs text-white placeholder-zinc-500 focus:outline-none focus:border-[#D4AF37] w-64"
            />
          </div>
          <div className="text-xs text-zinc-400 font-medium">
            Toplam: <span className="text-white font-bold">{templates.length}</span> Şablon
          </div>
        </div>

        <div className="flex items-center gap-2 flex-wrap">
          <button
            onClick={() => setJsonModalOpen(true)}
            className="px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs font-semibold text-zinc-300 transition-all flex items-center gap-2"
          >
            <svg className="w-3.5 h-3.5 text-[#D4AF37]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
            </svg>
            JSON İçe Aktar
          </button>

          <button
            onClick={handleExportJson}
            className="px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs font-semibold text-zinc-300 transition-all flex items-center gap-2"
          >
            <svg className="w-3.5 h-3.5 text-[#D4AF37]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
            </svg>
            JSON Kopyala
          </button>

          <button
            onClick={handleCreateNew}
            className="px-4 py-2 rounded-xl bg-gradient-to-r from-[#D4AF37] to-[#F59E0B] text-[#0C0C0E] font-bold text-xs shadow-lg shadow-[#D4AF37]/20 hover:opacity-95 transition-all flex items-center gap-1.5"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v16m8-8H4" />
            </svg>
            + Yeni Şablon Ekle
          </button>
        </div>
      </div>

      {/* Ana Çift Kolonlu Çalışma Alanı */}
      <div className="grid grid-cols-1 xl:grid-cols-12 gap-6 items-start">
        {/* SOL: ŞABLON LİSTESİ & PARAMETRELER (7 KOLON) */}
        <div className="xl:col-span-7 space-y-6">
          {/* Yatay Şablon Kartları */}
          <div className="bg-[#121215] p-4 rounded-2xl border border-white/10 space-y-3">
            <div className="text-xs font-bold text-zinc-400 uppercase tracking-wider">
              Şablon Seç & Düzenle
            </div>
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-2.5 max-h-48 overflow-y-auto pr-1">
              {filteredTemplates.map((tpl) => {
                const isSelected = tpl.key === selectedKey;
                return (
                  <button
                    key={tpl.key}
                    onClick={() => {
                      setSelectedKey(tpl.key);
                      setSelectedCanvasElement("rName");
                    }}
                    className={`p-3 rounded-xl text-left border transition-all flex flex-col justify-between gap-2 ${
                      isSelected
                        ? "bg-[#D4AF37]/15 border-[#D4AF37] shadow-sm shadow-[#D4AF37]/20"
                        : "bg-white/[0.03] border-white/5 hover:bg-white/[0.06]"
                    }`}
                  >
                    <div>
                      <div className="text-[10px] font-mono text-zinc-500 uppercase">{tpl.key}</div>
                      <div className="font-bold text-xs text-white line-clamp-1">{tpl.name}</div>
                    </div>
                    <div className="flex items-center justify-between text-[10px] text-zinc-400">
                      <span>{tpl.aspectRatio || "1/1"}</span>
                      <span className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: tpl.plaqueColor || "#D4AF37" }} />
                    </div>
                  </button>
                );
              })}
            </div>
          </div>

          {/* Şablon Parametre Editörü */}
          <div className="bg-[#121215] rounded-2xl border border-white/10 overflow-hidden">
            {/* Editör Sekmeleri */}
            <div className="border-b border-white/10 px-6 py-3 flex items-center justify-between bg-black/20">
              <div className="flex items-center gap-2">
                <button
                  onClick={() => setActiveTab("visual")}
                  className={`px-3 py-1.5 rounded-lg text-xs font-bold transition-all ${
                    activeTab === "visual"
                      ? "bg-[#D4AF37] text-[#0C0C0E]"
                      : "text-zinc-400 hover:text-white"
                  }`}
                >
                  Görsel Parametreler & Fontlar
                </button>
                <button
                  onClick={() => setActiveTab("json")}
                  className={`px-3 py-1.5 rounded-lg text-xs font-bold transition-all ${
                    activeTab === "json"
                      ? "bg-[#D4AF37] text-[#0C0C0E]"
                      : "text-zinc-400 hover:text-white"
                  }`}
                >
                  Ham JSON Kodu
                </button>
              </div>

              <div className="flex items-center gap-2">
                <button
                  onClick={() => handleClone(currentTemplate)}
                  className="px-2.5 py-1 rounded-lg bg-white/5 hover:bg-white/10 text-zinc-300 text-xs font-medium"
                >
                  Çoğalt
                </button>
                <button
                  onClick={() => handleDelete(currentTemplate.key)}
                  className="px-2.5 py-1 rounded-lg bg-red-500/10 hover:bg-red-500/20 text-red-400 text-xs font-medium"
                >
                  Sil
                </button>
              </div>
            </div>

            {/* Sekme 1: Görsel Editör Formu */}
            {activeTab === "visual" && (
              <div className="p-6 space-y-6">
                {/* 1. Temel Bilgiler */}
                <div className="space-y-4">
                  <div className="text-xs font-bold text-[#D4AF37] uppercase tracking-wider">
                    1. Temel Şablon Bilgileri
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="space-y-1.5">
                      <label className="text-xs text-zinc-400 font-medium">Şablon Key (Benzersiz ID)</label>
                      <input
                        type="text"
                        value={currentTemplate.key}
                        onChange={(e) => updateCurrent({ key: e.target.value })}
                        className="w-full bg-black/40 border border-white/10 rounded-xl px-3 py-2 text-xs text-white font-mono focus:border-[#D4AF37] outline-none"
                      />
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-xs text-zinc-400 font-medium">Şablon Adı</label>
                      <input
                        type="text"
                        value={currentTemplate.name}
                        onChange={(e) => updateCurrent({ name: e.target.value })}
                        className="w-full bg-black/40 border border-white/10 rounded-xl px-3 py-2 text-xs text-white focus:border-[#D4AF37] outline-none"
                      />
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-xs text-zinc-400 font-medium">Kategori</label>
                      <input
                        type="text"
                        value={currentTemplate.categoryName || ""}
                        onChange={(e) => updateCurrent({ categoryName: e.target.value })}
                        className="w-full bg-black/40 border border-white/10 rounded-xl px-3 py-2 text-xs text-white focus:border-[#D4AF37] outline-none"
                      />
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-xs text-zinc-400 font-medium">En/Boy Oranı (Aspect Ratio)</label>
                      <select
                        value={currentTemplate.aspectRatio || "1/1"}
                        onChange={(e) => updateCurrent({ aspectRatio: e.target.value })}
                        className="w-full bg-black/40 border border-white/10 rounded-xl px-3 py-2 text-xs text-white focus:border-[#D4AF37] outline-none"
                      >
                        <option value="1/1">1:1 (Kare Standart Masa Kartı)</option>
                        <option value="400/650">400:650 (A5 Dikey Matbaa Kartı)</option>
                        <option value="400/580">400:580 (Dikey Akrilik Stand)</option>
                        <option value="380/500">380:500 (Kompakt Masa Standı)</option>
                      </select>
                    </div>
                  </div>
                </div>

                {/* 2. Arka Plan Resmi / SVG / Renkler */}
                <div className="space-y-4 pt-4 border-t border-white/5">
                  <div className="flex items-center justify-between">
                    <div className="text-xs font-bold text-[#D4AF37] uppercase tracking-wider">
                      2. Arka Plan Resmi & Tasarım Dokusu
                    </div>
                    <button
                      type="button"
                      onClick={() => fileInputRef.current?.click()}
                      className="px-3 py-1.5 rounded-lg bg-[#D4AF37]/20 border border-[#D4AF37]/40 text-[#D4AF37] text-xs font-bold hover:bg-[#D4AF37]/30 transition-all flex items-center gap-1.5"
                    >
                      <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
                      </svg>
                      Figma / Bilgisayardan Görsel/SVG Yükle
                    </button>
                  </div>

                  {currentTemplate.bgImageUrl ? (
                    <div className="p-3 bg-black/40 rounded-xl border border-white/10 flex items-center justify-between gap-3">
                      <div className="flex items-center gap-3">
                        <img
                          src={currentTemplate.bgImageUrl}
                          alt="Arka Plan"
                          className="w-12 h-12 rounded-lg object-cover border border-white/10"
                        />
                        <div>
                          <div className="text-xs font-bold text-white">Özel Arka Plan Yüklendi</div>
                          <div className="text-[10px] text-emerald-400">Canlı tuvalde aktif</div>
                        </div>
                      </div>
                      <button
                        onClick={() => updateCurrent({ bgImageUrl: undefined, bgType: "gradient" })}
                        className="text-xs text-red-400 hover:underline"
                      >
                        Görseli Kaldır
                      </button>
                    </div>
                  ) : (
                    <div
                      onClick={() => fileInputRef.current?.click()}
                      className="border-2 border-dashed border-white/10 hover:border-[#D4AF37]/50 rounded-2xl p-4 text-center cursor-pointer transition-all bg-black/20"
                    >
                      <div className="text-xs font-semibold text-zinc-300">
                        SVG Çerçeve veya Mermer/Ahşap Dokulu Görsel Yükleyin
                      </div>
                      <div className="text-[10px] text-zinc-500 mt-1">
                        SVG, PNG, WebP formatları desteklenir (Önerilen: 800x800 veya 800x1200)
                      </div>
                    </div>
                  )}

                  {/* Renk Paleti */}
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 pt-2">
                    <div className="space-y-1.5">
                      <label className="text-xs text-zinc-400 font-medium">Plaket / Kart Rengi</label>
                      <div className="flex items-center gap-2">
                        <input
                          type="color"
                          value={currentTemplate.plaqueColor || "#132034"}
                          onChange={(e) => updateCurrent({ plaqueColor: e.target.value })}
                          className="w-8 h-8 rounded-lg bg-transparent border-0 cursor-pointer"
                        />
                        <input
                          type="text"
                          value={currentTemplate.plaqueColor || "#132034"}
                          onChange={(e) => updateCurrent({ plaqueColor: e.target.value })}
                          className="flex-1 bg-black/40 border border-white/10 rounded-xl px-2.5 py-1.5 text-xs text-white font-mono"
                        />
                      </div>
                    </div>

                    <div className="space-y-1.5">
                      <label className="text-xs text-zinc-400 font-medium">Vurgu Kenarlık Rengi</label>
                      <div className="flex items-center gap-2">
                        <input
                          type="color"
                          value={currentTemplate.borderAccent || "#D4AF37"}
                          onChange={(e) => updateCurrent({ borderAccent: e.target.value })}
                          className="w-8 h-8 rounded-lg bg-transparent border-0 cursor-pointer"
                        />
                        <input
                          type="text"
                          value={currentTemplate.borderAccent || "#D4AF37"}
                          onChange={(e) => updateCurrent({ borderAccent: e.target.value })}
                          className="flex-1 bg-black/40 border border-white/10 rounded-xl px-2.5 py-1.5 text-xs text-white font-mono"
                        />
                      </div>
                    </div>

                    <div className="space-y-1.5">
                      <label className="text-xs text-zinc-400 font-medium">Restoran Adı Vurgu Rengi</label>
                      <div className="flex items-center gap-2">
                        <input
                          type="color"
                          value={currentTemplate.accentText || "#D4AF37"}
                          onChange={(e) => handleAccentTextColorChange(e.target.value)}
                          className="w-8 h-8 rounded-lg bg-transparent border-0 cursor-pointer"
                        />
                        <input
                          type="text"
                          value={currentTemplate.accentText || "#D4AF37"}
                          onChange={(e) => handleAccentTextColorChange(e.target.value)}
                          className="flex-1 bg-black/40 border border-white/10 rounded-xl px-2.5 py-1.5 text-xs text-white font-mono"
                        />
                      </div>
                    </div>
                  </div>
                </div>

                {/* 3. TİPOGRAFİ & GOOGLE FONTS & YAZI RENKLERİ STÜDYOSU */}
                <div className="space-y-4 pt-4 border-t border-white/5">
                  <div className="flex items-center justify-between">
                    <div className="text-xs font-bold text-[#D4AF37] uppercase tracking-wider flex items-center gap-2">
                      <svg className="w-4 h-4 text-[#D4AF37]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
                      </svg>
                      3. Tipografi, Renk & Google Fonts Stüdyosu
                    </div>
                    <span className="text-[10px] text-zinc-400">
                      Kütüphane: <strong className="text-white">Google Fonts</strong>
                    </span>
                  </div>

                  {/* Düzenlenecek Metin Katmanı Seçimi */}
                  <div className="space-y-2">
                    <label className="text-xs text-zinc-400 font-medium">Düzenlenecek Metin Katmanı:</label>
                    <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
                      {(currentTemplate.layers || []).map((layerObj) => {
                        const isSelected = selectedCanvasElement === layerObj.id;
                        let layerLabel = layerObj.text || layerObj.id;
                        if (layerObj.id === "rName") layerLabel = "Restoran Adı";
                        if (layerObj.id === "sub") layerLabel = "Alt Başlık";
                        if (layerObj.id === "cta") layerLabel = "Yönlendirme";
                        if (layerObj.id === "table") layerLabel = "Masa No / Wifi";

                        return (
                          <button
                            key={layerObj.id}
                            type="button"
                            onClick={() => setSelectedCanvasElement(layerObj.id)}
                            className={`py-2 px-3 rounded-xl text-xs font-bold transition-all border flex items-center justify-between gap-1.5 ${
                              isSelected
                                ? "bg-[#D4AF37] text-black border-[#D4AF37] shadow-sm"
                                : "bg-black/40 text-zinc-300 border-white/10 hover:bg-white/5"
                            }`}
                          >
                            <span className="truncate">{layerLabel}</span>
                            <span
                              className="w-2.5 h-2.5 rounded-full border border-black/30 shrink-0"
                              style={{ backgroundColor: layerObj.color || "#FFFFFF" }}
                            />
                          </button>
                        );
                      })}
                    </div>
                  </div>

                  {/* Seçili Katmanın Font, Renk ve Metin İçeriği Ayarları */}
                  {activeEditingLayer && (
                    <div className="p-4 bg-black/40 rounded-2xl border border-white/10 space-y-4">
                      <div className="flex items-center justify-between border-b border-white/5 pb-2">
                        <span className="text-xs font-bold text-white flex items-center gap-2">
                          <span
                            className="w-3 h-3 rounded-full border border-white/20 inline-block"
                            style={{ backgroundColor: activeEditingLayer.color || "#FFFFFF" }}
                          />
                          Katman: {activeEditingLayer.id === "rName" ? "Restoran Adı" : activeEditingLayer.id === "sub" ? "Alt Başlık" : activeEditingLayer.id === "cta" ? "Yönlendirme (CTA)" : activeEditingLayer.id === "table" ? "Masa No" : activeEditingLayer.id}
                        </span>
                        <span className="text-[11px] font-mono text-[#D4AF37]">
                          Renk: <strong className="text-white">{activeEditingLayer.color || "#FFFFFF"}</strong>
                        </span>
                      </div>

                      {/* Metin İçeriği (Yazı) Girişi */}
                      <div className="space-y-1">
                        <label className="text-[11px] text-[#D4AF37] font-bold uppercase tracking-wider block">
                          ✏️ Metin İçeriği (Yazı)
                        </label>
                        <input
                          type="text"
                          value={activeEditingLayer.text || ""}
                          onChange={(e) => handleLayerTextChange(activeEditingLayer.id, e.target.value)}
                          placeholder="Metin yazın..."
                          className="w-full bg-black/80 border border-[#D4AF37]/40 rounded-xl px-3.5 py-2.5 text-xs font-semibold text-white focus:border-[#D4AF37] focus:ring-1 focus:ring-[#D4AF37] outline-none transition-all"
                        />
                      </div>

                      {/* Hızlı Renk Seçimi Paleti */}
                      <div className="space-y-2">
                        <label className="text-[11px] text-zinc-400 font-medium">Bu Metin İçin Renk Paleti:</label>
                        <div className="flex items-center gap-2 flex-wrap">
                          {QUICK_COLOR_PALETTES.map((palette) => {
                            const isSelectedColor = (activeEditingLayer.color || "").toUpperCase() === palette.value.toUpperCase();
                            return (
                              <button
                                key={palette.value}
                                type="button"
                                onClick={() => handleLayerColorChange(activeEditingLayer.id, palette.value)}
                                className={`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-bold border transition-all ${
                                  isSelectedColor
                                    ? "bg-white/20 border-white text-white shadow-sm"
                                    : "bg-white/5 border-white/10 text-zinc-300 hover:bg-white/10"
                                }`}
                              >
                                <span
                                  className="w-3 h-3 rounded-full border border-black/40"
                                  style={{ backgroundColor: palette.value }}
                                />
                                {palette.name}
                              </button>
                            );
                          })}
                        </div>
                      </div>

                      {/* Özel Renk Seçici (Color Picker & Hex Input) */}
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2 border-t border-white/5">
                        <div className="space-y-1">
                          <label className="text-[11px] text-zinc-400 font-medium">Özel Renk Seç (Color Picker / Hex)</label>
                          <div className="flex items-center gap-2">
                            <input
                              type="color"
                              value={activeEditingLayer.color || "#FFFFFF"}
                              onChange={(e) => handleLayerColorChange(activeEditingLayer.id, e.target.value)}
                              className="w-8 h-8 rounded-lg bg-transparent border-0 cursor-pointer shrink-0"
                            />
                            <input
                              type="text"
                              value={activeEditingLayer.color || "#FFFFFF"}
                              onChange={(e) => handleLayerColorChange(activeEditingLayer.id, e.target.value)}
                              placeholder="#FFFFFF"
                              className="flex-1 bg-black/60 border border-white/10 rounded-xl px-2.5 py-1.5 text-xs text-white font-mono"
                            />
                          </div>
                        </div>

                        <div className="space-y-1">
                          <label className="text-[11px] text-zinc-400 font-medium">Font Boyutu (px)</label>
                          <input
                            type="number"
                            value={activeEditingLayer.fontSize || 16}
                            onChange={(e) => {
                              const updated = (currentTemplate.layers || []).map((l) =>
                                l.id === activeEditingLayer.id
                                  ? { ...l, fontSize: Number(e.target.value) }
                                  : l
                              );
                              updateCurrent({ layers: updated });
                            }}
                            className="w-full bg-black/60 border border-white/10 rounded-xl px-2.5 py-1.5 text-xs text-white font-mono"
                          />
                        </div>
                      </div>

                      {/* Hızlı Popüler Font Seçimi */}
                      <div className="space-y-2 pt-2 border-t border-white/5">
                        <label className="text-[11px] text-zinc-400 font-medium">Öne Çıkan Google Fontları:</label>
                        <div className="flex flex-wrap gap-1.5 max-h-36 overflow-y-auto pr-1">
                          {POPULAR_GOOGLE_FONTS.map((font) => {
                            const isCurrent = (activeEditingLayer.fontFamily || "").includes(font.name);
                            return (
                              <button
                                key={font.name}
                                type="button"
                                onClick={() => {
                                  const updated = (currentTemplate.layers || []).map((l) =>
                                    l.id === activeEditingLayer.id
                                      ? { ...l, fontFamily: font.family }
                                      : l
                                  );
                                  updateCurrent({ layers: updated });
                                }}
                                style={{ fontFamily: font.family }}
                                className={`px-2.5 py-1.5 rounded-lg text-xs transition-all border ${
                                  isCurrent
                                    ? "bg-[#D4AF37] text-black border-[#D4AF37] font-bold"
                                    : "bg-white/5 text-zinc-300 border-white/10 hover:bg-white/10 hover:text-white"
                                }`}
                              >
                                {font.name}
                              </button>
                            );
                          })}
                        </div>
                      </div>

                      {/* Özel Google Font Arama / Ekleme Kutusu */}
                      <div className="space-y-1.5 pt-2 border-t border-white/5">
                        <label className="text-[11px] text-zinc-400 font-medium flex items-center justify-between">
                          <span>Google Fonts'tan İstediğiniz Fontu Yazın:</span>
                          <a
                            href="https://fonts.google.com"
                            target="_blank"
                            rel="noreferrer"
                            className="text-[#D4AF37] hover:underline"
                          >
                            fonts.google.com &rarr;
                          </a>
                        </label>
                        <div className="flex items-center gap-2">
                          <input
                            type="text"
                            placeholder="Örn: Cinzel Decorative, Ephesis, Syne, Bebas Neue..."
                            value={customFontInput}
                            onChange={(e) => setCustomFontInput(e.target.value)}
                            onKeyDown={(e) => {
                              if (e.key === "Enter") {
                                e.preventDefault();
                                handleAddCustomGoogleFont();
                              }
                            }}
                            className="flex-1 bg-black/60 border border-white/10 rounded-xl px-3 py-2 text-xs text-white placeholder-zinc-500 focus:border-[#D4AF37] outline-none"
                          />
                          <button
                            type="button"
                            onClick={handleAddCustomGoogleFont}
                            className="px-4 py-2 rounded-xl bg-[#D4AF37] text-black font-bold text-xs hover:opacity-90 transition-all shrink-0"
                          >
                            Fontu Uygula
                          </button>
                        </div>
                      </div>

                      {/* Kalınlık ve Harf Boşluğu */}
                      <div className="grid grid-cols-2 gap-3 pt-2">
                        <div className="space-y-1">
                          <label className="text-[11px] text-zinc-400 font-medium">Kalınlık</label>
                          <select
                            value={activeEditingLayer.fontWeight || "800"}
                            onChange={(e) => {
                              const updated = (currentTemplate.layers || []).map((l) =>
                                l.id === activeEditingLayer.id
                                  ? { ...l, fontWeight: e.target.value }
                                  : l
                              );
                              updateCurrent({ layers: updated });
                            }}
                            className="w-full bg-black/60 border border-white/10 rounded-xl px-2 py-1.5 text-xs text-white focus:border-[#D4AF37] outline-none"
                          >
                            <option value="normal">Normal (400)</option>
                            <option value="600">Yarı Kalın (600)</option>
                            <option value="700">Kalın (700)</option>
                            <option value="800">Ekstra Kalın (800)</option>
                            <option value="900">Siyah (900)</option>
                          </select>
                        </div>

                        <div className="space-y-1">
                          <label className="text-[11px] text-zinc-400 font-medium">Harf Boşluğu (px)</label>
                          <input
                            type="number"
                            value={activeEditingLayer.letterSpacing ?? 1}
                            onChange={(e) => {
                              const updated = (currentTemplate.layers || []).map((l) =>
                                l.id === activeEditingLayer.id
                                  ? { ...l, letterSpacing: Number(e.target.value) }
                                  : l
                              );
                              updateCurrent({ layers: updated });
                            }}
                            className="w-full bg-black/60 border border-white/10 rounded-xl px-2.5 py-1.5 text-xs text-white font-mono"
                          />
                        </div>

                        <div className="space-y-1 sm:col-span-2">
                          <label className="text-[11px] text-zinc-400 font-medium flex items-center justify-between">
                            <span>Yazı Kavis / Eğrilik (Arc Text)</span>
                            <span className="text-[#D4AF37] font-bold">{activeEditingLayer.curveDegree || 0}°</span>
                          </label>
                          <div className="flex items-center gap-2">
                            <input
                              type="range"
                              min="-100"
                              max="100"
                              step="5"
                              value={activeEditingLayer.curveDegree || 0}
                              onChange={(e) => {
                                const updated = (currentTemplate.layers || []).map((l) =>
                                  l.id === activeEditingLayer.id
                                    ? { ...l, curveDegree: Number(e.target.value) }
                                    : l
                                );
                                updateCurrent({ layers: updated });
                              }}
                              className="w-full accent-[#D4AF37] cursor-pointer"
                            />
                          </div>
                          <div className="flex items-center gap-1.5 pt-1">
                            {[
                              { label: "Düz (0°)", deg: 0 },
                              { label: "Hafif ◠ (35°)", deg: 35 },
                              { label: "Belirgin ◠ (55°)", deg: 55 },
                              { label: "Ters ◡ (-35°)", deg: -35 },
                            ].map((btn) => (
                              <button
                                key={btn.deg}
                                type="button"
                                onClick={() => {
                                  const updated = (currentTemplate.layers || []).map((l) =>
                                    l.id === activeEditingLayer.id
                                      ? { ...l, curveDegree: btn.deg }
                                      : l
                                  );
                                  updateCurrent({ layers: updated });
                                }}
                                className={`px-2 py-0.5 rounded text-[10px] font-bold border transition-all ${
                                  (activeEditingLayer.curveDegree || 0) === btn.deg
                                    ? "bg-[#D4AF37] text-black border-[#D4AF37]"
                                    : "bg-white/5 text-zinc-400 border-white/10 hover:bg-white/10"
                                }`}
                              >
                                {btn.label}
                              </button>
                            ))}
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                </div>

                {/* 4. QR Kod Boyut & Konum Ayarı */}
                <div className="space-y-4 pt-4 border-t border-white/5">
                  <div className="text-xs font-bold text-[#D4AF37] uppercase tracking-wider flex items-center justify-between">
                    <span>4. Varsayılan QR Kod & Çerçeve Konfigürasyonu</span>
                    <span className="text-[10px] text-zinc-500 font-normal">
                      (Sağdaki tuvalden mouse ile de sürükleyebilirsiniz)
                    </span>
                  </div>
                  <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                    <div className="space-y-1">
                      <label className="text-[11px] text-zinc-400 font-medium">QR Boyut (px)</label>
                      <input
                        type="number"
                        value={currentTemplate.qrConfig?.size || 115}
                        onChange={(e) =>
                          updateCurrent({
                            qrConfig: { ...currentTemplate.qrConfig, size: Number(e.target.value) },
                          })
                        }
                        className="w-full bg-black/40 border border-white/10 rounded-xl px-3 py-2 text-xs text-white font-mono"
                      />
                    </div>

                    <div className="space-y-1">
                      <label className="text-[11px] text-zinc-400 font-medium">X Konumu (%)</label>
                      <input
                        type="number"
                        value={currentTemplate.qrConfig?.xPercent || 50}
                        onChange={(e) =>
                          updateCurrent({
                            qrConfig: { ...currentTemplate.qrConfig, xPercent: Number(e.target.value) },
                          })
                        }
                        className="w-full bg-black/40 border border-white/10 rounded-xl px-3 py-2 text-xs text-white font-mono"
                      />
                    </div>

                    <div className="space-y-1">
                      <label className="text-[11px] text-zinc-400 font-medium">Y Konumu (%)</label>
                      <input
                        type="number"
                        value={currentTemplate.qrConfig?.yPercent || 38}
                        onChange={(e) =>
                          updateCurrent({
                            qrConfig: { ...currentTemplate.qrConfig, yPercent: Number(e.target.value) },
                          })
                        }
                        className="w-full bg-black/40 border border-white/10 rounded-xl px-3 py-2 text-xs text-white font-mono"
                      />
                    </div>

                    <div className="space-y-1">
                      <label className="text-[11px] text-zinc-400 font-medium">Köşe Yuvarlaklığı</label>
                      <input
                        type="number"
                        value={currentTemplate.qrConfig?.borderRadius || 14}
                        onChange={(e) =>
                          updateCurrent({
                            qrConfig: { ...currentTemplate.qrConfig, borderRadius: Number(e.target.value) },
                          })
                        }
                        className="w-full bg-black/40 border border-white/10 rounded-xl px-3 py-2 text-xs text-white font-mono"
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-3 pt-2">
                    <div className="space-y-1">
                      <label className="text-[11px] text-zinc-400 font-medium">Kenarlık / Çerçeve Rengi</label>
                      <input
                        type="text"
                        value={currentTemplate.qrConfig?.borderColor || "#D4AF37"}
                        onChange={(e) =>
                          updateCurrent({
                            qrConfig: { ...currentTemplate.qrConfig, borderColor: e.target.value },
                          })
                        }
                        className="w-full bg-black/40 border border-white/10 rounded-xl px-3 py-2 text-xs text-white font-mono"
                      />
                    </div>

                    <div className="space-y-1">
                      <label className="text-[11px] text-zinc-400 font-medium">Kutu Arka Plan Rengi</label>
                      <input
                        type="text"
                        value={currentTemplate.qrConfig?.bgBoxColor || "#FFFFFF"}
                        onChange={(e) =>
                          updateCurrent({
                            qrConfig: { ...currentTemplate.qrConfig, bgBoxColor: e.target.value },
                          })
                        }
                        className="w-full bg-black/40 border border-white/10 rounded-xl px-3 py-2 text-xs text-white font-mono"
                      />
                    </div>
                  </div>
                </div>

                {/* Kaydet Butonu */}
                <div className="pt-4 border-t border-white/10 flex items-center justify-between">
                  <span className="text-xs text-zinc-400">
                    Kaydedilen şablon, renkler ve fontlar anında API ve mobilde yayına girer.
                  </span>
                  <button
                    onClick={handleSaveAndPublish}
                    disabled={isSaving}
                    className="px-6 py-2.5 rounded-xl bg-[#D4AF37] text-black font-extrabold text-xs shadow-lg shadow-[#D4AF37]/20 hover:opacity-90 transition-all flex items-center gap-2"
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.5" d="M5 13l4 4L19 7" />
                    </svg>
                    {isSaving ? "Yayınlanıyor..." : "Kaydet ve Yayına Al"}
                  </button>
                </div>
              </div>
            )}

            {/* Sekme 2: Ham JSON Editörü */}
            {activeTab === "json" && (
              <div className="p-6 space-y-4">
                <div className="text-xs text-zinc-400">
                  Bu şablonun tüm JSON spesifikasyonunu buradan doğrudan düzenleyebilirsiniz:
                </div>
                <textarea
                  rows={16}
                  value={JSON.stringify(currentTemplate, null, 2)}
                  onChange={(e) => {
                    try {
                      const updated = JSON.parse(e.target.value);
                      updateCurrent(updated);
                    } catch {}
                  }}
                  className="w-full bg-black/60 border border-white/10 rounded-xl p-4 text-xs text-emerald-400 font-mono focus:border-[#D4AF37] outline-none"
                />
                <button
                  onClick={handleSaveAndPublish}
                  className="px-5 py-2 rounded-xl bg-[#D4AF37] text-black font-bold text-xs"
                >
                  JSON Değişikliklerini Uygula ve Yayınla
                </button>
              </div>
            )}
          </div>
        </div>

        {/* SAĞ: CANLI MASA KARTI SİMÜLATÖRÜ & MOUSE DRAG KANVASI (5 KOLON) */}
        <div className="xl:col-span-5 space-y-4 sticky top-6">
          <div className="bg-[#121215] p-5 rounded-2xl border border-white/10 space-y-4">
            <div className="flex items-center justify-between">
              <div className="text-xs font-bold text-[#D4AF37] uppercase tracking-wider flex items-center gap-2">
                <span className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse" />
                İnteraktif Canlı Tuval & Önizleme
              </div>
              <div className="text-[11px] text-zinc-500 font-mono">{currentTemplate.aspectRatio || "1/1"}</div>
            </div>

            {/* Test Restoranı Adı Kutusu */}
            <div className="space-y-1">
              <label className="text-[11px] text-zinc-400">Önizleme Restoran Adı:</label>
              <input
                type="text"
                value={testRestaurantName}
                onChange={(e) => setTestRestaurantName(e.target.value)}
                className="w-full bg-black/40 border border-white/10 rounded-xl px-3 py-1.5 text-xs text-white font-bold"
              />
            </div>

            {/* Bilgilendirme Rozeti */}
            <div className="flex items-center justify-between text-[11px] bg-white/[0.03] px-3 py-1.5 rounded-lg border border-white/5 text-zinc-400">
              <span>💡 Yazılara veya QR koduna tıklayıp sürükleyebilirsiniz</span>
              <span className="font-mono text-[#D4AF37] font-bold">
                X: {currentTemplate.qrConfig?.xPercent || 50}% | Y: {currentTemplate.qrConfig?.yPercent || 38}%
              </span>
            </div>

            {/* İNTERAKTİF MOUSE SÜRÜKLE-BIRAK STAND TUVALİ */}
            <div
              className="flex justify-center items-center py-4 bg-black/40 rounded-2xl border border-white/5 overflow-hidden"
              onMouseMove={handleCanvasMouseMove}
              onMouseUp={handleCanvasMouseUp}
              onMouseLeave={handleCanvasMouseUp}
            >
              <div
                ref={canvasContainerRef}
                style={{
                  width: previewWidth,
                  height: previewHeight,
                  background: currentTemplate.bgImageUrl
                    ? undefined
                    : currentTemplate.bgGradient || currentTemplate.plaqueColor || "#132034",
                  borderRadius: 20,
                  border: `2px solid ${currentTemplate.borderAccent || "#D4AF37"}`,
                  position: "relative",
                  boxShadow: "0 20px 40px -15px rgba(0,0,0,0.8)",
                  overflow: "hidden",
                }}
                className="select-none relative"
              >
                {/* Varsa Arka Plan Görseli / SVG */}
                {currentTemplate.bgImageUrl && (
                  <img
                    src={currentTemplate.bgImageUrl}
                    alt="Stand Arka Planı"
                    className="absolute inset-0 w-full h-full object-cover pointer-events-none z-0"
                    draggable={false}
                  />
                )}

                {/* 1. Restoran Adı (Mouse ile Sürüklenebilir) */}
                {(() => {
                  const rLayer = currentTemplate.layers?.find((l) => l.id === "rName");
                  const textColor = rLayer?.color || currentTemplate.accentText || "#D4AF37";
                  return (
                    <div
                      onMouseDown={() => {
                        setActiveDragItem({ type: "layer", id: "rName" });
                        setSelectedCanvasElement("rName");
                      }}
                      style={{
                        position: "absolute",
                        top: `${rLayer?.yPercent || 16}%`,
                        left: "50%",
                        transform: "translate(-50%, -50%)",
                        fontFamily: rLayer?.fontFamily || "'Playfair Display', serif",
                        color: textColor,
                        fontSize: rLayer?.fontSize || 16,
                        fontWeight: (rLayer?.fontWeight as any) || "800",
                        letterSpacing: `${rLayer?.letterSpacing ?? 2}px`,
                        textTransform: "uppercase",
                        cursor: activeDragItem?.id === "rName" ? "grabbing" : "grab",
                        zIndex: 20,
                      }}
                      className={`text-center px-2 py-0.5 rounded transition-all whitespace-nowrap ${
                        selectedCanvasElement === "rName"
                          ? "ring-1 ring-[#D4AF37] bg-black/40"
                          : "hover:ring-1 hover:ring-white/20"
                      }`}
                    >
                      {rLayer?.curveDegree && rLayer.curveDegree !== 0 ? (
                        <CurvedTextWeb
                          text={testRestaurantName}
                          fontSize={rLayer?.fontSize || 16}
                          color={textColor}
                          fontFamily={rLayer?.fontFamily || "'Playfair Display', serif"}
                          fontWeight={(rLayer?.fontWeight as any) || "800"}
                          letterSpacing={rLayer?.letterSpacing ?? 2}
                          curveDegree={rLayer.curveDegree}
                        />
                      ) : (
                        testRestaurantName
                      )}
                    </div>
                  );
                })()}

                {/* 2. Alt Başlık (Mouse ile Sürüklenebilir) */}
                {(() => {
                  const subLayer = currentTemplate.layers?.find((l) => l.id === "sub");
                  const textColor = subLayer?.color || currentTemplate.subText || "#E5C378";
                  return (
                    <div
                      onMouseDown={() => {
                        setActiveDragItem({ type: "layer", id: "sub" });
                        setSelectedCanvasElement("sub");
                      }}
                      style={{
                        position: "absolute",
                        top: `${subLayer?.yPercent || 26}%`,
                        left: "50%",
                        transform: "translate(-50%, -50%)",
                        fontFamily: subLayer?.fontFamily || "'Plus Jakarta Sans', sans-serif",
                        color: textColor,
                        fontSize: subLayer?.fontSize || 9,
                        fontWeight: (subLayer?.fontWeight as any) || "600",
                        letterSpacing: `${subLayer?.letterSpacing ?? 1.5}px`,
                        cursor: activeDragItem?.id === "sub" ? "grabbing" : "grab",
                        zIndex: 20,
                      }}
                      className={`text-center px-2 py-0.5 rounded transition-all whitespace-nowrap ${
                        selectedCanvasElement === "sub"
                          ? "ring-1 ring-[#D4AF37] bg-black/40"
                          : "hover:ring-1 hover:ring-white/20"
                      }`}
                    >
                      {subLayer?.curveDegree && subLayer.curveDegree !== 0 ? (
                        <CurvedTextWeb
                          text="RESTAURANT & BAR"
                          fontSize={subLayer?.fontSize || 9}
                          color={textColor}
                          fontFamily={subLayer?.fontFamily || "'Plus Jakarta Sans', sans-serif"}
                          fontWeight={(subLayer?.fontWeight as any) || "600"}
                          letterSpacing={subLayer?.letterSpacing ?? 1.5}
                          curveDegree={subLayer.curveDegree}
                        />
                      ) : (
                        "RESTAURANT & BAR"
                      )}
                    </div>
                  );
                })()}

                {/* 3. İNTERAKTİF SÜRÜKLENEBİLİR QR KOD ALANI */}
                <div
                  onMouseDown={() => {
                    setActiveDragItem({ type: "qr" });
                    setSelectedCanvasElement("qr");
                  }}
                  style={{
                    position: "absolute",
                    left: `${currentTemplate.qrConfig?.xPercent || 50}%`,
                    top: `${currentTemplate.qrConfig?.yPercent || 38}%`,
                    transform: "translate(-50%, -50%)",
                    padding: 8,
                    backgroundColor: currentTemplate.qrConfig?.bgBoxColor || "#FFFFFF",
                    borderRadius: currentTemplate.qrConfig?.borderRadius || 14,
                    border: `2px solid ${currentTemplate.qrConfig?.borderColor || currentTemplate.borderAccent || "#D4AF37"}`,
                    boxShadow: "0 8px 16px rgba(0,0,0,0.4)",
                    cursor: activeDragItem?.type === "qr" ? "grabbing" : "grab",
                    zIndex: 30,
                  }}
                  className={`flex items-center justify-center transition-all ${
                    selectedCanvasElement === "qr"
                      ? "ring-2 ring-[#D4AF37] ring-offset-2 ring-offset-black"
                      : "hover:ring-1 hover:ring-white/40"
                  }`}
                >
                  <QRCodeSVG
                    value="https://menul.io/demo"
                    size={Math.min(130, currentTemplate.qrConfig?.size || 115)}
                    level="M"
                    fgColor="#0C0C0E"
                    bgColor="#FFFFFF"
                  />

                  <div className="absolute -top-2 -right-2 bg-[#D4AF37] text-black w-4 h-4 rounded-full flex items-center justify-center text-[8px] font-bold shadow">
                    ✥
                  </div>
                </div>

                {/* 4. Yönlendirme Metni (Mouse ile Sürüklenebilir) */}
                {(() => {
                  const ctaLayer = currentTemplate.layers?.find((l) => l.id === "cta");
                  const textColor = ctaLayer?.color || currentTemplate.headerText || "#FFFFFF";
                  return (
                    <div
                      onMouseDown={() => {
                        setActiveDragItem({ type: "layer", id: "cta" });
                        setSelectedCanvasElement("cta");
                      }}
                      style={{
                        position: "absolute",
                        top: `${ctaLayer?.yPercent || 80}%`,
                        left: "50%",
                        transform: "translate(-50%, -50%)",
                        fontFamily: ctaLayer?.fontFamily || "'Playfair Display', serif",
                        color: textColor,
                        fontSize: ctaLayer?.fontSize || 10,
                        fontWeight: (ctaLayer?.fontWeight as any) || "700",
                        letterSpacing: `${ctaLayer?.letterSpacing ?? 1}px`,
                        cursor: activeDragItem?.id === "cta" ? "grabbing" : "grab",
                        zIndex: 20,
                      }}
                      className={`text-center px-2 py-0.5 rounded transition-all whitespace-nowrap ${
                        selectedCanvasElement === "cta"
                          ? "ring-1 ring-[#D4AF37] bg-black/40"
                          : "hover:ring-1 hover:ring-white/20"
                      }`}
                    >
                      {ctaLayer?.curveDegree && ctaLayer.curveDegree !== 0 ? (
                        <CurvedTextWeb
                          text="MENÜYÜ GÖRMEK İÇİN OKUTUN"
                          fontSize={ctaLayer?.fontSize || 10}
                          color={textColor}
                          fontFamily={ctaLayer?.fontFamily || "'Playfair Display', serif"}
                          fontWeight={(ctaLayer?.fontWeight as any) || "700"}
                          letterSpacing={ctaLayer?.letterSpacing ?? 1}
                          curveDegree={ctaLayer.curveDegree}
                        />
                      ) : (
                        "MENÜYÜ GÖRMEK İÇİN OKUTUN"
                      )}
                    </div>
                  );
                })()}

                {/* 5. Masa No & Wifi Metni (Mouse ile Sürüklenebilir) */}
                {(() => {
                  const tableLayer = currentTemplate.layers?.find((l) => l.id === "table");
                  const textColor = tableLayer?.color || currentTemplate.subText || "#A1A1AA";
                  return (
                    <div
                      onMouseDown={() => {
                        setActiveDragItem({ type: "layer", id: "table" });
                        setSelectedCanvasElement("table");
                      }}
                      style={{
                        position: "absolute",
                        top: `${tableLayer?.yPercent || 90}%`,
                        left: "50%",
                        transform: "translate(-50%, -50%)",
                        fontFamily: tableLayer?.fontFamily || "'Plus Jakarta Sans', sans-serif",
                        color: textColor,
                        fontSize: tableLayer?.fontSize || 8.5,
                        fontWeight: (tableLayer?.fontWeight as any) || "600",
                        cursor: activeDragItem?.id === "table" ? "grabbing" : "grab",
                        zIndex: 20,
                      }}
                      className={`text-center px-2 py-0.5 rounded transition-all whitespace-nowrap ${
                        selectedCanvasElement === "table"
                          ? "ring-1 ring-[#D4AF37] bg-black/40"
                          : "hover:ring-1 hover:ring-white/20"
                      }`}
                    >
                      {tableLayer?.curveDegree && tableLayer.curveDegree !== 0 ? (
                        <CurvedTextWeb
                          text="MASA NO: 01 • WIFI: Bistro"
                          fontSize={tableLayer?.fontSize || 8.5}
                          color={textColor}
                          fontFamily={tableLayer?.fontFamily || "'Plus Jakarta Sans', sans-serif"}
                          fontWeight={(tableLayer?.fontWeight as any) || "600"}
                          letterSpacing={tableLayer?.letterSpacing ?? 0.5}
                          curveDegree={tableLayer.curveDegree}
                        />
                      ) : (
                        "MASA NO: 01 • WIFI: Bistro"
                      )}
                    </div>
                  );
                })()}

                {/* Köşe Süsleme Çerçevesi */}
                <div
                  style={{
                    position: "absolute",
                    inset: 8,
                    border: `1px solid ${currentTemplate.dividerColor || "rgba(212, 175, 55, 0.25)"}`,
                    borderRadius: 14,
                    pointerEvents: "none",
                  }}
                />
              </div>
            </div>

            {/* Hızlı Kaydet Butonu */}
            <button
              onClick={handleSaveAndPublish}
              disabled={isSaving}
              className="w-full py-2.5 rounded-xl bg-[#D4AF37] text-black font-extrabold text-xs shadow-lg shadow-[#D4AF37]/20 hover:opacity-90 transition-all flex items-center justify-center gap-2"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.5" d="M5 13l4 4L19 7" />
              </svg>
              {isSaving ? "Yayınlanıyor..." : "Masa Kartını, Renkleri ve Fontları Kaydet"}
            </button>
          </div>
        </div>
      </div>

      {/* JSON İçe Aktarma Modalı */}
      {jsonModalOpen && (
        <div className="fixed inset-0 z-50 bg-black/80 backdrop-blur-sm flex items-center justify-center p-4">
          <div className="bg-[#18181B] border border-white/10 rounded-2xl w-full max-w-xl p-6 space-y-4 shadow-2xl">
            <div className="flex items-center justify-between">
              <h3 className="text-base font-bold text-white">JSON Şablonu İçe Aktar</h3>
              <button
                onClick={() => setJsonModalOpen(false)}
                className="text-zinc-400 hover:text-white text-xs font-bold"
              >
                Kapat
              </button>
            </div>
            <p className="text-xs text-zinc-400">
              Figma veya diğer şablon tasarım araçlarından kopyaladığınız JSON şablon kodunu buraya yapıştırın:
            </p>
            <textarea
              rows={10}
              placeholder='{ "key": "qr-new", "name": "Lüks Mermer", "aspectRatio": "1/1", ... }'
              value={jsonInput}
              onChange={(e) => setJsonInput(e.target.value)}
              className="w-full bg-black/60 border border-white/10 rounded-xl p-3 text-xs text-emerald-400 font-mono focus:border-[#D4AF37] outline-none"
            />
            <div className="flex justify-end gap-2">
              <button
                onClick={() => setJsonModalOpen(false)}
                className="px-4 py-2 rounded-xl bg-white/5 text-zinc-400 text-xs font-semibold"
              >
                İptal
              </button>
              <button
                onClick={handleImportJson}
                className="px-5 py-2 rounded-xl bg-[#D4AF37] text-black font-extrabold text-xs"
              >
                Şablonu Yükle
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
