import { useEffect, useRef, useState } from "react";
import { router } from "expo-router";
import {
  ActivityIndicator,
  Alert,
  Image,
  Pressable,
  RefreshControl,
  ScrollView,
  Share,
  Text,
  View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Ionicons } from "@expo/vector-icons";
import * as Haptics from "expo-haptics";
import * as Clipboard from "expo-clipboard";
import * as Sharing from "expo-sharing";
import * as Print from "expo-print";
import { QR_STAND_PRESETS, type QrStandPreset } from "@menulio/shared";
import { supabase } from "@/lib/supabase";
import { api } from "@/lib/api";
import { getActiveRestaurant, type ActiveRestaurant } from "@/lib/active-restaurant";
import {
  COMPONENT_TEMPLATES,
  TEMPLATE_ASPECT_RATIOS,
  type QrCustomFields,
} from "@/components/qr-templates";
import {
  QrCanvasStudio,
  getDefaultLayersForTemplate,
  getDefaultQrConfigForTemplate,
  type CanvasTextLayer,
  type CanvasQrConfig,
} from "@/components/qr-canvas";

const HIDE_ALL_TEMPLATE_FIELDS: QrCustomFields = {
  restaurantName: { text: "", visible: false },
  subtitle: { text: "", visible: false },
  tableNo: { text: "", visible: false },
  ctaText: { text: "", visible: false },
  wifiText: { text: "", visible: false },
  socialText: { text: "", visible: false },
};

interface QrResponse {
  id: string;
  redirectUrl: string;
  targetUrl: string;
  pngBase64: string;
}

function getPresetAspectRatio(preset?: QrStandPreset | null): number {
  if (!preset) return 1;
  if (preset.aspectRatio) {
    const parts = preset.aspectRatio.split(/[/:]/).map(Number);
    if (parts[0] && parts[1]) {
      return parts[0] / parts[1];
    }
  }
  if (TEMPLATE_ASPECT_RATIOS[preset.key]) {
    return TEMPLATE_ASPECT_RATIOS[preset.key];
  }
  return 1;
}

export default function QrScreen() {
  const insets = useSafeAreaInsets();
  const [active, setActive] = useState<ActiveRestaurant | null>(null);
  const [restaurantName, setRestaurantName] = useState<string>("Gourmet Bistro");
  const [qr, setQr] = useState<QrResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);
  const [scrollEnabled, setScrollEnabled] = useState(true);

  // Dinamik Şablon Listesi (API'den ve yerelden)
  const [presets, setPresets] = useState<QrStandPreset[]>(() =>
    Object.values(QR_STAND_PRESETS)
  );

  const [selectedKey, setSelectedKey] = useState<string>(
    presets[0]?.key || "qr-1"
  );
  const [exportingPng, setExportingPng] = useState(false);
  const [exportingPdf, setExportingPdf] = useState(false);

  // Aktif Şablon ve Oran Hesaplama (Şablondaki Dinamik Aspect Ratio Öncelikli)
  const currentPreset = presets.find((p) => p.key === selectedKey) || presets[0];
  const aspectRatio = getPresetAspectRatio(currentPreset);
  const displayWidth = 290;
  const displayHeight = Math.round(displayWidth / aspectRatio);

  // Instagram Story / Canva Tarzı Katmanlar & QR Konfigürasyonu
  const [layers, setLayers] = useState<CanvasTextLayer[]>(() =>
    getDefaultLayersForTemplate("qr-1", "Gourmet Bistro")
  );
  const [qrConfig, setQrConfig] = useState<CanvasQrConfig>(() =>
    getDefaultQrConfigForTemplate("qr-1", 290, 290)
  );

  const [selectedLayerId, setSelectedLayerId] = useState<string | null>(null);
  const [isQrSelected, setIsQrSelected] = useState<boolean>(false);

  // Şablonlar Arasında Düzenlemeleri Koruyan Önbellek
  const templateCacheRef = useRef<
    Record<string, { layers: CanvasTextLayer[]; qrConfig: CanvasQrConfig }>
  >({});

  const handleLayersChange = (updater: React.SetStateAction<CanvasTextLayer[]>) => {
    setLayers((prev) => {
      const next = typeof updater === "function" ? updater(prev) : updater;
      templateCacheRef.current[selectedKey] = {
        layers: next,
        qrConfig: templateCacheRef.current[selectedKey]?.qrConfig || qrConfig,
      };
      return next;
    });
  };

  const handleQrConfigChange = (updater: React.SetStateAction<CanvasQrConfig>) => {
    setQrConfig((prev) => {
      const next = typeof updater === "function" ? updater(prev) : updater;
      templateCacheRef.current[selectedKey] = {
        layers: templateCacheRef.current[selectedKey]?.layers || layers,
        qrConfig: next,
      };
      return next;
    });
  };

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const viewShotRef = useRef<any>(null);

  const [refreshing, setRefreshing] = useState(false);
  const [syncing, setSyncing] = useState(false);

  // Şablon ve QR Verilerini Çek / Senkronize Et
  const fetchTemplatesAndQr = async (isManualRefresh = false) => {
    if (isManualRefresh) {
      setRefreshing(true);
      setSyncing(true);
      try { Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); } catch {}
    }

    try {
      // 1. Supabase ve API'den Dinamik Şablonları Çek
      let fetchedPresets: QrStandPreset[] = [];
      try {
        const { data: dbTemplates, error: dbErr } = await supabase
          .from("qr_stand_templates")
          .select("*")
          .eq("is_active", true)
          .order("created_at", { ascending: false });

        if (!dbErr && dbTemplates && dbTemplates.length > 0) {
          fetchedPresets = dbTemplates.map((row: any) => ({
            key: row.key,
            name: row.name,
            categoryName: row.category_name,
            svgTemplateUrl: row.svg_template_url || `/${row.key}.svg`,
            aspectRatio: row.aspect_ratio || "1/1",
            bgType: row.bg_type || "gradient",
            bgImageUrl: row.bg_image_url,
            bgGradient: row.bg_gradient,
            plaqueColor: row.plaque_color,
            borderAccent: row.border_accent,
            accentText: row.accent_text,
            headerText: row.header_text,
            subText: row.sub_text,
            dividerColor: row.divider_color,
            qrConfig: row.qr_config,
            layers: row.layers,
          }));
        } else {
          const tplData = await api.get<{ templates: QrStandPreset[] }>("/qr-templates");
          if (tplData?.templates && tplData.templates.length > 0) {
            fetchedPresets = tplData.templates;
          }
        }
      } catch {
        // fallback
      }

      let currentRestName = restaurantName;

      // 2. Aktif Restoran ve QR Verilerini Çek
      const activeRest = await getActiveRestaurant();
      if (activeRest) {
        setActive(activeRest);
        try {
          const qrData = await api.post<QrResponse>(`/restaurants/${activeRest.restaurantId}/qr`);
          setQr(qrData);

          const restDetail = await api.get<{ name?: string }>(`/restaurants/${activeRest.restaurantId}`);
          if (restDetail?.name) {
            currentRestName = restDetail.name;
            setRestaurantName(restDetail.name);
          }
        } catch {}
      }

      if (fetchedPresets.length > 0) {
        setPresets(fetchedPresets);

        // Eğer mevcut seçili şablon silinmişse ilk geçerli şablona geç
        let effectiveKey = selectedKey;
        const exists = fetchedPresets.some((p) => p.key === selectedKey);
        if (!exists) {
          effectiveKey = fetchedPresets[0].key;
          setSelectedKey(effectiveKey);
        }

        // Önbellekten silinen şablonları temizle
        const validKeys = new Set(fetchedPresets.map((p) => p.key));
        Object.keys(templateCacheRef.current).forEach((k) => {
          if (!validKeys.has(k)) {
            delete templateCacheRef.current[k];
          }
        });

        // Aktif seçili şablonu yeni verilerle güncelle
        const activeTpl = fetchedPresets.find((p) => p.key === effectiveKey) || fetchedPresets[0];
        if (activeTpl) {
          const pRatio = getPresetAspectRatio(activeTpl);
          const calcHeight = Math.round(displayWidth / (pRatio || 1));

          let newLayers: CanvasTextLayer[];
          if ((activeTpl as any).layers && (activeTpl as any).layers.length > 0) {
            newLayers = (activeTpl as any).layers.map((l: any) => ({
              id: l.id || `layer-${Math.random()}`,
              text: l.text === "{{RESTAURANT_NAME}}" ? currentRestName.toUpperCase() : l.text,
              x: l.x ?? (displayWidth - 200) / 2,
              y: l.y ?? Math.round((calcHeight * (l.yPercent || 15)) / 100),
              rotation: l.rotation || 0,
              fontSize: l.fontSize || 16,
              fontId: l.fontFamily ? l.fontFamily.split(",")[0].replace(/['"]/g, "").trim() : "serif",
              color: l.color || activeTpl.accentText || "#D4AF37",
              textAlign: l.textAlign || "center",
              bgStyle: l.bgStyle || "none",
              letterSpacing: l.letterSpacing || 1,
            }));
          } else {
            newLayers = getDefaultLayersForTemplate(activeTpl.key, currentRestName);
          }

          let newQr: CanvasQrConfig;
          if ((activeTpl as any).qrConfig) {
            const c = (activeTpl as any).qrConfig;
            newQr = {
              x: Math.round(((displayWidth - (c.size || 115)) * (c.xPercent || 50)) / 100),
              y: Math.round(((calcHeight - (c.size || 115)) * (c.yPercent || 38)) / 100),
              size: c.size || 115,
              borderRadius: c.borderRadius || 14,
              borderWidth: c.borderWidth || 2,
              borderColor: c.borderColor || activeTpl.borderAccent || "#D4AF37",
              padding: c.padding || 8,
              bgBoxColor: c.bgBoxColor || "#FFFFFF",
            };
          } else {
            newQr = getDefaultQrConfigForTemplate(activeTpl.key, displayWidth, calcHeight);
          }

          setLayers(newLayers);
          setQrConfig(newQr);

          // Önbelleği de taze veriyle güncelle
          templateCacheRef.current[activeTpl.key] = {
            layers: newLayers,
            qrConfig: newQr,
          };
        }
      }

      if (isManualRefresh) {
        try { Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success); } catch {}
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "QR yüklenemedi");
    } finally {
      setLoading(false);
      setRefreshing(false);
      setSyncing(false);
    }
  };

  useEffect(() => {
    fetchTemplatesAndQr(false);

    // Supabase Realtime Değişiklik Aboneliği (Admin kaydettiğinde anında güncelle)
    const channel = supabase
      .channel("public:qr_stand_templates")
      .on(
        "postgres_changes",
        { event: "*", schema: "public", table: "qr_stand_templates" },
        () => {
          fetchTemplatesAndQr(false);
        }
      )
      .subscribe();

    return () => {
      supabase.removeChannel(channel);
    };
  }, []);

  async function handleCopy() {
    if (!qr?.targetUrl) return;
    try {
      await Clipboard.setStringAsync(qr.targetUrl);
      Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
    } catch {}
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }

  async function handleShareQuick() {
    if (!qr?.targetUrl) return;
    try {
      Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
      await Share.share({
        title: "Dijital QR Menü",
        message: `${qr.targetUrl}\nMenümüzü incelemek için QR kodu taratın veya linke tıklayın.`,
        url: qr.targetUrl,
      });
    } catch {}
  }

  async function handleExportPng() {
    if (!viewShotRef.current) return;
    setSelectedLayerId(null);
    setIsQrSelected(false);
    setExportingPng(true);
    try {
      Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
      await new Promise((r) => setTimeout(r, 120));
      const uri = await viewShotRef.current.capture?.();
      if (uri) {
        await Sharing.shareAsync(uri, {
          mimeType: "image/png",
          dialogTitle: "Masa Stant QR Görselini Paylaş / Kaydet",
        });
      }
    } catch {
      Alert.alert("Hata", "Görsel oluşturulamadı.");
    } finally {
      setExportingPng(false);
    }
  }

  async function handleExportPdf() {
    if (!qr || !active || !viewShotRef.current) return;
    setSelectedLayerId(null);
    setIsQrSelected(false);
    setExportingPdf(true);
    try {
      Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Heavy);
      await new Promise((r) => setTimeout(r, 120));
      const pngUri = await viewShotRef.current?.capture();
      if (!pngUri) throw new Error("Görsel alınamadı");

      const htmlContent = `
        <!DOCTYPE html>
        <html>
        <head>
          <meta charset="utf-8"/>
          <style>
            @page { size: A5 portrait; margin: 0; }
            * { box-sizing: border-box; }
            body {
              margin: 0; padding: 0; width: 148mm; height: 210mm;
              display: flex; align-items: center; justify-content: center;
              background: #000000;
              -webkit-print-color-adjust: exact;
            }
            .img-wrap {
              width: 140mm;
              height: 200mm;
              display: flex;
              align-items: center;
              justify-content: center;
            }
            img {
              width: 100%;
              height: 100%;
              object-fit: contain;
            }
          </style>
        </head>
        <body>
          <div class="img-wrap">
            <img src="${pngUri}" />
          </div>
        </body>
        </html>
      `;

      const { uri } = await Print.printToFileAsync({
        html: htmlContent,
        width: 420,
        height: 595,
      });

      await Sharing.shareAsync(uri, {
        mimeType: "application/pdf",
        dialogTitle: "A5 Baskıya Hazır PDF İndir / Paylaş",
      });
    } catch {
      Alert.alert("Hata", "PDF oluşturulamadı.");
    } finally {
      setExportingPdf(false);
    }
  }

  if (loading) {
    return (
      <View style={{ flex: 1, backgroundColor: "#0C0C0E", alignItems: "center", justifyContent: "center" }}>
        <ActivityIndicator size="large" color="#D4AF37" />
        <Text style={{ marginTop: 14, color: "#A1A1AA", fontSize: 14, fontWeight: "600" }}>
          QR Stant Stüdyosu Hazırlanıyor...
        </Text>
      </View>
    );
  }

  if (error || !qr) {
    return (
      <View style={{ flex: 1, backgroundColor: "#0C0C0E", alignItems: "center", justifyContent: "center", padding: 24 }}>
        <Ionicons name="alert-circle-outline" size={48} color="#EF4444" style={{ marginBottom: 12 }} />
        <Text style={{ color: "#EF4444", fontSize: 16, fontWeight: "600", textAlign: "center" }}>
          {error ?? "QR kod yüklenemedi"}
        </Text>
        <Pressable
          onPress={() => router.back()}
          accessible={true}
          accessibilityRole="button"
          accessibilityLabel="Geri Dön"
          style={{ marginTop: 20, backgroundColor: "#242429", paddingHorizontal: 20, paddingVertical: 12, borderRadius: 10, minHeight: 44, justifyContent: "center" }}
        >
          <Text style={{ color: "#FFF", fontWeight: "600" }}>Geri Dön</Text>
        </Pressable>
      </View>
    );
  }

  return (
    <ScrollView
      scrollEnabled={scrollEnabled}
      refreshControl={
        <RefreshControl
          refreshing={refreshing}
          onRefresh={() => fetchTemplatesAndQr(true)}
          tintColor="#D4AF37"
          colors={["#D4AF37"]}
        />
      }
      contentContainerStyle={{
        flexGrow: 1,
        backgroundColor: "#0C0C0E",
        paddingTop: insets.top + 8,
        paddingBottom: insets.bottom + 40,
      }}
      keyboardShouldPersistTaps="handled"
      keyboardDismissMode="on-drag"
      showsVerticalScrollIndicator={false}
    >
      <View style={{ width: "100%", maxWidth: 440, alignSelf: "center", paddingHorizontal: 16 }}>
        {/* Üst Navigasyon & Başlık Çubuğu */}
        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "space-between",
            marginBottom: 12,
          }}
        >
          {/* Geri Dön Butonu */}
          <Pressable
            onPress={() => {
              try { Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); } catch {}
              router.back();
            }}
            hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
            accessible={true}
            accessibilityRole="button"
            accessibilityLabel="Geri Dön"
            style={({ pressed }) => ({
              width: 40,
              height: 40,
              borderRadius: 13,
              backgroundColor: "#18181B",
              borderWidth: 1,
              borderColor: "rgba(255,255,255,0.08)",
              alignItems: "center",
              justifyContent: "center",
              opacity: pressed ? 0.75 : 1,
            })}
          >
            <Ionicons name="chevron-back" size={20} color="#FFFFFF" />
          </Pressable>

          {/* Stüdyo Rozeti */}
          <View
            style={{
              backgroundColor: "rgba(212, 175, 55, 0.12)",
              paddingHorizontal: 14,
              paddingVertical: 6,
              borderRadius: 99,
              flexDirection: "row",
              alignItems: "center",
              gap: 6,
              borderWidth: 1,
              borderColor: "rgba(212, 175, 55, 0.25)",
            }}
          >
            <Ionicons name="sparkles" size={13} color="#D4AF37" />
            <Text style={{ color: "#D4AF37", fontSize: 11, fontWeight: "800", letterSpacing: 0.5 }}>
              INSTAGRAM QR STÜDYOSU
            </Text>
          </View>

          {/* Canlı Yenile / Senkronize Et Butonu */}
          <Pressable
            onPress={() => fetchTemplatesAndQr(true)}
            hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
            accessible={true}
            accessibilityRole="button"
            accessibilityLabel="Şablonları Canlı Yenile"
            style={({ pressed }) => ({
              width: 40,
              height: 40,
              borderRadius: 13,
              backgroundColor: "#18181B",
              borderWidth: 1,
              borderColor: syncing ? "#D4AF37" : "rgba(255,255,255,0.08)",
              alignItems: "center",
              justifyContent: "center",
              opacity: pressed ? 0.75 : 1,
            })}
          >
            <Ionicons
              name="sync"
              size={18}
              color={syncing ? "#D4AF37" : "#A1A1AA"}
            />
          </Pressable>
        </View>

        {/* Yatay Şablon Seçici Bar */}
        {presets.length > 0 && (
          <ScrollView
            horizontal
            showsHorizontalScrollIndicator={false}
            style={{ flexGrow: 0, marginBottom: 12 }}
            contentContainerStyle={{ gap: 8, paddingHorizontal: 2, alignItems: "center" }}
          >
            {presets.map((preset) => {
              const isSelected = preset.key === selectedKey;
              const pRatio = getPresetAspectRatio(preset);
              const calcHeight = Math.round(displayWidth / (pRatio || 1));

              return (
                <Pressable
                  key={preset.key}
                  onPress={() => {
                    try { Haptics.selectionAsync(); } catch {}

                    // 1. Mevcut şablonun son durumunu önbelleğe kaydet
                    templateCacheRef.current[selectedKey] = {
                      layers,
                      qrConfig,
                    };

                    const nextKey = preset.key;
                    setSelectedKey(nextKey);

                    // 2. Daha önce düzenlenmişse önbellekten geri yükle
                    if (templateCacheRef.current[nextKey]) {
                      setLayers(templateCacheRef.current[nextKey].layers);
                      setQrConfig(templateCacheRef.current[nextKey].qrConfig);
                    } else {
                      // İlk defa açılıyorsa başlat
                      let initialLayers: CanvasTextLayer[];
                      if ((preset as any).layers && (preset as any).layers.length > 0) {
                        initialLayers = (preset as any).layers.map((l: any) => ({
                          id: l.id || `layer-${Math.random()}`,
                          text: l.text === "{{RESTAURANT_NAME}}" ? restaurantName.toUpperCase() : l.text,
                          x: l.x ?? (displayWidth - 200) / 2,
                          y: l.y ?? Math.round((calcHeight * (l.yPercent || 15)) / 100),
                          rotation: l.rotation || 0,
                          fontSize: l.fontSize || 16,
                          fontId: l.fontId || "serif",
                          color: l.color || "#D4AF37",
                          textAlign: l.textAlign || "center",
                          bgStyle: l.bgStyle || "none",
                          letterSpacing: l.letterSpacing || 1,
                        }));
                      } else {
                        initialLayers = getDefaultLayersForTemplate(nextKey, restaurantName);
                      }

                      let initialQr: CanvasQrConfig;
                      if ((preset as any).qrConfig) {
                        const c = (preset as any).qrConfig;
                        initialQr = {
                          x: Math.round(((displayWidth - (c.size || 115)) * (c.xPercent || 50)) / 100),
                          y: Math.round(((calcHeight - (c.size || 115)) * (c.yPercent || 38)) / 100),
                          size: c.size || 115,
                          borderRadius: c.borderRadius || 14,
                          borderWidth: c.borderWidth || 2,
                          borderColor: c.borderColor || preset.borderAccent || "#D4AF37",
                          padding: c.padding || 8,
                          bgBoxColor: c.bgBoxColor || "#FFFFFF",
                        };
                      } else {
                        initialQr = getDefaultQrConfigForTemplate(nextKey, displayWidth, calcHeight);
                      }

                      setLayers(initialLayers);
                      setQrConfig(initialQr);
                      templateCacheRef.current[nextKey] = {
                        layers: initialLayers,
                        qrConfig: initialQr,
                      };
                    }

                    setSelectedLayerId(null);
                    setIsQrSelected(false);
                  }}
                  hitSlop={{ top: 6, bottom: 6, left: 4, right: 4 }}
                  accessible={true}
                  accessibilityRole="button"
                  accessibilityLabel={`${preset.name} şablonunu seç`}
                  accessibilityState={{ selected: isSelected }}
                  style={({ pressed }) => ({
                    paddingHorizontal: 12,
                    paddingVertical: 8,
                    minHeight: 36,
                    borderRadius: 12,
                    backgroundColor: isSelected ? "#D4AF37" : "#18181B",
                    borderWidth: 1.5,
                    borderColor: isSelected ? "#D4AF37" : "rgba(255,255,255,0.12)",
                    flexDirection: "row",
                    alignItems: "center",
                    gap: 6,
                    opacity: pressed ? 0.85 : 1,
                  })}
                >
                  <View
                    style={{
                      width: 10,
                      height: 10,
                      borderRadius: 5,
                      backgroundColor: preset.plaqueColor || "#18181B",
                      borderWidth: 1,
                      borderColor: isSelected ? "#0C0C0E" : "rgba(255,255,255,0.5)",
                    }}
                  />
                  <Text
                    style={{
                      fontSize: 12,
                      fontWeight: "700",
                      color: isSelected ? "#0C0C0E" : "#FFFFFF",
                    }}
                  >
                    {preset.name}
                  </Text>
                </Pressable>
              );
            })}
          </ScrollView>
        )}

        {/* İnteraktif Instagram QR & Canva Stüdyosu */}
        <QrCanvasStudio
          templateKey={selectedKey}
          restaurantName={restaurantName}
          qrBase64={qr.pngBase64}
          width={displayWidth}
          height={displayHeight}
          renderBackground={() => {
            const cur = presets.find((p) => p.key === selectedKey);
            const bgImg = (cur as any)?.bgImageUrl;

            // 1. Eğer şablona özel bir Arka Plan Görseli / SVG yüklenmişse bunu render et
            if (bgImg) {
              return (
                <View
                  style={{
                    width: displayWidth,
                    height: displayHeight,
                    backgroundColor: cur?.plaqueColor || "#132034",
                    borderRadius: 24,
                    overflow: "hidden",
                    borderWidth: 2,
                    borderColor: cur?.borderAccent || "#D4AF37",
                  }}
                >
                  <Image
                    source={{ uri: bgImg }}
                    style={{ width: "100%", height: "100%", position: "absolute" }}
                    resizeMode="cover"
                  />
                  {/* İç Dekoratif Çerçeve */}
                  <View
                    style={{
                      position: "absolute",
                      top: 10,
                      left: 10,
                      right: 10,
                      bottom: 10,
                      borderWidth: 1,
                      borderColor: cur?.dividerColor || "rgba(212, 175, 55, 0.3)",
                      borderRadius: 16,
                    }}
                  />
                </View>
              );
            }

            // 2. Özel görsel yoksa ve Yerel Hardcoded Component varsa onu kullan
            if (COMPONENT_TEMPLATES[selectedKey]) {
              const Comp = COMPONENT_TEMPLATES[selectedKey];
              return (
                <Comp
                  qrBase64={qr.pngBase64}
                  width={displayWidth}
                  height={displayHeight}
                  fields={HIDE_ALL_TEMPLATE_FIELDS}
                  hideQr={true}
                />
              );
            }

            // 3. Fallback dinamik stant
            if (!cur) return null;

            return (
              <View
                style={{
                  width: displayWidth,
                  height: displayHeight,
                  backgroundColor: cur.plaqueColor || "#132034",
                  borderRadius: 24,
                  overflow: "hidden",
                  borderWidth: 2,
                  borderColor: cur.borderAccent || "#D4AF37",
                }}
              >
                <View
                  style={{
                    position: "absolute",
                    top: 10,
                    left: 10,
                    right: 10,
                    bottom: 10,
                    borderWidth: 1,
                    borderColor: cur.dividerColor || "rgba(212, 175, 55, 0.3)",
                    borderRadius: 16,
                  }}
                />
              </View>
            );
          }}
          layers={layers}
          onLayersChange={handleLayersChange}
          qrConfig={qrConfig}
          onQrConfigChange={handleQrConfigChange}
          viewShotRef={viewShotRef}
          selectedLayerId={selectedLayerId}
          onSelectLayer={setSelectedLayerId}
          isQrSelected={isQrSelected}
          onSelectQr={setIsQrSelected}
          onDragStateChange={(dragging) => setScrollEnabled(!dragging)}
        />

        {/* Aksiyon Butonları Grubu */}
        <View style={{ width: "100%", gap: 10, marginTop: 4 }}>
          {/* PDF İndirme Butonu */}
          <Pressable
            onPress={handleExportPdf}
            disabled={exportingPdf}
            accessible={true}
            accessibilityRole="button"
            accessibilityLabel="PDF Olarak İndir (A5 Matbaa Baskı)"
            style={({ pressed }) => ({
              backgroundColor: "#D4AF37",
              borderRadius: 14,
              minHeight: 52,
              padding: 15,
              flexDirection: "row",
              alignItems: "center",
              justifyContent: "center",
              gap: 8,
              opacity: pressed || exportingPdf ? 0.85 : 1,
              shadowColor: "#D4AF37",
              shadowOffset: { width: 0, height: 4 },
              shadowOpacity: 0.25,
              shadowRadius: 8,
              elevation: 4,
            })}
          >
            {exportingPdf ? (
              <ActivityIndicator size="small" color="#0C0C0E" />
            ) : (
              <>
                <Ionicons name="document-text-outline" size={20} color="#0C0C0E" />
                <Text style={{ color: "#0C0C0E", fontSize: 15, fontWeight: "800" }}>
                  PDF Olarak İndir (A5 Matbaa Baskı)
                </Text>
              </>
            )}
          </Pressable>

          {/* PNG İndirme Butonu */}
          <Pressable
            onPress={handleExportPng}
            disabled={exportingPng}
            accessible={true}
            accessibilityRole="button"
            accessibilityLabel="PNG Olarak Kaydet veya Paylaş"
            style={({ pressed }) => ({
              backgroundColor: "#18181B",
              borderWidth: 1.5,
              borderColor: "rgba(255,255,255,0.12)",
              borderRadius: 14,
              minHeight: 48,
              padding: 14,
              flexDirection: "row",
              alignItems: "center",
              justifyContent: "center",
              gap: 8,
              opacity: pressed || exportingPng ? 0.85 : 1,
            })}
          >
            {exportingPng ? (
              <ActivityIndicator size="small" color="#FFFFFF" />
            ) : (
              <>
                <Ionicons name="image-outline" size={19} color="#FFFFFF" />
                <Text style={{ color: "#FFFFFF", fontSize: 14, fontWeight: "700" }}>
                  PNG Olarak Kaydet / Paylaş
                </Text>
              </>
            )}
          </Pressable>

          {/* Menü Linki Paylaş */}
          <Pressable
            onPress={handleShareQuick}
            accessible={true}
            accessibilityRole="button"
            accessibilityLabel="Menü Linkini Paylaş"
            style={({ pressed }) => ({
              backgroundColor: "#18181B",
              borderWidth: 1,
              borderColor: "rgba(255,255,255,0.08)",
              borderRadius: 14,
              minHeight: 44,
              padding: 13,
              flexDirection: "row",
              alignItems: "center",
              justifyContent: "center",
              gap: 8,
              opacity: pressed ? 0.85 : 1,
            })}
          >
            <Ionicons name="share-outline" size={17} color="#D4AF37" />
            <Text style={{ color: "#D4AF37", fontSize: 13.5, fontWeight: "700" }}>
              Menü Linkini Paylaş
            </Text>
          </Pressable>

          {/* Hızlı Kopyalama Kutusu */}
          <Pressable
            onPress={handleCopy}
            accessible={true}
            accessibilityRole="button"
            accessibilityLabel={`Menü linkini kopyala: ${qr.targetUrl}`}
            style={({ pressed }) => ({
              backgroundColor: "#121215",
              borderWidth: 1,
              borderColor: "rgba(255,255,255,0.08)",
              borderRadius: 12,
              padding: 12,
              minHeight: 44,
              flexDirection: "row",
              alignItems: "center",
              justifyContent: "space-between",
              marginTop: 2,
              opacity: pressed ? 0.85 : 1,
            })}
          >
            <Text style={{ color: "#A1A1AA", fontSize: 11.5, flex: 1 }} numberOfLines={1}>
              {qr.targetUrl}
            </Text>
            <Ionicons
              name={copied ? "checkmark-circle" : "copy-outline"}
              size={18}
              color={copied ? "#10B981" : "#D4AF37"}
              style={{ marginLeft: 8 }}
            />
          </Pressable>
        </View>
      </View>
    </ScrollView>
  );
}
