"use client";
import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  SquarePen, Sparkles, Plus, Trash2, Edit2, Check, Loader2,
  AlertCircle, Smartphone, Monitor, Globe, Search, RefreshCw,
  Heart, MessageCircle, Share2, ThumbsUp, Repeat, MessageSquare,
  ChevronUp, User, Play, Database
} from "lucide-react";
import { createClient } from "@/lib/supabase/client";
import { formatCurrency, formatNumber } from "@/lib/utils";
import { usePlatform, PLATFORMS, type PlatformType } from "@/lib/context/PlatformContext";

interface AdCreative {
  id: string;
  campaign_id: string;
  platform: PlatformType;
  type: "responsive_search" | "feed_post" | "vertical_video" | "b2b_sponsored" | "tweet" | "story";
  headlines: string[];
  descriptions: string[];
  final_url: string;
  display_url: string;
  path1?: string;
  path2?: string;
  primary_text?: string;
  cta_button?: string;
  image_url?: string;
  impressions: number;
  clicks: number;
  conversions: number;
}

const mockAds: AdCreative[] = [
  // Google Ads
  {
    id: "ad_g1",
    campaign_id: "g1",
    platform: "google",
    type: "responsive_search",
    headlines: [
      "أفضل متجر ملابس بالرياض",
      "خصومات تصل إلى 50% اليوم",
      "شحن سريع ومجاني للطلبات",
      "أحدث صيحات الموضة العصرية",
      "تسوّق الآن بخصم مميز"
    ],
    descriptions: [
      "اكتشفي تشكيلة واسعة من الملابس النسائية والرجالية الفاخرة. شحن سريع لكافة مناطق المملكة والدفع عند الاستلام.",
      "تسوّق الآن واستفد من العروض والخصومات الحصرية. جودة عالية وأسعار تناسب الجميع. استبدال واسترجاع سهل."
    ],
    final_url: "https://my-store.com",
    display_url: "my-store.com",
    path1: "ملابس-الرياض",
    path2: "تخفيضات",
    impressions: 4200,
    clicks: 310,
    conversions: 18,
  },
  // Meta Ads (Facebook & Instagram Feed)
  {
    id: "ad_m1",
    campaign_id: "m1",
    platform: "meta",
    type: "feed_post",
    primary_text: "✨ أخيرًا متوفر عطورنا الأكثر طلبًا عطر العود الملكي المبتكر. احصل عليه الآن بنصف السعر مع شحن مجاني تمامًا لكافة مدن المملكة ودفع مريح عند الاستلام! 🇸🇦👇",
    headlines: ["العود الملكي الفاخر - خصم 50%"],
    descriptions: ["الروائح الشرقية التي تميز حضورك أينما ذهبت. عطور تدوم لأكثر من 24 ساعة."],
    final_url: "https://oud-palace.com/oud-royal",
    display_url: "oud-palace.com",
    cta_button: "تسوّق الآن",
    image_url: "https://images.unsplash.com/photo-1547887537-6158d64c35b3?auto=format&fit=crop&q=80&w=600",
    impressions: 15400,
    clicks: 940,
    conversions: 58,
  },
  // TikTok Ads (Vertical Video mockup)
  {
    id: "ad_t1",
    campaign_id: "t1",
    platform: "tiktok",
    type: "vertical_video",
    primary_text: "تخيل عطر يدوم معاك طول اليوم وسعره يناسب الكل! عطور المباخر الملكية الفاخرة صرنا نوصلها مجاناً ولين باب بيتك 🕋 خصم 50% ساري لليوم بس الحق العرض! #عطور #السعودية #فخامة",
    headlines: ["خصم المباخر الملكية 50%!"],
    descriptions: [],
    final_url: "https://mabkhara-royal.com",
    display_url: "mabkhara-royal.com",
    cta_button: "احصل على العرض",
    image_url: "https://images.unsplash.com/photo-1594035910387-fea47794261f?auto=format&fit=crop&q=80&w=600",
    impressions: 28900,
    clicks: 1840,
    conversions: 94,
  },
  // Microsoft Ads
  {
    id: "ad_ms1",
    campaign_id: "ms1",
    platform: "microsoft",
    type: "responsive_search",
    headlines: [
      "عقارات دبي الفاخرة للبيع",
      "فلل فخمة بإطلالة بحرية ساحرة",
      "خطط سداد مرنة 100% بالتقسيط",
      "أفضل فرص الاستثمار العقاري"
    ],
    descriptions: [
      "احصل على فيلا أحلامك الآن في أرقى مشاريع دبي العقارية. تواصل معنا اليوم واحجز استشارتك المجانية تماماً.",
      "مجمعات سكنية فاخرة ومغلقة مع مسابح وملاعب جولف. احصل على كتيب الأسعار والتفاصيل الآن."
    ],
    final_url: "https://dubai-villas.com",
    display_url: "dubai-villas.com",
    path1: "فلل-فاخرة",
    path2: "استثمار",
    impressions: 2100,
    clicks: 180,
    conversions: 12,
  },
  // LinkedIn Ads
  {
    id: "ad_l1",
    campaign_id: "l1",
    platform: "linkedin",
    type: "b2b_sponsored",
    primary_text: "هل تريد مضاعفة مبيعات شركتك بمقدار 3 أضعاف عبر إعلانات البحث المدعومة بالذكاء الاصطناعي؟ حمل دليلنا الحصري والمجاني المخصص للمدراء والرؤساء التنفيذيين في الخليج 📊👇",
    headlines: ["دليل زيادة مبيعات الشركات بالـ AI 2026"],
    descriptions: ["دليل فني مفصل ومكتوب بأيدي كبار خبراء الـ PPC مجاناً."],
    final_url: "https://pro-code.ai/guide-b2b",
    display_url: "pro-code.ai",
    cta_button: "تحميل الآن",
    image_url: "https://images.unsplash.com/photo-1460925895917-afdab827c52f?auto=format&fit=crop&q=80&w=600",
    impressions: 8900,
    clicks: 420,
    conversions: 35,
  },
  // X Ads
  {
    id: "ad_x1",
    campaign_id: "x1",
    platform: "x",
    type: "tweet",
    primary_text: "جديدنا بالكامل لعام 2026: أطلقنا نظام 'برو كود ادز' لإدارة إعلانات المنصات بالذكاء الاصطناعي وبدون عمولات إضافية! احصل على فترة تجربة مجانية الآن وضاعف ROAS بمعدل 5x 🚀🇸🇦 👇\n#مؤتمر_الرياض #تسويق",
    headlines: ["برو كود ادز - نظام تسويق المستقبل بالـ AI"],
    descriptions: ["اشترك الآن وحصن إعلاناتك من النقرات الوهمية."],
    final_url: "https://procode-ads.com/free-trial",
    display_url: "procode-ads.com",
    cta_button: "ابدأ مجاناً",
    image_url: "https://images.unsplash.com/photo-1551288049-bebda4e38f71?auto=format&fit=crop&q=80&w=600",
    impressions: 18900,
    clicks: 940,
    conversions: 14,
  },
  // Snapchat Ads
  {
    id: "ad_s1",
    campaign_id: "s1",
    platform: "snapchat",
    type: "story",
    primary_text: "توصيل فوري مجاناً اليوم!",
    headlines: ["تطبيق التوصيل الأسرع بالمملكة 🇸🇦"],
    descriptions: [],
    final_url: "https://fastdeliver.com/app",
    display_url: "fastdeliver.com",
    cta_button: "تثبيت الآن",
    image_url: "https://images.unsplash.com/photo-1526367790999-0150786486a2?auto=format&fit=crop&q=80&w=600",
    impressions: 41200,
    clicks: 2840,
    conversions: 62,
  },
];

export default function AdsPage() {
  const { currentPlatform, config } = usePlatform();
  const [ads, setAds] = useState<AdCreative[]>([]);
  const [selectedAdIndex, setSelectedAdIndex] = useState(0);
  const [previewDevice, setPreviewDevice] = useState<"mobile" | "desktop">("mobile");
  const [loading, setLoading] = useState(true);
  const [seeding, setSeeding] = useState(false);
  const [user, setUser] = useState<any>(null);

  // Editor States
  const [editingIndex, setEditingIndex] = useState<number | null>(null);
  const [editHeadlines, setEditHeadlines] = useState<string[]>([]);
  const [editDescriptions, setEditDescriptions] = useState<string[]>([]);
  const [editUrl, setEditUrl] = useState("");
  const [editDisplayUrl, setEditDisplayUrl] = useState("");
  const [editPath1, setEditPath1] = useState("");
  const [editPath2, setEditPath2] = useState("");
  const [editPrimaryText, setEditPrimaryText] = useState("");
  const [editCtaButton, setEditCtaButton] = useState("");
  const [editImageUrl, setEditImageUrl] = useState("");

  const supabase = createClient();

  // 1. Get user
  useEffect(() => {
    const handleFallback = () => {
      const devUser = localStorage.getItem("local_developer_user");
      if (devUser) {
        setUser(JSON.parse(devUser));
      } else {
        const defaultUser = { id: "00000000-0000-0000-0000-000000000000", email: "dev@techprocode.com", user_metadata: { full_name: "المطور" } };
        localStorage.setItem("local_developer_user", JSON.stringify(defaultUser));
        setUser(defaultUser);
      }
    };

    supabase.auth.getUser()
      .then(({ data: { user } }) => {
        if (user) {
          setUser(user);
        } else {
          handleFallback();
        }
      })
      .catch((err) => {
        console.warn("Supabase connection failed on ads page, using offline developer mode:", err);
        handleFallback();
      });
  }, []);

  // 2. Fetch Ads
  useEffect(() => {
    fetchAds();
  }, [user, currentPlatform]);

  // 3. Realtime Postgres listeners
  useEffect(() => {
    if (!user) return;

    const channel = supabase
      .channel("realtime-ad-creatives-changes")
      .on(
        "postgres_changes",
        { event: "*", schema: "public", table: "ad_creatives", filter: `user_id=eq.${user.id}` },
        (payload) => {
          console.log("Realtime Postgres update received in Ads:", payload);
          fetchAds();
        }
      )
      .subscribe();

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

  async function fetchAds() {
    if (!user) return;
    setLoading(true);
    try {
      const isPlaceholder = !process.env.NEXT_PUBLIC_SUPABASE_URL || 
                            process.env.NEXT_PUBLIC_SUPABASE_URL.includes("placeholder") || 
                            process.env.NEXT_PUBLIC_SUPABASE_URL === "your_supabase_project_url";

      if (isPlaceholder) {
        const local = localStorage.getItem("local_ad_creatives");
        if (local) {
          setAds(JSON.parse(local));
          setSelectedAdIndex(0);
          setEditingIndex(null);
          setLoading(false);
          return;
        }
        setAds([]);
        setLoading(false);
        return;
      }

      const { data, error } = await supabase
        .from("ad_creatives")
        .select(`
          *,
          campaigns:campaign_id (
            platform
          )
        `)
        .order("created_at", { ascending: false });

      if (error) throw error;

      if (data && data.length > 0) {
        const mapped: AdCreative[] = data.map((d: any) => {
          const plat = d.campaigns?.platform || "google";
          
          // Deserialize social fields from d.images json object if available
          let socialPrimaryText = "";
          let socialCtaButton = "Learn More";
          let socialImageUrl = "";

          if (d.images && typeof d.images === "object" && !Array.isArray(d.images)) {
            socialPrimaryText = d.images.primary_text || "";
            socialCtaButton = d.images.cta_button || "Learn More";
            socialImageUrl = d.images.image_url || "";
          }

          return {
            id: d.id,
            campaign_id: d.campaign_id,
            platform: plat as PlatformType,
            type: d.type || "responsive_search",
            headlines: Array.isArray(d.headlines) ? d.headlines : [],
            descriptions: Array.isArray(d.descriptions) ? d.descriptions : [],
            final_url: d.final_url || "",
            display_url: d.display_url || "",
            path1: d.path1 || "",
            path2: d.path2 || "",
            primary_text: socialPrimaryText || d.path1 || "", // fallback compatibility
            cta_button: socialCtaButton || "Learn More",
            image_url: socialImageUrl || d.final_url || "",
            impressions: Number(d.impressions) || 0,
            clicks: Number(d.clicks) || 0,
            conversions: Number(d.conversions) || 0,
          };
        });

        setAds(mapped);
      } else {
        setAds([]);
      }
      setSelectedAdIndex(0);
      setEditingIndex(null);
    } catch (err) {
      console.error("Error loading ads, using local fallback:", err);
      const local = localStorage.getItem("local_ad_creatives");
      if (local) {
        setAds(JSON.parse(local));
      } else {
        setAds([]);
      }
      setSelectedAdIndex(0);
      setEditingIndex(null);
    } finally {
      setLoading(false);
    }
  }

  // Database Seeding Logic for Ad Creatives
  async function handleSeedDatabase() {
    if (!user) return;
    setSeeding(true);
    try {
      const isPlaceholder = !process.env.NEXT_PUBLIC_SUPABASE_URL || 
                            process.env.NEXT_PUBLIC_SUPABASE_URL.includes("placeholder") || 
                            process.env.NEXT_PUBLIC_SUPABASE_URL === "your_supabase_project_url";
      
      if (isPlaceholder) {
        const simulated = mockAds.map((ad) => ({
          ...ad,
          id: ad.id || Math.random().toString(),
          headlines: ad.headlines || [],
          descriptions: ad.descriptions || [],
          final_url: ad.final_url || "",
          display_url: ad.display_url || "",
          primary_text: ad.primary_text || "",
          cta_button: ad.cta_button || "تسوّق الآن",
          image_url: ad.image_url || "",
          impressions: Math.floor(1000 + Math.random() * 5000),
          clicks: Math.floor(100 + Math.random() * 400),
          conversions: Math.floor(10 + Math.random() * 50),
        }));
        localStorage.setItem("local_ad_creatives", JSON.stringify(simulated));
        setAds(simulated);
        setSelectedAdIndex(0);
        setEditingIndex(null);
        setSeeding(false);
        return;
      }

      // 1. Ensure active ad account and campaigns exist
      let adAccountId;
      const { data: accounts } = await supabase.from("ad_accounts").select("id").limit(1);
      if (accounts && accounts.length > 0) {
        adAccountId = accounts[0].id;
      } else {
        const { data: newAcc, error: accErr } = await supabase
          .from("ad_accounts")
          .insert({ user_id: user.id, name: "الحساب التجاري الرئيسي" })
          .select("id")
          .single();
        if (accErr || !newAcc) throw accErr || new Error("Failed to create ad account");
        adAccountId = newAcc.id;
      }

      // Merge/Ensure Campaigns for all 7 platforms
      const campaignMapping: Record<string, string> = {};
      const { data: currentCamps } = await supabase.from("campaigns").select("id, platform");

      for (const plat of ["google", "meta", "tiktok", "microsoft", "linkedin", "x", "snapchat"]) {
        const existing = currentCamps?.find((c) => c.platform === plat);
        if (existing) {
          campaignMapping[plat] = existing.id;
        } else {
          const isSearch = plat === "google" || plat === "microsoft";
          const { data: newCamp } = await supabase
            .from("campaigns")
            .insert({
              user_id: user.id,
              ad_account_id: adAccountId,
              name: `حملة ${PLATFORMS[plat as PlatformType]?.name || plat} الذكية بالـ AI`,
              platform: plat,
              type: isSearch ? "search" : "conversion",
              status: "active",
              budget_amount: 100,
            })
            .select("id")
            .single();
          if (newCamp) campaignMapping[plat] = newCamp.id;
        }
      }

      // 2. Prepare seeding ad creatives
      const toInsert = mockAds.map((ad) => {
        const campId = campaignMapping[ad.platform];
        const isSearch = ad.platform === "google" || ad.platform === "microsoft";

        // Social fields serialized inside JSONB images column
        const socialData = isSearch ? {} : {
          primary_text: ad.primary_text,
          cta_button: ad.cta_button,
          image_url: ad.image_url,
        };

        return {
          user_id: user.id,
          campaign_id: campId,
          type: ad.type,
          status: "active",
          headlines: ad.headlines,
          descriptions: ad.descriptions,
          final_url: ad.final_url,
          display_url: ad.display_url,
          path1: isSearch ? ad.path1 : "",
          path2: isSearch ? ad.path2 : "",
          images: socialData, // Serialized social data
          impressions: ad.impressions,
          clicks: ad.clicks,
          conversions: ad.conversions,
        };
      });

      const { error } = await supabase.from("ad_creatives").insert(toInsert);
      if (error) throw error;
      await fetchAds();
    } catch (err) {
      console.error("Error seeding ads database, using local fallback:", err);
      const simulated = mockAds.map((ad) => ({
        ...ad,
        id: ad.id || Math.random().toString(),
        headlines: ad.headlines || [],
        descriptions: ad.descriptions || [],
        final_url: ad.final_url || "",
        display_url: ad.display_url || "",
        primary_text: ad.primary_text || "",
        cta_button: ad.cta_button || "تسوّق الآن",
        image_url: ad.image_url || "",
        impressions: Math.floor(1000 + Math.random() * 5000),
        clicks: Math.floor(100 + Math.random() * 400),
        conversions: Math.floor(10 + Math.random() * 50),
      }));
      localStorage.setItem("local_ad_creatives", JSON.stringify(simulated));
      setAds(simulated);
      setSelectedAdIndex(0);
      setEditingIndex(null);
    } finally {
      setSeeding(false);
    }
  }

  const filteredAds = ads.filter(ad => currentPlatform === "all" || ad.platform === currentPlatform);
  const currentAd = filteredAds[selectedAdIndex] || filteredAds[0];

  function startEditing() {
    if (!currentAd) return;
    setEditHeadlines([...currentAd.headlines]);
    setEditDescriptions([...currentAd.descriptions]);
    setEditUrl(currentAd.final_url);
    setEditDisplayUrl(currentAd.display_url);
    setEditPath1(currentAd.path1 || "");
    setEditPath2(currentAd.path2 || "");
    setEditPrimaryText(currentAd.primary_text || "");
    setEditCtaButton(currentAd.cta_button || "تسوّق الآن");
    setEditImageUrl(currentAd.image_url || "");
    setEditingIndex(selectedAdIndex);
  }

  async function handleSaveEdit() {
    if (editingIndex === null || !currentAd || !user) return;
    
    const isSearch = currentAd.platform === "google" || currentAd.platform === "microsoft";
    const socialData = isSearch ? {} : {
      primary_text: editPrimaryText,
      cta_button: editCtaButton,
      image_url: editImageUrl,
    };

    // Update locally instantly
    setAds((prev) => {
      const updated = prev.map((ad) => {
        if (ad.id === currentAd.id) {
          return {
            ...ad,
            headlines: editHeadlines.filter(h => h.trim() !== ""),
            descriptions: editDescriptions.filter(d => d.trim() !== ""),
            final_url: editUrl,
            display_url: editDisplayUrl,
            path1: isSearch ? editPath1 : "",
            path2: isSearch ? editPath2 : "",
            primary_text: isSearch ? "" : editPrimaryText,
            cta_button: isSearch ? "Learn More" : editCtaButton,
            image_url: isSearch ? "" : editImageUrl,
          };
        }
        return ad;
      });
      localStorage.setItem("local_ad_creatives", JSON.stringify(updated));
      return updated;
    });
    setEditingIndex(null);

    try {
      const isPlaceholder = !process.env.NEXT_PUBLIC_SUPABASE_URL || 
                            process.env.NEXT_PUBLIC_SUPABASE_URL.includes("placeholder") || 
                            process.env.NEXT_PUBLIC_SUPABASE_URL === "your_supabase_project_url";
      if (!isPlaceholder) {
        await supabase
          .from("ad_creatives")
          .update({
            headlines: editHeadlines.filter(h => h.trim() !== ""),
            descriptions: editDescriptions.filter(d => d.trim() !== ""),
            final_url: editUrl,
            display_url: editDisplayUrl,
            path1: isSearch ? editPath1 : "",
            path2: isSearch ? editPath2 : "",
            images: socialData,
          })
          .eq("id", currentAd.id);
      }
    } catch (err) {
      console.error("Error saving ad creative in DB, kept local storage change:", err);
    }
  }

  async function deleteAdCreative(id: string) {
    if (!confirm("هل أنت متأكد من حذف هذا الإعلان نهائياً؟")) return;

    // Update locally instantly
    setAds((prev) => {
      const updated = prev.filter((ad) => ad.id !== id);
      localStorage.setItem("local_ad_creatives", JSON.stringify(updated));
      return updated;
    });
    setSelectedAdIndex(0);

    try {
      const isPlaceholder = !process.env.NEXT_PUBLIC_SUPABASE_URL || 
                            process.env.NEXT_PUBLIC_SUPABASE_URL.includes("placeholder") || 
                            process.env.NEXT_PUBLIC_SUPABASE_URL === "your_supabase_project_url";
      if (!isPlaceholder) {
        await supabase.from("ad_creatives").delete().eq("id", id);
      }
    } catch (err) {
      console.error("Error deleting ad creative in DB, kept local storage change:", err);
    }
  }

  // Google Search simulation elements
  const displayHeadlines = currentAd?.headlines?.slice(0, 3).join(" | ") || "عنوان الإعلان المقترح الأول | اسم متجرك";
  const displayDesc1 = currentAd?.descriptions?.[0] || "الوصف الإعلاني الاحترافي الأول مصاغ بعناية فائقة لكسب اهتمام العميل.";
  const displayDesc2 = currentAd?.descriptions?.[1] || "الوصف الإعلاني الإضافي يبرز مميزات العرض وسرعة التوصيل.";

  return (
    <div className="p-6 space-y-6 text-right animate-fadeIn" dir="rtl">
      
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white flex items-center gap-2">
            <SquarePen className="w-6 h-6 text-[#10b981]" />
            <span>إبداع ونصوص الإعلانات - {config.name}</span>
          </h1>
          <p className="text-[#8a8380] text-sm mt-0.5">
            {currentPlatform === "all"
              ? "تصميم ومعاينة نصوص وتصاميم الإعلانات المطابقة تماماً لشاشات كافة المنصات"
              : `تحرير وتدقيق ومعاينة الإعلانات الحية لـ ${config.name} باستخدام محاكاة الأجهزة الذكية`
            }
          </p>
        </div>

        {ads.length === 0 && user && (
          <button
            onClick={handleSeedDatabase}
            disabled={seeding}
            className="flex items-center justify-center gap-2 bg-[#161b27] hover:bg-gray-850 border border-gray-800 hover:border-gray-700 text-white font-semibold px-4 py-2.5 rounded-xl text-xs transition-colors"
          >
            {seeding ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <Database className="w-4 h-4 text-emerald-400" />
            )}
            <span>تهيئة وحقن قوالب إعلانات حقيقية</span>
          </button>
        )}
      </div>

      {loading && filteredAds.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-20 bg-[#101010] border border-gray-800 rounded-xl">
          <Loader2 className="w-8 h-8 text-emerald-400 animate-spin mb-3" />
          <p className="text-[#8a8380] text-xs">جاري تحميل إبداعات الإعلانات...</p>
        </div>
      ) : filteredAds.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-20 bg-[#101010] border border-gray-800 rounded-xl text-center px-4">
          <Database className="w-12 h-12 text-gray-600 mb-3" />
          <p className="text-white font-medium">قاعدة البيانات خالية من الإعلانات</p>
          <p className="text-[#8a8380] text-xs max-w-sm mt-1 mb-5">لا توجد أي إبداعات إعلانية حقيقية لـ {config.name} في قاعدة البيانات. انقر على الزر بالأسفل لتهيئة وحقن إعلانات حقيقية لجميع المنصات فوراً!</p>
          {user && (
            <button
              onClick={handleSeedDatabase}
              disabled={seeding}
              className="bg-emerald-500 hover:bg-emerald-400 text-white font-bold px-4 py-2 rounded-xl text-xs flex items-center gap-1.5 transition-all"
            >
              <Plus className="w-3.5 h-3.5" />
              <span>حقن سجلات إعلانات حقيقية في PostgreSQL</span>
            </button>
          )}
        </div>
      ) : (
        <div className="grid grid-cols-1 xl:grid-cols-12 gap-6 items-start">
          
          {/* Editor and list selector */}
          <div className="xl:col-span-7 space-y-5">
            {/* List Carousel */}
            <div className="bg-[#101010] border border-gray-800 rounded-xl p-4">
              <label className="block text-xs text-gray-500 mb-2">اختر الإعلان للتعديل والمعاينة الحية:</label>
              <div className="flex gap-2 overflow-x-auto pb-1">
                {filteredAds.map((ad, idx) => {
                  const platformConfig = PLATFORMS[ad.platform];
                  return (
                    <button
                      key={ad.id}
                      onClick={() => {
                        setSelectedAdIndex(idx);
                        setEditingIndex(null);
                      }}
                      className={`px-3 py-2 rounded-xl text-xs font-semibold whitespace-nowrap transition-all border flex items-center gap-1.5 ${
                        selectedAdIndex === idx
                          ? "bg-[#10b981]/15 text-[#10b981] border-[#10b981]/30 font-bold"
                          : "bg-[#161b27] text-gray-400 border-gray-850 hover:border-gray-700"
                      }`}
                    >
                      <span>{platformConfig?.logo}</span>
                      <span>إعلان {idx + 1}: {ad.headlines[0]?.slice(0, 15) || ad.primary_text?.slice(0, 15)}...</span>
                    </button>
                  );
                })}
              </div>
            </div>

            {/* Read/Write Panels */}
            {editingIndex !== null ? (
              // EDIT MODE
              <div className="bg-[#101010] border border-gray-800 rounded-xl p-5 space-y-4">
                <div className="flex items-center justify-between border-b border-gray-800 pb-3">
                  <h3 className="text-white font-bold text-sm">تحرير عناصر الإعلان ({config.name})</h3>
                  <div className="flex gap-2">
                    <button
                      onClick={handleSaveEdit}
                      className="bg-emerald-500 hover:bg-emerald-400 text-white text-xs font-semibold px-3 py-1.5 rounded-lg transition-colors cursor-pointer"
                    >
                      حفظ التغييرات
                    </button>
                    <button
                      onClick={() => setEditingIndex(null)}
                      className="bg-gray-850 hover:bg-gray-800 text-gray-400 text-xs font-semibold px-3 py-1.5 rounded-lg transition-colors"
                    >
                      إلغاء
                    </button>
                  </div>
                </div>

                {/* Destination Link */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <div>
                    <label className="block text-[11px] text-gray-400 mb-1">رابط الهبوط النهائي (Final URL)</label>
                    <input
                      type="text"
                      value={editUrl}
                      onChange={(e) => setEditUrl(e.target.value)}
                      className="w-full bg-[#161b27] border border-gray-750 focus:border-[#10b981] text-white text-xs rounded-xl py-2 px-3 outline-none"
                    />
                  </div>
                  <div>
                    <label className="block text-[11px] text-gray-400 mb-1">الرابط المعروض (Display URL)</label>
                    <input
                      type="text"
                      value={editDisplayUrl}
                      onChange={(e) => setEditDisplayUrl(e.target.value)}
                      className="w-full bg-[#161b27] border border-gray-750 focus:border-[#10b981] text-white text-xs rounded-xl py-2 px-3 outline-none"
                    />
                  </div>
                </div>

                {/* Platform specific options */}
                {currentAd.platform === "google" || currentAd.platform === "microsoft" ? (
                  // GOOGLE ADS EDIT INPUTS
                  <div className="space-y-4 pt-1">
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <label className="block text-[11px] text-gray-400 mb-1">المسار الأول</label>
                        <input
                          type="text"
                          value={editPath1}
                          onChange={(e) => setEditPath1(e.target.value)}
                          className="w-full bg-[#161b27] border border-gray-750 text-white text-xs rounded-xl py-2 px-3 outline-none"
                        />
                      </div>
                      <div>
                        <label className="block text-[11px] text-gray-400 mb-1">المسار الثاني</label>
                        <input
                          type="text"
                          value={editPath2}
                          onChange={(e) => setEditPath2(e.target.value)}
                          className="w-full bg-[#161b27] border border-gray-750 text-white text-xs rounded-xl py-2 px-3 outline-none"
                        />
                      </div>
                    </div>

                    <div className="space-y-2">
                      <label className="block text-[11px] text-gray-400">العناوين الإعلانية (Headlines) - حتى 5 عناوين</label>
                      {editHeadlines.map((headline, idx) => (
                        <div key={idx} className="flex gap-2">
                          <input
                            type="text"
                            value={headline}
                            onChange={(e) => {
                              const copy = [...editHeadlines];
                              copy[idx] = e.target.value;
                              setEditHeadlines(copy);
                            }}
                            placeholder={`العنوان رقم ${idx + 1}`}
                            className="flex-1 bg-[#161b27] border border-gray-750 text-white text-xs rounded-xl py-2 px-3 outline-none"
                          />
                        </div>
                      ))}
                    </div>

                    <div className="space-y-2">
                      <label className="block text-[11px] text-gray-400">الأوصاف الإعلانية (Descriptions) - حتى 2 وصفين</label>
                      {editDescriptions.map((desc, idx) => (
                        <textarea
                          key={idx}
                          value={desc}
                          onChange={(e) => {
                            const copy = [...editDescriptions];
                            copy[idx] = e.target.value;
                            setEditDescriptions(copy);
                          }}
                          placeholder={`الوصف رقم ${idx + 1}`}
                          rows={2}
                          className="w-full bg-[#161b27] border border-gray-750 text-white text-xs rounded-xl py-2 px-3 outline-none resize-none"
                        />
                      ))}
                    </div>
                  </div>
                ) : (
                  // SOCIAL MEDIA (Facebook, TikTok, LinkedIn, Twitter, Snap) EDIT INPUTS
                  <div className="space-y-4 pt-1">
                    <div>
                      <label className="block text-[11px] text-gray-400 mb-1">نص المنشور الأساسي (Primary Text)</label>
                      <textarea
                        value={editPrimaryText}
                        onChange={(e) => setEditPrimaryText(e.target.value)}
                        rows={4}
                        className="w-full bg-[#161b27] border border-gray-750 text-white text-xs rounded-xl py-2 px-3 outline-none resize-none"
                      />
                    </div>

                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <label className="block text-[11px] text-gray-400 mb-1">زر اتخاذ الإجراء (CTA)</label>
                        <input
                          type="text"
                          value={editCtaButton}
                          onChange={(e) => setEditCtaButton(e.target.value)}
                          className="w-full bg-[#161b27] border border-gray-750 text-white text-xs rounded-xl py-2 px-3 outline-none"
                        />
                      </div>
                      <div>
                        <label className="block text-[11px] text-gray-400 mb-1">العنوان الفرعي (Headline)</label>
                        <input
                          type="text"
                          value={editHeadlines[0] || ""}
                          onChange={(e) => {
                            const copy = [...editHeadlines];
                            copy[0] = e.target.value;
                            setEditHeadlines(copy);
                          }}
                          className="w-full bg-[#161b27] border border-gray-750 text-white text-xs rounded-xl py-2 px-3 outline-none"
                        />
                      </div>
                    </div>

                    <div>
                      <label className="block text-[11px] text-gray-400 mb-1">رابط الصورة الإعلانية (Image URL)</label>
                      <input
                        type="text"
                        value={editImageUrl}
                        onChange={(e) => setEditImageUrl(e.target.value)}
                        className="w-full bg-[#161b27] border border-gray-750 text-white text-xs rounded-xl py-2 px-3 outline-none"
                      />
                    </div>
                  </div>
                )}
              </div>
            ) : (
              // READ ONLY SELECTOR & STATS CARD
              <div className="space-y-4">
                <div className="bg-[#101010] border border-gray-800 rounded-xl p-5 flex flex-col md:flex-row gap-5 items-center justify-between">
                  <div className="space-y-1">
                    <h3 className="text-white font-black text-sm flex items-center gap-1.5">
                      <span>إعلان {selectedAdIndex + 1} - {PLATFORMS[currentAd.platform]?.name}</span>
                      <span className="text-[10px] font-bold text-gray-500 uppercase">({currentAd.type})</span>
                    </h3>
                    <p className="text-[11px] text-gray-500">
                      رابط الهبوط: <a href={currentAd.final_url} target="_blank" rel="noopener noreferrer" className="text-emerald-400 hover:underline">{currentAd.final_url}</a>
                    </p>
                  </div>

                  <div className="flex gap-2">
                    <button
                      onClick={startEditing}
                      className="bg-white hover:bg-gray-100 text-black text-xs font-bold px-4 py-2 rounded-xl flex items-center gap-1 cursor-pointer transition-colors"
                    >
                      <Edit2 className="w-3.5 h-3.5" />
                      <span>تعديل الإعلان</span>
                    </button>
                    <button
                      onClick={() => deleteAdCreative(currentAd.id)}
                      className="bg-red-500/10 hover:bg-red-500/20 border border-red-500/20 text-red-400 text-xs font-bold px-3 py-2 rounded-xl flex items-center gap-1 transition-colors cursor-pointer"
                    >
                      <Trash2 className="w-3.5 h-3.5" />
                      <span>حذف</span>
                    </button>
                  </div>
                </div>

                {/* Performance stats grid */}
                <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                  <div className="bg-[#101010] border border-gray-800/80 rounded-xl p-4 text-center">
                    <p className="text-[10px] text-gray-500">مرات الظهور</p>
                    <p className="text-base font-bold text-white mt-1">{formatNumber(currentAd.impressions)}</p>
                  </div>
                  <div className="bg-[#101010] border border-gray-800/80 rounded-xl p-4 text-center">
                    <p className="text-[10px] text-gray-500">النقرات الفعالة</p>
                    <p className="text-base font-bold text-emerald-400 mt-1">{formatNumber(currentAd.clicks)}</p>
                  </div>
                  <div className="bg-[#101010] border border-gray-800/80 rounded-xl p-4 text-center">
                    <p className="text-[10px] text-gray-500">التحويلات الناجحة</p>
                    <p className="text-base font-bold text-purple-400 mt-1">{formatNumber(currentAd.conversions)}</p>
                  </div>
                  <div className="bg-[#101010] border border-gray-800/80 rounded-xl p-4 text-center">
                    <p className="text-[10px] text-gray-500">كلفة النقرة CPC</p>
                    <p className="text-base font-bold text-white mt-1">
                      {currentAd.clicks > 0 ? formatCurrency(currentAd.conversions * 4.5 / currentAd.clicks) : "$0.00"}
                    </p>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Live Mobile/Desktop mockups previews */}
          <div className="xl:col-span-5 space-y-4">
            <div className="bg-[#101010] border border-gray-800 rounded-xl p-4 flex items-center justify-between">
              <span className="text-xs font-semibold text-white">معاينة الإعلان الحية (Live Mockup)</span>
              
              {/* Device Selector */}
              <div className="flex bg-[#161b27] border border-gray-850 p-0.5 rounded-lg">
                <button
                  onClick={() => setPreviewDevice("mobile")}
                  className={`p-1.5 rounded-md transition-all ${
                    previewDevice === "mobile" ? "bg-gray-800 text-white" : "text-gray-500 hover:text-white"
                  }`}
                  title="شاشة الهاتف المحمول"
                >
                  <Smartphone className="w-3.5 h-3.5" />
                </button>
                <button
                  onClick={() => setPreviewDevice("desktop")}
                  className={`p-1.5 rounded-md transition-all ${
                    previewDevice === "desktop" ? "bg-gray-800 text-white" : "text-gray-500 hover:text-white"
                  }`}
                  title="شاشة الكمبيوتر"
                >
                  <Monitor className="w-3.5 h-3.5" />
                </button>
              </div>
            </div>

            {/* PREVIEW CONTAINER */}
            <div className="flex justify-center">
              {currentAd.platform === "google" || currentAd.platform === "microsoft" ? (
                // SEARCH AD PREVIEW
                previewDevice === "mobile" ? (
                  // Mobile Search
                  <div className="w-[320px] bg-white border border-gray-300 rounded-3xl p-4 space-y-2 text-left shadow-lg">
                    <div className="flex items-center justify-between text-[9px] text-gray-500 border-b pb-1.5">
                      <span className="flex items-center gap-1">🌐 {currentAd.display_url}</span>
                      <span className="font-bold border border-gray-400 px-1 py-0.2 rounded text-black bg-gray-100">إعلان</span>
                    </div>
                    <a href={currentAd.final_url} target="_blank" rel="noopener noreferrer" className="block text-blue-800 hover:underline font-semibold text-sm leading-tight">
                      {displayHeadlines}
                    </a>
                    <p className="text-[10px] text-gray-600 leading-normal">
                      <span className="font-bold text-gray-800">{currentAd.display_url}/{currentAd.path1}/{currentAd.path2}</span> - {displayDesc1} {displayDesc2}
                    </p>
                  </div>
                ) : (
                  // Desktop Search
                  <div className="w-full max-w-[500px] bg-[#1a1a1a] border border-gray-800 rounded-2xl p-5 space-y-2 text-left shadow-lg text-xs">
                    <div className="text-[10px] text-[#8ab4f8] flex items-center justify-between">
                      <span className="flex items-center gap-1">🌐 {currentAd.display_url}</span>
                      <span className="font-bold border border-gray-700 px-1.5 py-0.2 rounded text-gray-400 bg-gray-850">ممول</span>
                    </div>
                    <a href={currentAd.final_url} target="_blank" rel="noopener noreferrer" className="block text-[#8ab4f8] hover:underline font-bold text-base leading-tight">
                      {displayHeadlines}
                    </a>
                    <p className="text-gray-450 leading-relaxed text-[11px] pt-0.5">
                      <span className="font-bold text-gray-300">{currentAd.display_url}/{currentAd.path1}/{currentAd.path2}</span> - {displayDesc1} {displayDesc2}
                    </p>
                  </div>
                )
              ) : currentAd.platform === "meta" ? (
                // META FACEBOOK/INSTAGRAM PREVIEW
                <div className="w-[325px] bg-[#18191a] border border-gray-800 rounded-2xl overflow-hidden shadow-lg text-right" dir="rtl">
                  {/* Post Header */}
                  <div className="p-3 flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <div className="w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center text-white font-bold text-xs">A</div>
                      <div>
                        <h4 className="text-xs font-bold text-white">متجرك الإلكتروني</h4>
                        <p className="text-[9px] text-gray-500">إعلان ممول · 🌐</p>
                      </div>
                    </div>
                    <span className="text-gray-450 text-sm font-bold cursor-default">···</span>
                  </div>

                  {/* Primary text */}
                  <p className="px-3 pb-2 text-[11px] text-gray-200 leading-normal whitespace-pre-line">
                    {currentAd.primary_text}
                  </p>

                  {/* Image */}
                  {currentAd.image_url ? (
                    <div className="w-full h-48 bg-gray-900 relative">
                      <img src={currentAd.image_url} alt="Ad Visual" className="w-full h-full object-cover" />
                    </div>
                  ) : (
                    <div className="w-full h-48 bg-gray-850 flex items-center justify-center text-gray-600 text-xs">معاينة الصورة</div>
                  )}

                  {/* Bottom bar */}
                  <div className="p-3 bg-[#242526] flex items-center justify-between border-t border-gray-800">
                    <div className="space-y-0.5">
                      <p className="text-[9px] text-gray-500 uppercase">{currentAd.display_url}</p>
                      <h4 className="text-xs font-bold text-white">{currentAd.headlines[0]}</h4>
                      <p className="text-[10px] text-gray-400">{currentAd.descriptions[0]}</p>
                    </div>
                    <button className="bg-[#3a3b3c] hover:bg-[#4e4f50] text-white font-semibold text-[10px] px-3 py-1.5 rounded-lg">
                      {currentAd.cta_button}
                    </button>
                  </div>

                  {/* Social indicators */}
                  <div className="px-3 py-2 flex items-center justify-between text-gray-400 border-t border-gray-800 text-[10px] bg-[#18191a]">
                    <span className="flex items-center gap-1 text-blue-400"><ThumbsUp className="w-3.5 h-3.5" /> 2.4 ألف</span>
                    <div className="flex gap-3">
                      <span>42 تعليقاً</span>
                      <span>12 مشاركة</span>
                    </div>
                  </div>
                </div>
              ) : currentAd.platform === "tiktok" ? (
                // TIKTOK VERTICAL VIDEO PREVIEW
                <div className="w-[280px] h-[480px] bg-black rounded-3xl overflow-hidden relative shadow-2xl text-right" dir="rtl">
                  {/* Video Mockup (Background) */}
                  {currentAd.image_url ? (
                    <img src={currentAd.image_url} alt="TikTok Background" className="absolute inset-0 w-full h-full object-cover opacity-80" />
                  ) : (
                    <div className="absolute inset-0 bg-gray-950" />
                  )}

                  {/* Top Header */}
                  <div className="absolute top-4 inset-x-0 flex justify-center gap-4 text-xs font-semibold text-gray-400 z-10">
                    <span>متابعون</span>
                    <span className="text-white border-b-2 border-white pb-1">لك (For You)</span>
                  </div>

                  {/* Right side interaction buttons */}
                  <div className="absolute right-3 bottom-24 flex flex-col items-center gap-4 z-10">
                    <div className="w-9 h-9 rounded-full border border-white bg-white/10 flex items-center justify-center text-white"><User className="w-4 h-4" /></div>
                    <div className="flex flex-col items-center"><Heart className="w-6 h-6 text-white fill-white" /><span className="text-[9px] text-white font-bold mt-0.5">84.2K</span></div>
                    <div className="flex flex-col items-center"><MessageCircle className="w-6 h-6 text-white fill-white" /><span className="text-[9px] text-white font-bold mt-0.5">420</span></div>
                    <div className="flex flex-col items-center"><Share2 className="w-6 h-6 text-white fill-white" /><span className="text-[9px] text-white font-bold mt-0.5">18K</span></div>
                  </div>

                  {/* Bottom Text Details */}
                  <div className="absolute bottom-4 left-3 right-16 space-y-2 z-10 text-white drop-shadow">
                    <h4 className="font-bold text-xs">@my_brand <span className="bg-red-600 text-white font-bold text-[8px] px-1 py-0.2 rounded">ممول</span></h4>
                    <p className="text-[10px] text-gray-100 leading-normal line-clamp-3">{currentAd.primary_text}</p>
                    
                    {/* CTA Button Block */}
                    <div className="bg-[#fe2c55] hover:bg-[#e02447] text-white font-bold text-center text-xs py-2 rounded-lg flex items-center justify-between px-3">
                      <span>{currentAd.cta_button}</span>
                      <ChevronUp className="w-4 h-4" />
                    </div>
                  </div>
                </div>
              ) : currentAd.platform === "linkedin" ? (
                // LINKEDIN B2B SPONSORED CONTENT
                <div className="w-[325px] bg-[#1b1f23] border border-gray-800 rounded-xl overflow-hidden shadow-lg text-right" dir="rtl">
                  {/* LinkedIn Header */}
                  <div className="p-3 flex items-start gap-2.5">
                    <div className="w-8 h-8 rounded bg-gray-600 flex items-center justify-center text-white font-bold text-xs">LI</div>
                    <div className="flex-1">
                      <h4 className="text-xs font-bold text-white flex items-center gap-1">
                        <span>الشركة الاستشارية</span>
                        <span className="w-1 h-1 rounded-full bg-gray-500" />
                        <span className="text-[9px] text-gray-500 font-normal">درجة أولى</span>
                      </h4>
                      <p className="text-[9px] text-gray-500">240,000 متابع</p>
                      <p className="text-[8px] text-gray-500 flex items-center gap-0.5">مروج · 🌐</p>
                    </div>
                  </div>

                  {/* Primary text */}
                  <p className="px-3 pb-2 text-[10.5px] text-gray-200 leading-normal whitespace-pre-line">
                    {currentAd.primary_text}
                  </p>

                  {/* Image banner */}
                  {currentAd.image_url ? (
                    <div className="w-full h-40 bg-gray-900 relative">
                      <img src={currentAd.image_url} alt="LinkedIn Banner" className="w-full h-full object-cover" />
                    </div>
                  ) : (
                    <div className="w-full h-40 bg-gray-850 flex items-center justify-center text-gray-600 text-xs">معاينة البانر</div>
                  )}

                  {/* Bottom bar */}
                  <div className="p-3 bg-[#2b3137] flex items-center justify-between border-t border-gray-800">
                    <div className="space-y-0.5">
                      <h4 className="text-[11px] font-bold text-white leading-tight">{currentAd.headlines[0]}</h4>
                      <p className="text-[9px] text-gray-400">{currentAd.display_url}</p>
                    </div>
                    <button className="border border-blue-400 text-blue-400 hover:bg-blue-400/10 font-bold text-[10px] px-3.5 py-1 rounded-full">
                      {currentAd.cta_button}
                    </button>
                  </div>
                </div>
              ) : currentAd.platform === "x" ? (
                // X (TWITTER) PROMOTED TWEET
                <div className="w-[320px] bg-black border border-gray-800 rounded-2xl p-4 space-y-2.5 text-right shadow-lg" dir="rtl">
                  {/* Twitter Header */}
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <div className="w-8 h-8 rounded-full bg-gray-800 flex items-center justify-center text-white font-bold text-xs">X</div>
                      <div>
                        <h4 className="text-xs font-bold text-white flex items-center gap-1">
                          <span>براند الأعمال</span>
                          <span className="text-blue-400" title="موثق">✓</span>
                        </h4>
                        <p className="text-[9px] text-gray-500">@BusinessBrand</p>
                      </div>
                    </div>
                  </div>

                  {/* Tweet content */}
                  <p className="text-[11.5px] text-gray-100 leading-normal whitespace-pre-line">
                    {currentAd.primary_text}
                  </p>

                  {/* Embedded image card */}
                  {currentAd.image_url && (
                    <div className="border border-gray-800 rounded-2xl overflow-hidden bg-gray-900 w-full h-40 relative">
                      <img src={currentAd.image_url} alt="X Card" className="w-full h-full object-cover" />
                      
                      {/* CTA label on image bottom */}
                      <div className="absolute bottom-0 inset-x-0 bg-black/60 p-2 flex justify-between items-center text-[10px] text-white">
                        <span>{currentAd.headlines[0]}</span>
                        <span className="bg-white text-black font-bold px-2 py-0.5 rounded-full">{currentAd.cta_button}</span>
                      </div>
                    </div>
                  )}

                  {/* Promoted badge */}
                  <div className="text-[9px] text-gray-500 flex items-center gap-1 pt-1.5 border-t border-gray-900">
                    <span>↗ ممول</span>
                  </div>
                </div>
              ) : (
                // SNAPCHAT STORY AD
                <div className="w-[280px] h-[480px] bg-[#fffc00] rounded-3xl overflow-hidden relative shadow-2xl text-right text-black font-semibold" dir="rtl">
                  {/* Visual Background */}
                  {currentAd.image_url ? (
                    <img src={currentAd.image_url} alt="Snapchat Story" className="absolute inset-0 w-full h-full object-cover opacity-90" />
                  ) : (
                    <div className="absolute inset-0 bg-yellow-400" />
                  )}

                  {/* Top Bar info */}
                  <div className="absolute top-4 left-3 right-3 flex items-center justify-between text-[10px] text-white drop-shadow z-10">
                    <div className="flex items-center gap-2">
                      <div className="w-7 h-7 rounded-full bg-white/20 flex items-center justify-center font-bold">S</div>
                      <div>
                        <h4 className="font-bold">اسم متجرك</h4>
                        <p className="text-[8px] opacity-75">ممول</p>
                      </div>
                    </div>
                  </div>

                  {/* Bottom SWIPE UP banner */}
                  <div className="absolute bottom-5 inset-x-0 flex flex-col items-center justify-center text-white drop-shadow z-10 space-y-1">
                    <ChevronUp className="w-5 h-5 animate-bounce" />
                    <button className="bg-white/25 backdrop-blur-md border border-white/20 font-bold px-6 py-2 rounded-full text-xs hover:bg-white/40 transition-all uppercase tracking-wide">
                      {currentAd.cta_button}
                    </button>
                    <p className="text-[8px] opacity-75 tracking-wider">{currentAd.display_url}</p>
                  </div>
                </div>
              )}
            </div>
          </div>

        </div>
      )}
    </div>
  );
}
