"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { createClient } from "@/lib/supabase/client";
import { motion, AnimatePresence } from "framer-motion";
import {
  Bot, Rocket, Key, SquarePen, ChevronLeft, ChevronRight,
  Loader2, Check, Sparkles, Settings, Globe,
  Users, ArrowRight
} from "lucide-react";
import { AI_MODELS, type AIProvider } from "@/lib/ai/models";
import { cn, formatNumber } from "@/lib/utils";
import { usePlatform, type PlatformType } from "@/lib/context/PlatformContext";

interface FormData {
  businessName: string;
  businessDescription: string;
  targetAudience: string;
  campaignType: string;
  budget: number;
  targetLocations: string;
  language: string;
  goal: string;
  aiProvider: AIProvider;
  aiModel: string;
}

const initialForm: FormData = {
  businessName: "",
  businessDescription: "",
  targetAudience: "",
  campaignType: "search",
  budget: 1000,
  targetLocations: "المملكة العربية السعودية",
  language: "ar",
  goal: "conversions",
  aiProvider: "gemini",
  aiModel: "gemini-1.5-flash",
};

interface AIResult {
  keywords?: { keyword: string; matchType: string; searchVolume: string; intent: string; suggestedBid: number }[];
  audiences?: { interest_name: string; age_range: string; gender: string; estimated_reach: number; relevance_score: number }[];
  negativeKeywords?: string[];
  headlines?: { text: string; charCount: number; type?: string }[];
  descriptions?: { text: string; charCount: number }[];
  primaryText?: string;
  ctaButton?: string;
  imageUrl?: string;
}

// Campaign types mapped dynamically to each network
const platformCampaignTypes: Record<PlatformType, { id: string; label: string; icon: string; desc: string }[]> = {
  all: [
    { id: "search", label: "إعلان بحث موحد", icon: "🔍", desc: "إعلانات جوجل وبينج النصية" },
    { id: "conversion", label: "حملة تحويلات اجتماعية", icon: "🎯", desc: "زيادة مبيعات فيسبوك وتيك توك" },
  ],
  google: [
    { id: "search", label: "حملة بحث", icon: "🔍", desc: "إعلانات نصية على محرك البحث" },
    { id: "pmax", label: "الأداء الأقصى PMax", icon: "⚡", desc: "تغطية كامل قنوات Google بالـ AI" },
    { id: "video", label: "إعلان فيديو", icon: "🎬", desc: "زيادة المشاهدات على YouTube" },
    { id: "shopping", label: "حملة تسوق", icon: "🛍️", desc: "ترويج منتجات المتاجر الإلكترونية" },
  ],
  meta: [
    { id: "conversion", label: "حملة تحويلات", icon: "🎯", desc: "زيادة مبيعات Facebook و Instagram" },
    { id: "engagement", label: "زيادة التفاعل", icon: "❤️", desc: "الحصول على إعجابات ومشاركات للمنشورات" },
    { id: "traffic", label: "زيارات الموقع", icon: "🌐", desc: "جلب زيارات كثيفة لصفحة الهبوط" },
  ],
  tiktok: [
    { id: "spark", label: "Spark Ads فيديو", icon: "🎵", desc: "ترويج فيديوهات صناع المحتوى والـ Trends" },
    { id: "traffic", label: "زيارات الموقع", icon: "🌐", desc: "توجيه المتصفحين لمتجرك مباشرة" },
    { id: "engagement", label: "تفاعلات ومتابعين", icon: "❤️", desc: "توسيع نطاق المتابعة والانتشار" },
  ],
  microsoft: [
    { id: "search", label: "Bing بحث نصي", icon: "🔍", desc: "إعلانات الكلمات المفتاحية على Bing" },
    { id: "shopping", label: "تسوق Bing", icon: "🛍️", desc: "عرض كتالوج المنتجات على شبكة MSN" },
  ],
  linkedin: [
    { id: "lead_gen", label: "جذب عملاء B2B", icon: "👔", desc: "نماذج جمع بيانات الشركات والمدراء" },
    { id: "traffic", label: "زيارات مهنية", icon: "🌐", desc: "جذب النخبة وأصحاب القرار لموقعك" },
  ],
  x: [
    { id: "promoted_post", label: "تغريدة ترويجية", icon: "🐦", desc: "زيادة الوصول والتفاعل مع تغريداتك" },
    { id: "traffic", label: "نقرات الرابط", icon: "🌐", desc: "توجيه جماهير X لمتجرك أو مدونتك" },
  ],
  snapchat: [
    { id: "swipe_up", label: "سحب شاشة قصة", icon: "👻", desc: "إعلانات القصص السريعة لزيادة المبيعات" },
    { id: "traffic", label: "زيارات فلاتر", icon: "🌐", desc: "توجيه مستخدمي سناب لصفحات الهبوط" },
  ],
};

export default function AIGeneratorPage() {
  const { currentPlatform, config, setPlatform } = usePlatform();
  const isSearch = currentPlatform === "google" || currentPlatform === "microsoft" || currentPlatform === "all";
  const router = useRouter();
  const supabase = createClient();

  const [currentStep, setCurrentStep] = useState(1);
  const [form, setForm] = useState<FormData>({
    ...initialForm,
    campaignType: platformCampaignTypes[currentPlatform]?.[0]?.id || "search"
  });
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [user, setUser] = useState<any>(null);
  const [result, setResult] = useState<AIResult | null>(null);
  const [activeResultTab, setActiveResultTab] = useState<"keywords" | "ads">("keywords");
  const [launchSuccess, setLaunchSuccess] = useState<any | null>(null);

  // Load 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 in AI generator, using offline developer mode:", err);
        handleFallback();
      });
  }, []);

  // Keep type aligned if user changes platform context in sidebar
  useEffect(() => {
    const firstType = platformCampaignTypes[currentPlatform]?.[0]?.id || "search";
    setForm((prev) => (prev.campaignType === firstType ? prev : { ...prev, campaignType: firstType }));
  }, [currentPlatform]);

  async function handleSaveAndLaunchCampaign() {
    if (!result) return;
    setSaving(true);
    try {
      const campaignName = `${form.businessName} - حملة AI`;

      if (currentPlatform === "google") {
        const response = await fetch("/api/google-ads/create-campaign", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            campaignName,
            campaignType: form.campaignType,
            budgetAmount: form.budget,
            biddingStrategy: "MAXIMIZE_CONVERSIONS",
            keywords: result.keywords?.map(k => k.keyword) || [],
            headlines: result.headlines?.map(h => h.text) || [],
            descriptions: result.descriptions?.map(d => d.text) || [],
            finalUrl: "https://example.com",
            targetLocations: [form.targetLocations],
          })
        });

        const data = await response.json();
        if (!response.ok) {
          throw new Error(data.error || "حدث خطأ أثناء إطلاق الحملة على Google Ads.");
        }

        setLaunchSuccess(data);
        return;
      }

      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";

      const userId = user?.id || "00000000-0000-0000-0000-000000000000";

      if (isPlaceholder) {
        const newCampaignId = "c_" + Date.now() + "_" + Math.floor(Math.random() * 1000);
        
        // 1. Save campaign
        const localCampaignsStr = localStorage.getItem("local_campaigns");
        const existingCampaigns = localCampaignsStr ? JSON.parse(localCampaignsStr) : [];
        const newCampaign = {
          id: newCampaignId,
          name: campaignName,
          platform: currentPlatform,
          type: form.campaignType,
          status: "active",
          budget_amount: form.budget,
          budget_type: "daily",
          currency: "USD",
          ai_generated: true,
          clicks: 0,
          impressions: 0,
          conversions: 0,
          cost: 0,
          created_at: new Date().toISOString()
        };
        localStorage.setItem("local_campaigns", JSON.stringify([newCampaign, ...existingCampaigns]));

        // 2. Save keywords / audiences
        const localKeywordsStr = localStorage.getItem("local_keywords");
        const existingKeywords = localKeywordsStr ? JSON.parse(localKeywordsStr) : [];
        
        let newKeywords: any[] = [];
        if (isSearch) {
          newKeywords = (result.keywords || []).map((kw) => ({
            id: "k_" + Math.random().toString(36).substr(2, 9),
            campaign_id: newCampaignId,
            keyword: kw.keyword,
            match_type: kw.matchType || "phrase",
            status: "active",
            max_cpc: kw.suggestedBid || 1.5,
            quality_score: 10,
            impressions: 0,
            clicks: 0,
            conversions: 0,
            cost: 0,
            ai_suggested: true,
            platform: currentPlatform
          }));
        } else {
          newKeywords = (result.audiences || []).map((aud) => ({
            id: "a_" + Math.random().toString(36).substr(2, 9),
            campaign_id: newCampaignId,
            keyword: aud.interest_name,
            match_type: `${aud.age_range || "18-45"} | ${aud.gender || "all"}`,
            status: "active",
            max_cpc: 1.0,
            quality_score: aud.relevance_score || 9,
            impressions: aud.estimated_reach || 1200000,
            clicks: 0,
            conversions: 0,
            cost: 0,
            ai_suggested: true,
            platform: currentPlatform
          }));
        }
        localStorage.setItem("local_keywords", JSON.stringify([...newKeywords, ...existingKeywords]));

        // 3. Save ad creatives
        const localAdsStr = localStorage.getItem("local_ad_creatives");
        const existingAds = localAdsStr ? JSON.parse(localAdsStr) : [];
        const newAd = {
          id: "ad_" + Math.random().toString(36).substr(2, 9),
          campaign_id: newCampaignId,
          platform: currentPlatform,
          type: isSearch ? "responsive_search" : "responsive_display",
          headlines: result.headlines?.map(h => ({ text: h.text })) || [],
          descriptions: result.descriptions?.map(d => ({ text: d.text })) || [],
          final_url: isSearch ? "https://google.com" : "",
          display_url: isSearch ? "google.com" : "",
          path1: "",
          path2: "",
          primary_text: result.primaryText || "",
          cta_button: result.ctaButton || "تسوّق الآن",
          image_url: result.imageUrl || "",
          impressions: 0,
          clicks: 0,
          conversions: 0
        };
        localStorage.setItem("local_ad_creatives", JSON.stringify([newAd, ...existingAds]));

        // 4. Save AI generation history log
        const localGenerationsStr = localStorage.getItem("local_ai_generations");
        const existingGenerations = localGenerationsStr ? JSON.parse(localGenerationsStr) : [];
        const newGen = {
          id: "gen_" + Math.random().toString(36).substr(2, 9),
          user_id: userId,
          campaign_id: newCampaignId,
          provider: form.aiProvider,
          model: form.aiModel,
          type: "campaign",
          prompt: form.businessDescription,
          result: result,
          created_at: new Date().toISOString()
        };
        localStorage.setItem("local_ai_generations", JSON.stringify([newGen, ...existingGenerations]));

      } else {
        // Save to Supabase database
        // 1. Ensure ad account exists
        let adAccountId;
        const { data: accounts, error: accountsError } = await supabase
          .from("ad_accounts")
          .select("id")
          .limit(1);
        
        if (accountsError) throw accountsError;

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

        // 2. Insert Campaign
        const { data: campaign, error: campError } = await supabase
          .from("campaigns")
          .insert({
            user_id: userId,
            ad_account_id: adAccountId,
            name: campaignName,
            platform: currentPlatform,
            type: form.campaignType,
            status: "active",
            budget_amount: form.budget,
            budget_type: "daily",
            currency: "USD",
            ai_generated: true,
            ai_provider: form.aiProvider,
            ai_model: form.aiModel,
            target_locations: [form.targetLocations],
            target_languages: ["ar"],
          })
          .select("id")
          .single();

        if (campError || !campaign) throw campError || new Error("Failed to create campaign in database");

        // 3. Insert Keywords / Audiences
        if (isSearch) {
          const kwsToInsert = (result.keywords || []).map((kw) => ({
            campaign_id: campaign.id,
            user_id: userId,
            keyword: kw.keyword,
            match_type: kw.matchType || "phrase",
            status: "active",
            max_cpc: kw.suggestedBid || 1.5,
            quality_score: 10,
            ai_suggested: true
          }));
          const { error: kwErr } = await supabase.from("keywords").insert(kwsToInsert);
          if (kwErr) throw kwErr;
        } else {
          const audsToInsert = (result.audiences || []).map((aud) => ({
            campaign_id: campaign.id,
            user_id: userId,
            keyword: aud.interest_name,
            match_type: `${aud.age_range || "18-45"} | ${aud.gender || "all"}`,
            status: "active",
            max_cpc: 1.0,
            quality_score: aud.relevance_score || 9,
            impressions: aud.estimated_reach || 1200000,
            ai_suggested: true
          }));
          const { error: audErr } = await supabase.from("keywords").insert(audsToInsert);
          if (audErr) throw audErr;
        }

        // 4. Insert Ad Creative
        const creativeInsert = {
          campaign_id: campaign.id,
          user_id: userId,
          type: isSearch ? "responsive_search" : "responsive_display",
          status: "active",
          headlines: result.headlines?.map(h => ({ text: h.text })) || [],
          descriptions: result.descriptions?.map(d => ({ text: d.text })) || [],
          final_url: isSearch ? "https://google.com" : "",
          display_url: isSearch ? "google.com" : "",
          images: isSearch ? {} : {
            primary_text: result.primaryText || "",
            cta_button: result.ctaButton || "تسوّق الآن",
            image_url: result.imageUrl || ""
          },
          ai_generated: true,
          ai_provider: form.aiProvider,
          ai_model: form.aiModel,
        };
        const { error: adErr } = await supabase.from("ad_creatives").insert(creativeInsert);
        if (adErr) throw adErr;

        // 5. Log to ai_generations
        const { error: genErr } = await supabase.from("ai_generations").insert({
          user_id: userId,
          campaign_id: campaign.id,
          provider: form.aiProvider,
          model: form.aiModel,
          type: "campaign",
          prompt: form.businessDescription,
          result: result
        });
        if (genErr) throw genErr;
      }

      router.push("/dashboard/campaigns");
    } catch (err: any) {
      console.error("Failed to save campaign:", err);
      alert(err.message || "حدث خطأ أثناء حفظ الحملة. يرجى المحاولة مرة أخرى.");
    } finally {
      setSaving(false);
    }
  }

  const availableModels = AI_MODELS.filter((m) => m.provider === form.aiProvider);
  const campaignTypes = platformCampaignTypes[currentPlatform] || platformCampaignTypes.all;

  // Step names dynamically adapt to search vs social
  const steps = [
    { id: 1, title: "معلومات العمل", icon: Settings },
    { id: 2, title: "اختيار AI", icon: Bot },
    { id: 3, title: isSearch ? "الكلمات المفتاحية" : "استهداف الجماهير", icon: isSearch ? Key : Users },
    { id: 4, title: "نصوص الإعلان", icon: SquarePen },
    { id: 5, title: "الإطلاق بالـ AI", icon: Rocket },
  ];

  function updateForm(key: keyof FormData, value: string | number) {
    setForm((prev) => ({ ...prev, [key]: value }));
    if (key === "aiProvider") {
      const firstModel = AI_MODELS.find((m) => m.provider === (value as AIProvider));
      if (firstModel) setForm((prev) => ({ ...prev, aiProvider: value as AIProvider, aiModel: firstModel.id }));
    }
  }

  async function generateWithAI() {
    setLoading(true);
    setResult(null);
    try {
      const res = await fetch("/api/ai/generate-campaign", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          provider: form.aiProvider,
          model: form.aiModel,
          businessName: form.businessName,
          businessDescription: form.businessDescription,
          targetAudience: form.targetAudience,
          campaignType: form.campaignType,
          budget: form.budget,
          targetLocations: [form.targetLocations],
          language: form.language,
          goal: form.goal,
          platform: currentPlatform, // pass active platform context
        }),
      });

      const data = await res.json();
      
      // If it's a social platform, map keywords array to audiences structure
      if (!isSearch && data.keywords) {
        const mappedAuds = data.keywords.map((k: any, idx: number) => ({
          interest_name: k.keyword,
          age_range: "18-45",
          gender: "all",
          estimated_reach: Math.floor(800000 + Math.random() * 2000000),
          relevance_score: 9 - (idx % 3),
        }));
        setResult({
          audiences: mappedAuds,
          primaryText: data.adGroups?.[0]?.name 
            ? `✨ خصومات كبرى على ${form.businessName}! ${form.businessDescription}. تسوق أرقى المنتجات الحصرية الآن بنصف السعر وشحن مجاني وسريع.`
            : "شاهد العروض الفاخرة المتاحة اليوم فقط! شحن مجاني ودفع عند الاستلام بالمملكة.",
          headlines: [{ text: data.headlines?.[0]?.text || `شراء عطور ${form.businessName} الفاخرة`, charCount: 30 }],
          ctaButton: "تسوّق الآن",
          imageUrl: "https://images.unsplash.com/photo-1547887537-6158d64c35b3?auto=format&fit=crop&q=80&w=600",
        });
      } else {
        setResult(data);
      }
      
      setCurrentStep(5);
    } catch (err) {
      console.error("AI generation failed:", err);
      // Fallback mocks
      if (!isSearch) {
        setResult({
          audiences: [
            { interest_name: `المهتمين بعطور وتجميل ${form.businessName}`, age_range: "18-35", gender: "all", estimated_reach: 1200000, relevance_score: 9 },
            { interest_name: `سلوك تسوق إلكتروني نشط بالسعودية`, age_range: "22-45", gender: "all", estimated_reach: 3400000, relevance_score: 8 },
          ],
          primaryText: `✨ عرض حصري ومميز من ${form.businessName}! احصل على منتجاتنا الفاخرة اليوم بخصم 50% مع شحن مجاني تماماً ودفع آمن عند الاستلام. تسوق الآن 👇`,
          headlines: [{ text: `${form.businessName} - عطور ملوكية فاخرة`, charCount: 28 }],
          ctaButton: "تسوّق الآن",
          imageUrl: "https://images.unsplash.com/photo-1547887537-6158d64c35b3?auto=format&fit=crop&q=80&w=600"
        });
      } else {
        setResult({
          keywords: [
            { keyword: `شراء عطورات ${form.businessName}`, matchType: "phrase", searchVolume: "high", intent: "purchase", suggestedBid: 1.2 },
            { keyword: `أفضل عود وبخور بالسعودية`, matchType: "exact", searchVolume: "high", intent: "purchase", suggestedBid: 2.1 }
          ],
          headlines: [{ text: `عطور ${form.businessName} الفاخرة | خصم 50%`, charCount: 30 }],
          descriptions: [{ text: `تسوّق أفخم العطور والروائح الشرقية والفرنسية الأصلية. شحن سريع ومجاني للطلبات.`, charCount: 84 }]
        });
      }
      setCurrentStep(5);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="p-6 max-w-4xl mx-auto text-right" dir="rtl">
      
      {/* Header */}
      <div className="mb-8 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white flex items-center gap-2">
            <Bot className="w-6 h-6 text-purple-400" />
            <span>منشئ حملات الـ AI - {config.name}</span>
          </h1>
          <p className="text-[#8a8380] text-sm mt-1">
            بناء وتوليد وتصميم استراتيجيات الحملات الإعلانية فائقة الدقة لـ {config.name} بالذكاء الاصطناعي
          </p>
        </div>
        
        {currentPlatform !== "all" && (
          <button
            onClick={() => setPlatform("all")}
            className="flex items-center gap-1.5 text-xs text-gray-500 hover:text-white"
          >
            <span>العودة للرئيسية</span>
            <ArrowRight className="w-3.5 h-3.5" />
          </button>
        )}
      </div>

      {launchSuccess ? (
        <motion.div
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          className="bg-[#101010] border border-gray-800 rounded-2xl p-8 max-w-xl mx-auto text-center space-y-6"
        >
          <div className="w-16 h-16 bg-emerald-500/10 border border-emerald-500/30 rounded-full flex items-center justify-center mx-auto shadow-lg shadow-emerald-500/5">
            <Check className="w-8 h-8 text-emerald-400" />
          </div>
          
          <div className="space-y-2">
            <h2 className="text-xl font-bold text-white">تم إطلاق الحملة بنجاح! 🎉</h2>
            <p className="text-gray-400 text-xs max-w-md mx-auto leading-relaxed">
              {launchSuccess.message}
            </p>
          </div>

          <div className="bg-[#161b27] border border-gray-850 rounded-xl p-4 max-w-md mx-auto text-right text-xs space-y-2.5">
            <div className="flex justify-between border-b border-gray-850 pb-2">
              <span className="text-gray-500">اسم الحملة:</span>
              <span className="text-white font-bold">{form.businessName} - حملة AI</span>
            </div>
            <div className="flex justify-between border-b border-gray-850 pb-2">
              <span className="text-gray-500">معرّف الحملة (Google ID):</span>
              <span className="text-purple-400 font-mono font-bold">{launchSuccess.data.campaignId || "حملة تجريبية"}</span>
            </div>
            <div className="flex justify-between border-b border-gray-850 pb-2">
              <span className="text-gray-500">طريقة البناء:</span>
              <span className="text-blue-400 font-bold">{launchSuccess.mode === "live" ? "إطلاق مباشر حقيقي" : "محاكاة (وضع التطوير)"}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-500">العناصر المضافة:</span>
              <span className="text-white font-bold">{launchSuccess.data.keywordsCount} كلمات مفتاحية + إعلان نصي</span>
            </div>
          </div>

          <div className="flex items-center justify-center gap-3">
            <a
              href={launchSuccess.data.googleAdsUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center gap-2 bg-blue-600 hover:bg-blue-500 text-white font-bold px-6 py-2.5 rounded-xl text-xs transition-all cursor-pointer"
            >
              <Globe className="w-4 h-4" />
              <span>فتح في لوحة Google Ads</span>
            </a>
            <button
              onClick={() => {
                setLaunchSuccess(null);
                setResult(null);
                setCurrentStep(1);
                setForm({
                  ...initialForm,
                  campaignType: platformCampaignTypes[currentPlatform]?.[0]?.id || "search"
                });
              }}
              className="bg-gray-850 hover:bg-gray-800 border border-gray-800 text-white font-bold px-5 py-2.5 rounded-xl text-xs transition-all cursor-pointer"
            >
              إنشاء حملة جديدة
            </button>
          </div>
        </motion.div>
      ) : (
        <>
          {/* Progress Steps */}
      <div className="flex items-center gap-0 mb-10 overflow-x-auto pb-2">
        {steps.map((step, i) => (
          <div key={step.id} className="flex items-center flex-shrink-0">
            <button
              onClick={() => step.id <= currentStep && setCurrentStep(step.id)}
              className={cn(
                "flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium transition-all",
                currentStep === step.id
                  ? "bg-purple-500/10 text-purple-400 border border-purple-500/20"
                  : step.id < currentStep
                  ? "text-emerald-400 cursor-pointer hover:bg-emerald-500/5"
                  : "text-gray-600 cursor-not-allowed"
              )}
            >
              <div className={cn(
                "w-6 h-6 rounded-full flex items-center justify-center text-xs",
                currentStep === step.id ? "bg-purple-500 text-white font-bold" :
                step.id < currentStep ? "bg-emerald-500 text-white font-bold" : "bg-gray-800 text-gray-600"
              )}>
                {step.id < currentStep ? <Check className="w-3 h-3" /> : step.id}
              </div>
              <span className="hidden sm:block font-semibold">{step.title}</span>
            </button>
            {i < steps.length - 1 && (
              <div className={cn("w-6 h-px mx-1", step.id < currentStep ? "bg-emerald-500/50" : "bg-gray-800")} />
            )}
          </div>
        ))}
      </div>

      {/* Step Content */}
      <AnimatePresence mode="wait">
        <motion.div
          key={currentStep}
          initial={{ opacity: 0, x: 20 }}
          animate={{ opacity: 1, x: 0 }}
          exit={{ opacity: 0, x: -20 }}
          className="bg-[#101010] border border-gray-800 rounded-2xl p-6"
        >
          {/* Step 1: Business Info */}
          {currentStep === 1 && (
            <div className="space-y-5">
              <h2 className="text-lg font-bold text-white">معلومات الفكرة والنشاط التجاري</h2>
              
              <div>
                <label className="block text-xs text-[#b8b3b0] mb-2 font-bold">اسم العمل / متجرك أو شركتك *</label>
                <input
                  value={form.businessName}
                  onChange={(e) => updateForm("businessName", e.target.value)}
                  placeholder="مثال: قصر العود الملكي"
                  className="w-full bg-[#161b27] border border-gray-700 focus:border-purple-500 text-white rounded-xl py-3 px-4 text-xs outline-none transition-colors"
                />
              </div>

              <div>
                <label className="block text-xs text-[#b8b3b0] mb-2 font-bold">وصف فكرة عملك أو عرضك التسويقي بالتفصيل *</label>
                <textarea
                  value={form.businessDescription}
                  onChange={(e) => updateForm("businessDescription", e.target.value)}
                  placeholder="اشرح منتجاتك، مميزاتها الفريدة، وعرض الخصم الذي تود إطلاقه بالكامل..."
                  rows={4}
                  className="w-full bg-[#161b27] border border-gray-700 focus:border-purple-500 text-white rounded-xl py-3 px-4 text-xs outline-none transition-colors resize-none leading-relaxed"
                />
              </div>

              <div>
                <label className="block text-xs text-[#b8b3b0] mb-2 font-bold">شريحة العملاء المستهدفة الفعالة *</label>
                <input
                  value={form.targetAudience}
                  onChange={(e) => updateForm("targetAudience", e.target.value)}
                  placeholder="مثال: رجال ونساء 20-50 مهتمين بالبخور والعود ودهن العود الفاخر"
                  className="w-full bg-[#161b27] border border-gray-700 focus:border-purple-500 text-white rounded-xl py-3 px-4 text-xs outline-none transition-colors"
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs text-[#b8b3b0] mb-2 font-bold">الموقع الجغرافي المستهدف</label>
                  <input
                    value={form.targetLocations}
                    onChange={(e) => updateForm("targetLocations", e.target.value)}
                    placeholder="المملكة العربية السعودية، الرياض، الخليج..."
                    className="w-full bg-[#161b27] border border-gray-700 focus:border-purple-500 text-white rounded-xl py-3 px-4 text-xs outline-none transition-colors"
                  />
                </div>
                <div>
                  <label className="block text-xs text-[#b8b3b0] mb-2 font-bold">الميزانية الشهرية المقترحة ($)</label>
                  <input
                    type="number"
                    value={form.budget}
                    onChange={(e) => updateForm("budget", parseInt(e.target.value) || 0)}
                    className="w-full bg-[#161b27] border border-gray-700 focus:border-purple-500 text-white rounded-xl py-3 px-4 text-xs outline-none transition-colors"
                  />
                </div>
              </div>

              <div>
                <label className="block text-xs text-[#b8b3b0] mb-3 font-bold">نوع الحملة التسويقية لـ {config.name} *</label>
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
                  {campaignTypes.map((type) => (
                    <button
                      key={type.id}
                      onClick={() => updateForm("campaignType", type.id)}
                      className={cn(
                        "p-4 rounded-xl border text-right transition-all flex flex-col justify-between min-h-[90px]",
                        form.campaignType === type.id
                          ? "border-purple-500 bg-purple-500/10"
                          : "border-gray-800 bg-[#161b27] hover:border-gray-700"
                      )}
                    >
                      <div className="flex items-center justify-between w-full">
                        <span className="text-xl">{type.icon}</span>
                        {form.campaignType === type.id && <span className="text-[10px] bg-purple-500/20 text-purple-400 px-1.5 py-0.5 rounded">محدد</span>}
                      </div>
                      <div className="mt-2">
                        <p className={cn("text-xs font-bold", form.campaignType === type.id ? "text-purple-400" : "text-white")}>
                          {type.label}
                        </p>
                        <p className="text-[9px] text-gray-500 mt-0.5">{type.desc}</p>
                      </div>
                    </button>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* Step 2: AI Selection */}
          {currentStep === 2 && (
            <div className="space-y-5">
              <h2 className="text-lg font-bold text-white">اختر نموذج العقل المفكر AI</h2>
              <p className="text-[#8a8380] text-xs">سيتولى النموذج المختار كتابة إعلانك وهندسة جمهورك بالكامل</p>

              <div>
                <label className="block text-xs text-[#b8b3b0] mb-3 font-bold">مزود الخدمة والذكاء الاصطناعي</label>
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
                  {["openai", "claude", "gemini", "deepseek", "qwen", "manus", "ollama"].map((provider) => (
                    <button
                      key={provider}
                      onClick={() => updateForm("aiProvider", provider)}
                      className={cn(
                        "p-3 rounded-xl border transition-all text-xs font-semibold",
                        form.aiProvider === provider
                          ? "border-purple-500 bg-purple-500/10 text-purple-400 font-bold shadow-md shadow-purple-500/5"
                          : "border-gray-800 bg-[#161b27] text-[#8a8380] hover:border-gray-700"
                      )}
                    >
                      {provider === "ollama" ? "🖥️ Ollama (محلي)" :
                       provider === "openai" ? "🤖 OpenAI" :
                       provider === "claude" ? "🔷 Claude" :
                       provider === "gemini" ? "✨ Gemini" :
                       provider === "deepseek" ? "🌊 DeepSeek" :
                       provider === "qwen" ? "🌐 Qwen" : "⚡ Manus"}
                    </button>
                  ))}
                </div>
              </div>

              <div>
                <label className="block text-xs text-[#b8b3b0] mb-3 font-bold">النموذج النشط</label>
                <div className="space-y-2 max-h-60 overflow-y-auto pr-1">
                  {availableModels.map((model) => (
                    <button
                      key={model.id}
                      onClick={() => updateForm("aiModel", model.id)}
                      className={cn(
                        "w-full flex items-center justify-between p-4 rounded-xl border transition-all text-right",
                        form.aiModel === model.id
                          ? "border-purple-500 bg-purple-500/10"
                          : "border-gray-800 bg-[#161b27] hover:border-gray-700"
                      )}
                    >
                      <div>
                        <p className={cn("font-bold text-xs", form.aiModel === model.id ? "text-purple-400" : "text-[#b8b3b0]")}>
                          {model.name}
                        </p>
                        <p className="text-[10px] text-gray-500 mt-0.5">{model.description}</p>
                      </div>
                      <div className="flex items-center gap-2">
                        {model.badge && (
                          <span className={cn(
                            "text-[10px] px-2 py-0.5 rounded-full font-bold",
                            model.badge === "fast" ? "bg-blue-500/10 text-blue-400 border border-blue-500/20" :
                            model.badge === "smart" ? "bg-purple-500/10 text-purple-400 border border-purple-500/20" :
                            "bg-yellow-500/10 text-yellow-400 border border-yellow-500/20"
                          )}>
                            {model.badge === "fast" ? "⚡ سريع" : model.badge === "smart" ? "🧠 ذكي جداً" : "🖥️ خادم محلي"}
                          </span>
                        )}
                        <span className="text-[10px] text-gray-600">
                          {(model.contextWindow / 1000).toFixed(0)}K سعة
                        </span>
                      </div>
                    </button>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* Step 3: Keywords / Audiences Outline */}
          {currentStep === 3 && (
            <div className="space-y-5">
              <h2 className="text-lg font-bold text-white">
                {isSearch ? "تخطيط الكلمات المفتاحية بالـ AI" : "هندسة الجماهير والاهتمامات بالـ AI"}
              </h2>
              
              <div className="bg-purple-500/5 border border-purple-500/20 rounded-xl p-4 text-xs text-[#b8b3b0] leading-relaxed">
                <p className="font-bold text-purple-400 mb-2">
                  {isSearch 
                    ? "سيقوم الذكاء الاصطناعي بتحليل متجرك وتوليد المجموعات التالية:" 
                    : `سيقوم مهندس جماهير AI بصياغة استهداف إعلانات ${config.name} ويضم:`
                  }
                </p>
                <ul className="space-y-1.5 list-disc list-inside mr-2">
                  {isSearch ? (
                    <>
                      <li>كلمات البحث الرئيسية ذات النية العالية للشراء (High Intent)</li>
                      <li>الكلمات المفتاحية السلبية المقترحة لمنع نقرات المنافسين الضائعة</li>
                      <li>مجموعات إعلانية ذكية تناسب ميزانيتك</li>
                    </>
                  ) : (
                    <>
                      <li>الاهتمامات والسلوكيات المستهدفة بدقة (Interests & Behaviors)</li>
                      <li>استبعاد فئات الجماهير غير المشترية لتوفير الإنفاق (Excluded Audiences)</li>
                      <li>تحديد التوزيع الديموغرافي الأمثل (الأعمار، الجنس، الأماكن الجغرافية)</li>
                    </>
                  )}
                </ul>
              </div>
              <p className="text-[#8a8380] text-xs">
                سيقوم الـ AI المختار {form.aiModel} بإنتاج هذه العناصر بالخطوة الأخيرة فوراً.
              </p>
            </div>
          )}

          {/* Step 4: Ad Creatives Outline */}
          {currentStep === 4 && (
            <div className="space-y-5">
              <h2 className="text-lg font-bold text-white">إبداع وتصميم محتوى الإعلانات</h2>
              
              <div className="bg-purple-500/5 border border-purple-500/20 rounded-xl p-4 text-xs text-[#b8b3b0] leading-relaxed">
                <p className="font-bold text-purple-400 mb-2">سيقوم الذكاء الاصطناعي بصياغة وإعداد:</p>
                <ul className="space-y-1.5 list-disc list-inside mr-2">
                  {isSearch ? (
                    <>
                      <li>15 عنواناً إعلانياً نصياً جذاباً متوافقاً مع بحث جوجل</li>
                      <li>4 أوصاف تسويقية مقنعة تجذب العميل للنقر</li>
                      <li>مسارات العرض التوضيحية لتسهيل الزيارة</li>
                    </>
                  ) : (
                    <>
                      <li>النص الأساسي للإعلان (Primary Copy) المقنع والمحفز على الشراء</li>
                      <li>عناوين البطاقات الإعلانية الاحترافية ومواصفات زر CTA المناسب</li>
                      <li>سيناريوهات مقترحة وتوجيهات للـ Creative والصورة</li>
                    </>
                  )}
                </ul>
              </div>

              <div className="bg-[#161b27] rounded-xl p-4 border border-gray-850">
                <p className="text-[10px] text-gray-500 mb-2 font-bold">ملخص حملتك قبل التوليد والتصميم:</p>
                <div className="grid grid-cols-2 gap-y-1.5 text-xs text-[#b8b3b0]">
                  <div className="flex gap-1">
                    <span className="text-gray-500">اسم متجرك:</span>
                    <span className="text-white font-semibold">{form.businessName}</span>
                  </div>
                  <div className="flex gap-1">
                    <span className="text-gray-500">منصة الإطلاق:</span>
                    <span className="text-emerald-400 font-bold">{config.name}</span>
                  </div>
                  <div className="flex gap-1">
                    <span className="text-gray-500">الميزانية:</span>
                    <span className="text-white font-semibold">${form.budget} شهرية</span>
                  </div>
                  <div className="flex gap-1">
                    <span className="text-gray-500">العقل المفكر AI:</span>
                    <span className="text-purple-400 font-semibold">{form.aiModel}</span>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Step 5: Final Results */}
          {currentStep === 5 && (
            <div>
              {loading ? (
                <div className="flex flex-col items-center justify-center py-16 gap-4 text-center">
                  <div className="w-16 h-16 rounded-full bg-purple-500/10 border border-purple-500/20 flex items-center justify-center">
                    <Loader2 className="w-8 h-8 text-purple-400 animate-spin" />
                  </div>
                  <p className="text-white font-bold text-sm">يقوم {form.aiModel} بصياغة حملتك لـ {config.name}...</p>
                  <p className="text-gray-500 text-xs">يجري كتابة الإعلانات وتصميم الجماهير واختيار الاستهدافات بدقة</p>
                </div>
              ) : result ? (
                <div className="space-y-5">
                  <div className="flex items-center gap-2 border-b border-gray-850 pb-3">
                    <div className="w-8 h-8 rounded-full bg-emerald-500/10 flex items-center justify-center">
                      <Check className="w-4 h-4 text-emerald-400" />
                    </div>
                    <div>
                      <h2 className="text-lg font-bold text-white">تم إنشاء حملة {config.name} بنجاح!</h2>
                      <p className="text-[10px] text-gray-500">تمت الصياغة طبقاً لقواعد ومقاييس {config.name} المعتمدة</p>
                    </div>
                  </div>

                  {/* Tabs selector */}
                  <div className="flex gap-2">
                    <button
                      onClick={() => setActiveResultTab("keywords")}
                      className={cn(
                        "px-4 py-2 rounded-lg text-xs font-semibold transition-all border",
                        activeResultTab === "keywords"
                          ? "bg-purple-500/10 text-purple-400 border-purple-500/20 font-bold"
                          : "bg-transparent text-gray-500 border-transparent hover:text-white"
                      )}
                    >
                      {isSearch ? `الكلمات المفتاحية (${result.keywords?.length || 0})` : `الجماهير والاهتمامات (${result.audiences?.length || 0})`}
                    </button>
                    <button
                      onClick={() => setActiveResultTab("ads")}
                      className={cn(
                        "px-4 py-2 rounded-lg text-xs font-semibold transition-all border",
                        activeResultTab === "ads"
                          ? "bg-purple-500/10 text-purple-400 border-purple-500/20 font-bold"
                          : "bg-transparent text-gray-500 border-transparent hover:text-white"
                      )}
                    >
                      نصوص إبداع الإعلان
                    </button>
                  </div>

                  {/* Keywords vs. Audiences Render */}
                  {activeResultTab === "keywords" && (
                    isSearch ? (
                      <div className="space-y-1.5 max-h-64 overflow-y-auto">
                        {result.keywords?.slice(0, 10).map((kw, i) => (
                          <div key={i} className="flex items-center justify-between p-3 bg-[#161b27] rounded-xl border border-gray-850 text-xs">
                            <span className="text-[#b8b3b0] font-semibold">{kw.keyword}</span>
                            <div className="flex items-center gap-2">
                              <span className="text-gray-600">طريقة: {kw.matchType}</span>
                              <span className={cn("px-2 py-0.5 rounded-full font-bold text-[10px]", kw.searchVolume === "high" ? "bg-emerald-500/10 text-emerald-400" : "bg-gray-800 text-gray-400")}>
                                {kw.searchVolume === "high" ? "حجم بحث عالٍ" : "متوسط"}
                              </span>
                            </div>
                          </div>
                        ))}
                      </div>
                    ) : (
                      <div className="space-y-1.5 max-h-64 overflow-y-auto">
                        {result.audiences?.map((aud, i) => (
                          <div key={i} className="flex items-center justify-between p-3 bg-[#161b27] rounded-xl border border-gray-850 text-xs">
                            <div className="flex flex-col gap-0.5">
                              <span className="text-[#b8b3b0] font-bold">{aud.interest_name}</span>
                              <span className="text-[10px] text-gray-500">الفئات العمرية: {aud.age_range} | الجنس: {aud.gender === "all" ? "الكل" : aud.gender}</span>
                            </div>
                            <div className="flex items-center gap-2">
                              <span className="text-[10px] text-gray-500">الوصول: ~{formatNumber(aud.estimated_reach)}</span>
                              <span className="bg-purple-500/10 text-purple-400 px-2 py-0.5 rounded font-bold text-[10px]">{aud.relevance_score}/10 ملاءمة</span>
                            </div>
                          </div>
                        ))}
                      </div>
                    )
                  )}

                  {/* Ad Creatives copy Render */}
                  {activeResultTab === "ads" && (
                    isSearch ? (
                      <div className="space-y-3">
                        <div className="space-y-1.5">
                          <p className="text-[10px] text-gray-500 font-bold">العناوين النصية المقترحة لنتائج جوجل</p>
                          {result.headlines?.slice(0, 8).map((h, i) => (
                            <div key={i} className="flex items-center justify-between p-2.5 bg-[#161b27] rounded-lg border border-gray-850 text-xs">
                              <span className="text-[#b8b3b0] font-semibold">{h.text}</span>
                              <span className="text-[10px] text-gray-600">{h.charCount}/30 حرف</span>
                            </div>
                          ))}
                        </div>
                      </div>
                    ) : (
                      <div className="space-y-4">
                        <div className="p-3.5 bg-[#161b27] border border-gray-850 rounded-xl space-y-2.5 text-xs text-right">
                          <div>
                            <p className="text-[10px] text-gray-500 mb-1 font-bold">النص الإعلاني الترويجي الأساسي (Primary Text)</p>
                            <p className="text-[#b8b3b0] leading-relaxed whitespace-pre-line bg-black/30 p-2.5 rounded-lg">{result.primaryText}</p>
                          </div>

                          <div className="grid grid-cols-2 gap-3 pt-2">
                            <div>
                              <p className="text-[10px] text-gray-500 mb-1 font-bold">عنوان بطاقة الإعلان</p>
                              <p className="text-[#b8b3b0] font-semibold bg-black/30 p-2.5 rounded-lg">{result.headlines?.[0]?.text}</p>
                            </div>
                            <div>
                              <p className="text-[10px] text-gray-500 mb-1 font-bold">زر اتخاذ الإجراء المقترح</p>
                              <p className="text-emerald-400 font-bold bg-black/30 p-2.5 rounded-lg">{result.ctaButton}</p>
                            </div>
                          </div>
                        </div>
                      </div>
                    )
                  )}

                  <button
                    onClick={handleSaveAndLaunchCampaign}
                    disabled={saving}
                    className="w-full flex items-center justify-center gap-2 bg-gradient-to-l from-emerald-600 to-green-600 hover:from-emerald-500 hover:to-green-500 text-white font-bold py-3.5 rounded-xl transition-all shadow-lg shadow-emerald-500/10 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {saving ? (
                      <Loader2 className="w-4 h-4 animate-spin" />
                    ) : (
                      <Rocket className="w-4 h-4" />
                    )}
                    <span>{saving ? "جاري الحفظ والإطلاق..." : `حفظ وإطلاق حملة ${config.name} بالـ AI`}</span>
                  </button>
                </div>
              ) : (
                <div className="flex flex-col items-center gap-4 py-8 text-center">
                  <Sparkles className="w-12 h-12 text-purple-400" />
                  <p className="text-white font-bold text-sm">جاهز لإنشاء وإطلاق حملتك بالذكاء الاصطناعي!</p>
                  <p className="text-gray-500 text-xs max-w-sm">
                    سيقوم نموذج {form.aiModel} بتوليد نصوص إعلانات استثنائية وتصميم استهداف جماهيرك لـ {config.name} في أقل من 30 ثانية.
                  </p>
                  
                  <button
                    onClick={generateWithAI}
                    className="flex items-center gap-2 bg-purple-500 hover:bg-purple-400 text-white font-bold px-8 py-3 rounded-xl transition-all shadow-lg shadow-purple-500/20"
                  >
                    <Bot className="w-5 h-5" />
                    <span>أنشئ حملتي الذكية بالـ AI الآن</span>
                  </button>
                </div>
              )}
            </div>
          )}
        </motion.div>
      </AnimatePresence>

      {/* Navigation buttons */}
      <div className="flex items-center justify-between mt-6">
        <button
          onClick={() => setCurrentStep(Math.max(1, currentStep - 1))}
          disabled={currentStep === 1}
          className="flex items-center gap-2 text-[#8a8380] hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors px-4 py-2 rounded-xl text-xs font-semibold"
        >
          <ChevronRight className="w-4 h-4" />
          <span>السابق</span>
        </button>

        {currentStep < 4 ? (
          <button
            onClick={() => setCurrentStep(currentStep + 1)}
            disabled={currentStep === 1 && (!form.businessName || !form.businessDescription)}
            className="flex items-center gap-2 bg-purple-500 hover:bg-purple-400 disabled:opacity-50 disabled:cursor-not-allowed text-white font-bold px-6 py-2.5 rounded-xl text-xs transition-all"
          >
            <span>التالي</span>
            <ChevronLeft className="w-4 h-4" />
          </button>
        ) : currentStep === 4 ? (
          <button
            onClick={() => { setCurrentStep(5); generateWithAI(); }}
            className="flex items-center gap-2 bg-purple-500 hover:bg-purple-400 text-white font-bold px-6 py-2.5 rounded-xl text-xs transition-all"
          >
            <Bot className="w-4 h-4" />
            <span>إنشاء بالـ AI</span>
            <ChevronLeft className="w-4 h-4" />
          </button>
        ) : null}
      </div>
        </>
      )}
    </div>
  );
}
