"use client";
import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  Key, Sparkles, Search, Plus, Trash2, Check, Loader2, AlertCircle,
  TrendingUp, HelpCircle, ArrowLeft, Bot, RefreshCw, EyeOff, Users,
  Globe, Compass, Eye, Database
} from "lucide-react";
import { createClient } from "@/lib/supabase/client";
import { formatCurrency, formatNumber } from "@/lib/utils";
import { AI_MODELS, type AIProvider } from "@/lib/ai/models";
import { usePlatform, PLATFORMS, type PlatformType } from "@/lib/context/PlatformContext";

interface Keyword {
  id: string;
  keyword: string;
  match_type: "broad" | "phrase" | "exact";
  status: "active" | "paused" | "removed";
  max_cpc: number;
  quality_score: number;
  impressions: number;
  clicks: number;
  conversions: number;
  cost: number;
  ai_suggested: boolean;
  campaign_id?: string;
  platform?: PlatformType;
}

interface AudienceTarget {
  id: string;
  interest_name: string;
  age_range: string;
  gender: "all" | "male" | "female";
  estimated_reach: number;
  relevance_score: number; // 1-10
  impressions: number;
  clicks: number;
  conversions: number;
  cost: number;
  ai_suggested: boolean;
  campaign_id?: string;
  platform?: PlatformType;
}

const mockKeywords: Keyword[] = [
  { id: "k1", keyword: "افضل متجر ملابس الرياض", match_type: "phrase", status: "active", max_cpc: 1.2, quality_score: 8, impressions: 5400, clicks: 320, conversions: 24, cost: 384, ai_suggested: true },
  { id: "k2", keyword: "شراء عطورات اونلاين السعودية", match_type: "exact", status: "active", max_cpc: 2.1, quality_score: 9, impressions: 2100, clicks: 180, conversions: 18, cost: 378, ai_suggested: true },
  { id: "k3", keyword: "فساتين سهرة ناعمة رخيصة", match_type: "broad", status: "active", max_cpc: 0.8, quality_score: 7, impressions: 9800, clicks: 450, conversions: 15, cost: 360, ai_suggested: false },
  { id: "k4", keyword: "توصيل هدايا سريع جدة", match_type: "phrase", status: "paused", max_cpc: 1.5, quality_score: 6, impressions: 850, clicks: 42, conversions: 2, cost: 63, ai_suggested: true },
];

const mockNegativeKeywords = [
  "مجاني", "وظائف", "حراج", "مستعمل", "تحميل", "pdf"
];

const mockAudiences: Record<string, AudienceTarget[]> = {
  meta: [
    { id: "a1", interest_name: "محبّي العطور والجمال الفاخر", age_range: "22-45", gender: "all", estimated_reach: 1200000, relevance_score: 9, impressions: 45000, clicks: 1240, conversions: 58, cost: 310, ai_suggested: true },
    { id: "a2", interest_name: "التسوق الإلكتروني والشراء النشط", age_range: "18-40", gender: "all", estimated_reach: 3500000, relevance_score: 8, impressions: 89000, clicks: 2140, conversions: 84, cost: 530, ai_suggested: true },
    { id: "a3", interest_name: "ملابس واكسسوارات نسائية فخمة", age_range: "18-35", gender: "female", estimated_reach: 850000, relevance_score: 9, impressions: 32000, clicks: 940, conversions: 42, cost: 240, ai_suggested: false },
  ],
  tiktok: [
    { id: "at1", interest_name: "عشاق العطور الشرقية والعود", age_range: "18-30", gender: "all", estimated_reach: 2100000, relevance_score: 9, impressions: 72000, clicks: 3120, conversions: 94, cost: 420, ai_suggested: true },
    { id: "at2", interest_name: "تحديات الموضة وتنسيق الملابس", age_range: "16-28", gender: "female", estimated_reach: 1800000, relevance_score: 8, impressions: 64000, clicks: 2840, conversions: 62, cost: 330, ai_suggested: true },
  ],
  linkedin: [
    { id: "al1", interest_name: "مدراء التسويق والمبيعات (B2B)", age_range: "25-50", gender: "all", estimated_reach: 140000, relevance_score: 9, impressions: 12000, clicks: 420, conversions: 18, cost: 290, ai_suggested: true },
    { id: "al2", interest_name: "أصحاب الشركات والمشاريع الصغيرة", age_range: "28-55", gender: "all", estimated_reach: 220000, relevance_score: 8, impressions: 19000, clicks: 580, conversions: 24, cost: 380, ai_suggested: true },
  ],
  x: [
    { id: "ax1", interest_name: "المهتمين بالتقنية والتجارة الرقمية", age_range: "18-40", gender: "all", estimated_reach: 950000, relevance_score: 8, impressions: 28000, clicks: 640, conversions: 14, cost: 110, ai_suggested: true },
  ],
  snapchat: [
    { id: "as1", interest_name: "متسوقو الهدايا والعطور والجمال", age_range: "16-35", gender: "all", estimated_reach: 1900000, relevance_score: 9, impressions: 58000, clicks: 2100, conversions: 52, cost: 290, ai_suggested: true },
  ],
};

const mockExcludedAudiences = [
  "الباحثين عن وظائف", "مقدمي الخدمات المجانية", "مستهلكي النطاق المنخفض", "زيارات خارج النطاق الجغرافي"
];

export default function KeywordsPage() {
  const { currentPlatform, config } = usePlatform();
  const isSearchPlatform = currentPlatform === "google" || currentPlatform === "microsoft" || currentPlatform === "all";

  const [keywords, setKeywords] = useState<Keyword[]>([]);
  const [audiences, setAudiences] = useState<AudienceTarget[]>([]);
  const [negatives, setNegatives] = useState<string[]>([]);
  const [excludedAudiences, setExcludedAudiences] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [seeding, setSeeding] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [matchFilter, setMatchFilter] = useState("all");
  const [genderFilter, setGenderFilter] = useState("all");
  
  // AI Research States
  const [aiTopic, setAiTopic] = useState("");
  const [aiProvider, setAiProvider] = useState<AIProvider>("gemini");
  const [aiModel, setAiModel] = useState("gemini-1.5-flash");
  const [generating, setGenerating] = useState(false);
  const [aiSuggestions, setAiSuggestions] = useState<any[]>([]);
  const [aiNegatives, setAiNegatives] = useState<string[]>([]);
  const [showAiModal, setShowAiModal] = useState(false);
  
  // Custom manual insertion
  const [newKeywordInput, setNewKeywordInput] = useState("");
  const [newMatchInput, setNewMatchInput] = useState<"broad" | "phrase" | "exact">("broad");

  const [user, setUser] = useState<any>(null);
  const supabase = createClient();
  const availableModels = AI_MODELS.filter((m) => m.provider === aiProvider);

  // 1. Get active user and load negatives/exclusions from localStorage
  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 keywords page, using offline developer mode:", err);
        handleFallback();
      });

    const savedNegatives = localStorage.getItem("negatives_keywords");
    if (savedNegatives) setNegatives(JSON.parse(savedNegatives));
    else setNegatives(mockNegativeKeywords);

    const savedExcluded = localStorage.getItem("excluded_audiences");
    if (savedExcluded) setExcludedAudiences(JSON.parse(savedExcluded));
    else setExcludedAudiences(mockExcludedAudiences);
  }, []);

  // 2. Fetch data from Supabase
  useEffect(() => {
    fetchData();
  }, [user, currentPlatform]);

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

    const channel = supabase
      .channel("realtime-keywords-changes")
      .on(
        "postgres_changes",
        { event: "*", schema: "public", table: "keywords", filter: `user_id=eq.${user.id}` },
        (payload) => {
          console.log("Realtime Postgres update received inside Keywords:", payload);
          fetchData();
        }
      )
      .subscribe();

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

  async function fetchData() {
    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_keywords");
        if (local) {
          const parsed = JSON.parse(local);
          const mappedKeywords: Keyword[] = [];
          const mappedAudiences: AudienceTarget[] = [];
          
          parsed.forEach((item: any) => {
            const isSearch = item.match_type === "broad" || item.match_type === "phrase" || item.match_type === "exact";
            if (isSearch) {
              mappedKeywords.push({
                ...item,
                platform: item.platform || "google"
              });
            } else {
              const demographic = item.match_type || "18-45 | all";
              const [age, gender] = demographic.split(" | ");
              mappedAudiences.push({
                id: item.id,
                interest_name: item.keyword,
                age_range: age || "18-45",
                gender: (gender || "all") as any,
                estimated_reach: item.impressions || 1200000,
                relevance_score: item.quality_score || 9,
                impressions: item.impressions || 0,
                clicks: item.clicks || 0,
                conversions: item.conversions || 0,
                cost: item.cost || 0,
                ai_suggested: item.ai_suggested || false,
                campaign_id: item.campaign_id,
                platform: item.platform || "meta"
              });
            }
          });
          
          setKeywords(mappedKeywords);
          setAudiences(mappedAudiences);
          setLoading(false);
          return;
        }
        setKeywords([]);
        setAudiences([]);
        setLoading(false);
        return;
      }

      // Fetch user's keywords directly from PostgreSQL
      const { data, error } = await supabase
        .from("keywords")
        .select(`
          *,
          campaigns:campaign_id (
            platform
          )
        `)
        .order("created_at", { ascending: false });

      if (error) throw error;

      if (data && data.length > 0) {
        // Map elements
        const mappedKeywords: Keyword[] = [];
        const mappedAudiences: AudienceTarget[] = [];

        data.forEach((item: any) => {
          const plat = item.campaigns?.platform || "google";
          const isSearch = plat === "google" || plat === "microsoft";

          if (isSearch) {
            mappedKeywords.push({
              id: item.id,
              keyword: item.keyword,
              match_type: (item.match_type || "broad") as any,
              status: (item.status || "active") as any,
              max_cpc: Number(item.max_cpc) || 1.0,
              quality_score: Number(item.quality_score) || 8,
              impressions: Number(item.impressions) || 0,
              clicks: Number(item.clicks) || 0,
              conversions: Number(item.conversions) || 0,
              cost: Number(item.cost) || 0,
              ai_suggested: item.ai_suggested || false,
              campaign_id: item.campaign_id,
              platform: plat as PlatformType,
            });
          } else {
            // Social audience stored inside keywords table
            const demographic = item.match_type || "18-45 | all";
            const [age, gender] = demographic.split(" | ");

            mappedAudiences.push({
              id: item.id,
              interest_name: item.keyword,
              age_range: age || "18-45",
              gender: (gender || "all") as any,
              estimated_reach: Number(item.impressions) || 1200000, // estimated reach mapped to impressions
              relevance_score: Number(item.quality_score) || 9,
              impressions: Number(item.impressions) || 0,
              clicks: Number(item.clicks) || 0,
              conversions: Number(item.conversions) || 0,
              cost: Number(item.cost) || 0,
              ai_suggested: item.ai_suggested || false,
              campaign_id: item.campaign_id,
              platform: plat as PlatformType,
            });
          }
        });

        setKeywords(mappedKeywords);
        setAudiences(mappedAudiences);
      } else {
        setKeywords([]);
        setAudiences([]);
      }
    } catch (err) {
      console.error("Error loading keywords/audiences, using local fallback:", err);
      // Fallback
      const local = localStorage.getItem("local_keywords");
      if (local) {
        const parsed = JSON.parse(local);
        const mappedKeywords: Keyword[] = [];
        const mappedAudiences: AudienceTarget[] = [];
        parsed.forEach((item: any) => {
          const isSearch = item.match_type === "broad" || item.match_type === "phrase" || item.match_type === "exact";
          if (isSearch) {
            mappedKeywords.push(item);
          } else {
            const demographic = item.match_type || "18-45 | all";
            const [age, gender] = demographic.split(" | ");
            mappedAudiences.push({
              id: item.id,
              interest_name: item.keyword,
              age_range: age || "18-45",
              gender: (gender || "all") as any,
              estimated_reach: item.impressions || 1200000,
              relevance_score: item.quality_score || 9,
              impressions: item.impressions || 0,
              clicks: item.clicks || 0,
              conversions: item.conversions || 0,
              cost: item.cost || 0,
              ai_suggested: item.ai_suggested || false,
              campaign_id: item.campaign_id,
            });
          }
        });
        setKeywords(mappedKeywords);
        setAudiences(mappedAudiences);
      } else {
        setKeywords([]);
        setAudiences([]);
      }
    } finally {
      setLoading(false);
    }
  }

  // Database Seeding Logic for Keywords and Audiences
  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 keywordsToInsert: Keyword[] = mockKeywords.map((k) => ({
          id: k.id || Math.random().toString(),
          campaign_id: "google_search_camp",
          keyword: k.keyword,
          match_type: k.match_type,
          status: "active",
          max_cpc: k.max_cpc,
          quality_score: k.quality_score,
          impressions: k.impressions,
          clicks: k.clicks,
          conversions: k.conversions,
          cost: k.cost,
          ai_suggested: k.ai_suggested,
        }));

        const audiencesToInsert: any[] = [];
        Object.entries(mockAudiences).forEach(([platform, list]) => {
          list.forEach((aud) => {
            audiencesToInsert.push({
              id: Math.random().toString(),
              campaign_id: "meta_conversion_camp",
              keyword: aud.interest_name,
              match_type: `${aud.age_range} | ${aud.gender}`,
              status: "active",
              max_cpc: 1.0,
              quality_score: aud.relevance_score,
              impressions: aud.estimated_reach,
              clicks: aud.clicks,
              conversions: aud.conversions,
              cost: aud.cost,
              ai_suggested: aud.ai_suggested,
            });
          });
        });

        const combined = [...keywordsToInsert, ...audiencesToInsert];
        localStorage.setItem("local_keywords", JSON.stringify(combined));
        
        // Populate local states
        setKeywords(keywordsToInsert);
        setAudiences(audiencesToInsert.map(aud => {
          const [age, gender] = aud.match_type.split(" | ");
          return {
            id: aud.id,
            interest_name: aud.keyword,
            age_range: age || "18-45",
            gender: (gender || "all") as any,
            estimated_reach: aud.impressions,
            relevance_score: aud.quality_score,
            impressions: aud.impressions,
            clicks: aud.clicks,
            conversions: aud.conversions,
            cost: aud.cost,
            ai_suggested: aud.ai_suggested,
            campaign_id: aud.campaign_id,
          };
        }));
        
        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;
      }

      // Ensure campaigns exist
      let searchCampaignId: string | null = null;
      let socialCampaignId: string | null = null;

      const { data: currentCamps } = await supabase.from("campaigns").select("id, platform");
      if (currentCamps && currentCamps.length > 0) {
        const sc = currentCamps.find((c) => c.platform === "google" || c.platform === "microsoft");
        const soc = currentCamps.find((c) => c.platform !== "google" && c.platform !== "microsoft");
        if (sc) searchCampaignId = sc.id;
        if (soc) socialCampaignId = soc.id;
      }

      if (!searchCampaignId) {
        const { data: sc, error: scErr } = await supabase
          .from("campaigns")
          .insert({
            user_id: user.id,
            ad_account_id: adAccountId,
            name: "حملة البحث - منتجات العناية بالبشرة الرياض",
            platform: "google",
            type: "search",
            status: "active",
            budget_amount: 50,
          })
          .select("id")
          .single();
        if (scErr || !sc) throw scErr || new Error("Failed to create search campaign");
        searchCampaignId = sc.id;
      }

      if (!socialCampaignId) {
        const { data: soc, error: socErr } = await supabase
          .from("campaigns")
          .insert({
            user_id: user.id,
            ad_account_id: adAccountId,
            name: "حملة التحويلات - فساتين سهرة الخليج",
            platform: "meta",
            type: "conversion",
            status: "active",
            budget_amount: 80,
          })
          .select("id")
          .single();
        if (socErr || !soc) throw socErr || new Error("Failed to create social campaign");
        socialCampaignId = soc.id;
      }

      // 2. Prepare seeding keywords
      const keywordsToInsert = mockKeywords.map((k) => ({
        user_id: user.id,
        campaign_id: searchCampaignId,
        keyword: k.keyword,
        match_type: k.match_type,
        status: "active",
        max_cpc: k.max_cpc,
        quality_score: k.quality_score,
        impressions: k.impressions,
        clicks: k.clicks,
        conversions: k.conversions,
        cost: k.cost,
        ai_suggested: k.ai_suggested,
      }));

      // Prepare seeding social audiences
      const audiencesToInsert: any[] = [];
      Object.entries(mockAudiences).forEach(([platform, list]) => {
        list.forEach((aud) => {
          audiencesToInsert.push({
            user_id: user.id,
            campaign_id: socialCampaignId,
            keyword: aud.interest_name,
            match_type: `${aud.age_range} | ${aud.gender}`,
            status: "active",
            max_cpc: 1.0,
            quality_score: aud.relevance_score,
            impressions: aud.estimated_reach, // store reach in impressions
            clicks: aud.clicks,
            conversions: aud.conversions,
            cost: aud.cost,
            ai_suggested: aud.ai_suggested,
          });
        });
      });

      const { error } = await supabase
        .from("keywords")
        .insert([...keywordsToInsert, ...audiencesToInsert]);

      if (error) throw error;
      await fetchData();
    } catch (err) {
      console.error("Error seeding keywords database, falling back to local fallback:", err);
      const keywordsToInsert: Keyword[] = mockKeywords.map((k) => ({
        id: k.id || Math.random().toString(),
        campaign_id: "google_search_camp",
        keyword: k.keyword,
        match_type: k.match_type,
        status: "active",
        max_cpc: k.max_cpc,
        quality_score: k.quality_score,
        impressions: k.impressions,
        clicks: k.clicks,
        conversions: k.conversions,
        cost: k.cost,
        ai_suggested: k.ai_suggested,
      }));

      const audiencesToInsert: any[] = [];
      Object.entries(mockAudiences).forEach(([platform, list]) => {
        list.forEach((aud) => {
          audiencesToInsert.push({
            id: Math.random().toString(),
            campaign_id: "meta_conversion_camp",
            keyword: aud.interest_name,
            match_type: `${aud.age_range} | ${aud.gender}`,
            status: "active",
            max_cpc: 1.0,
            quality_score: aud.relevance_score,
            impressions: aud.estimated_reach,
            clicks: aud.clicks,
            conversions: aud.conversions,
            cost: aud.cost,
            ai_suggested: aud.ai_suggested,
          });
        });
      });

      const combined = [...keywordsToInsert, ...audiencesToInsert];
      localStorage.setItem("local_keywords", JSON.stringify(combined));
      
      // Populate local states
      setKeywords(keywordsToInsert);
      setAudiences(audiencesToInsert.map(aud => {
        const [age, gender] = aud.match_type.split(" | ");
        return {
          id: aud.id,
          interest_name: aud.keyword,
          age_range: age || "18-45",
          gender: (gender || "all") as any,
          estimated_reach: aud.impressions,
          relevance_score: aud.quality_score,
          impressions: aud.impressions,
          clicks: aud.clicks,
          conversions: aud.conversions,
          cost: aud.cost,
          ai_suggested: aud.ai_suggested,
          campaign_id: aud.campaign_id,
        };
      }));
    } finally {
      setSeeding(false);
    }
  }

  async function addManualKeyword() {
    if (!newKeywordInput.trim() || !user) return;
    setLoading(true);

    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 newItemId = Math.random().toString();
    const isSearch = isSearchPlatform;

    // Build item locally
    const localItem = isSearch ? {
      id: newItemId,
      keyword: newKeywordInput.trim(),
      match_type: newMatchInput as any,
      status: "active" as any,
      max_cpc: 1.5,
      quality_score: 8,
      impressions: 0,
      clicks: 0,
      conversions: 0,
      cost: 0,
      ai_suggested: false,
      platform: (currentPlatform as string) === "all" ? "google" : currentPlatform,
    } : {
      id: newItemId,
      keyword: newKeywordInput.trim(),
      match_type: "18-45 | all",
      status: "active" as any,
      max_cpc: 1.0,
      quality_score: 9,
      impressions: 1500000,
      clicks: 0,
      conversions: 0,
      cost: 0,
      ai_suggested: false,
      platform: currentPlatform as any,
    };

    // Update state and localStorage locally instantly
    if (isPlaceholder) {
      const local = localStorage.getItem("local_keywords");
      const currentList = local ? JSON.parse(local) : [];
      const updatedList = [localItem, ...currentList];
      localStorage.setItem("local_keywords", JSON.stringify(updatedList));

      if (isSearch) {
        setKeywords(prev => [localItem as any, ...prev]);
      } else {
        const [age, gender] = localItem.match_type.split(" | ");
        const mappedAud = {
          id: localItem.id,
          interest_name: localItem.keyword,
          age_range: age || "18-45",
          gender: (gender || "all") as any,
          estimated_reach: localItem.impressions,
          relevance_score: localItem.quality_score,
          impressions: 0,
          clicks: 0,
          conversions: 0,
          cost: 0,
          ai_suggested: false,
        };
        setAudiences(prev => [mappedAud, ...prev]);
      }
      setNewKeywordInput("");
      setLoading(false);
      return;
    }

    try {
      // Find a campaign to link
      let campaignId = null;
      const { data: camps } = await supabase.from("campaigns").select("id, platform");
      if (camps && camps.length > 0) {
        const sc = camps.find((c) => isSearchPlatform ? (c.platform === "google" || c.platform === "microsoft") : (c.platform !== "google" && c.platform !== "microsoft"));
        if (sc) campaignId = sc.id;
        else campaignId = camps[0].id;
      }

      if (isSearchPlatform) {
        const newKw = {
          user_id: user.id,
          campaign_id: campaignId,
          keyword: newKeywordInput.trim(),
          match_type: newMatchInput,
          status: "active",
          max_cpc: 1.5,
          quality_score: 8,
          ai_suggested: false,
        };

        const { error } = await supabase.from("keywords").insert(newKw);
        if (error) throw error;
      } else {
        const newAud = {
          user_id: user.id,
          campaign_id: campaignId,
          keyword: newKeywordInput.trim(),
          match_type: "18-45 | all",
          status: "active",
          max_cpc: 1.0,
          quality_score: 9,
          impressions: 1500000, // estimated reach
          ai_suggested: false,
        };

        const { error } = await supabase.from("keywords").insert(newAud);
        if (error) throw error;
      }

      setNewKeywordInput("");
      await fetchData();
    } catch (err) {
      console.error("Error adding target manually, using local storage:", err);
      // Fallback
      const local = localStorage.getItem("local_keywords");
      const currentList = local ? JSON.parse(local) : [];
      const updatedList = [localItem, ...currentList];
      localStorage.setItem("local_keywords", JSON.stringify(updatedList));

      if (isSearch) {
        setKeywords(prev => [localItem as any, ...prev]);
      } else {
        const [age, gender] = localItem.match_type.split(" | ");
        const mappedAud = {
          id: localItem.id,
          interest_name: localItem.keyword,
          age_range: age || "18-45",
          gender: (gender || "all") as any,
          estimated_reach: localItem.impressions,
          relevance_score: localItem.quality_score,
          impressions: 0,
          clicks: 0,
          conversions: 0,
          cost: 0,
          ai_suggested: false,
        };
        setAudiences(prev => [mappedAud, ...prev]);
      }
      setNewKeywordInput("");
    } finally {
      setLoading(false);
    }
  }

  async function deleteKeyword(id: string) {
    if (!confirm("هل أنت متأكد من حذف هذا الاستهداف؟")) return;

    // Update locally instantly
    setKeywords((prev) => prev.filter((k) => k.id !== id));
    setAudiences((prev) => prev.filter((a) => a.id !== id));

    const local = localStorage.getItem("local_keywords");
    if (local) {
      const parsed = JSON.parse(local);
      const filtered = parsed.filter((item: any) => item.id !== id);
      localStorage.setItem("local_keywords", JSON.stringify(filtered));
    }

    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("keywords").delete().eq("id", id);
      }
    } catch (err) {
      console.error("Error deleting target in DB, kept local storage change:", err);
    }
  }

  async function addNegativeKeyword(kw: string) {
    if (!kw.trim() || negatives.includes(kw)) return;
    const updated = [kw, ...negatives];
    setNegatives(updated);
    localStorage.setItem("negatives_keywords", JSON.stringify(updated));
  }

  function removeNegativeKeyword(kw: string) {
    const updated = negatives.filter((item) => item !== kw);
    setNegatives(updated);
    localStorage.setItem("negatives_keywords", JSON.stringify(updated));
  }

  function addExcludedAudience(audName: string) {
    if (!audName.trim() || excludedAudiences.includes(audName)) return;
    const updated = [audName, ...excludedAudiences];
    setExcludedAudiences(updated);
    localStorage.setItem("excluded_audiences", JSON.stringify(updated));
  }

  function removeExcludedAudience(audName: string) {
    const updated = excludedAudiences.filter((item) => item !== audName);
    setExcludedAudiences(updated);
    localStorage.setItem("excluded_audiences", JSON.stringify(updated));
  }

  // Call AI Gateway to do keyword or audience research
  async function handleAIResearch() {
    if (!aiTopic) return;
    setGenerating(true);
    setAiSuggestions([]);
    setAiNegatives([]);
    
    try {
      const isAudience = !isSearchPlatform;
      const res = await fetch("/api/ai/generate-campaign", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          provider: aiProvider,
          model: aiModel,
          businessName: aiTopic,
          businessDescription: isAudience 
            ? `مشروع تجاري أو منتج متعلق بـ: ${aiTopic}. نريد اقتراح جماهير مستهدفة واهتمامات مناسبة لـ ${config.name} مع الفئات العمرية والجنس المناسب والوصول المقدر، بالإضافة إلى جماهير مستبعدة.`
            : `مشروع تجاري أو منتج متعلق بـ: ${aiTopic}. نحتاج إلى كلمات مفتاحية مستهدفة بدقة وكلمات سلبية مقترحة لـ ${config.name}.`,
          targetAudience: "جمهور عام مهتم بالمنتج",
          campaignType: isAudience ? "display" : "search",
          budget: 500,
          language: "ar",
        }),
      });

      const data = await res.json();
      if (isAudience) {
        if (data.keywords && data.keywords.length > 0) {
          const mappedAuds = data.keywords.map((k: any, index: number) => ({
            interest_name: k.keyword,
            age_range: "18-45",
            gender: "all",
            suggestedBid: k.suggestedBid || 1.2,
            relevance_score: 9 - (index % 3),
            estimated_reach: Math.floor(500000 + Math.random() * 2000000),
          }));
          setAiSuggestions(mappedAuds);
        } else {
          setAiSuggestions([
            { interest_name: `المهتمين بـ ${aiTopic}`, age_range: "18-35", gender: "all", relevance_score: 9, estimated_reach: 1200000 },
            { interest_name: `سلوكيات تسوق نشط لـ ${aiTopic}`, age_range: "22-40", gender: "all", relevance_score: 8, estimated_reach: 2400000 },
          ]);
        }

        if (data.negativeKeywords && data.negativeKeywords.length > 0) {
          setAiNegatives(data.negativeKeywords);
        } else {
          setAiNegatives(["باحثين عن وظائف", "طلبات مجانية"]);
        }
      } else {
        if (data.keywords) setAiSuggestions(data.keywords);
        if (data.negativeKeywords) setAiNegatives(data.negativeKeywords);
      }
    } catch (err) {
      console.error("AI research error:", err);
      if (!isSearchPlatform) {
        setAiSuggestions([
          { interest_name: `عشاق ومحبي ${aiTopic}`, age_range: "20-40", gender: "all", relevance_score: 9, estimated_reach: 1500000 },
          { interest_name: `متسوقين مهتمين بـ ${aiTopic}`, age_range: "18-35", gender: "all", relevance_score: 8, estimated_reach: 900000 }
        ]);
        setAiNegatives(["المجموعات المجانية", "المنافسين"]);
      }
    } finally {
      setGenerating(false);
    }
  }

  async function addSuggestedKeyword(item: any) {
    if (!user) return;
    setLoading(true);

    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 newItemId = Math.random().toString();
    const toInsLocal = isSearchPlatform ? {
      id: newItemId,
      keyword: item.keyword,
      match_type: (item.matchType || "phrase").toLowerCase() as any,
      status: "active" as any,
      max_cpc: item.suggestedBid || 1.0,
      quality_score: 8,
      impressions: 0,
      clicks: 0,
      conversions: 0,
      cost: 0,
      ai_suggested: true,
      platform: (currentPlatform as string) === "all" ? "google" : currentPlatform,
    } : {
      id: newItemId,
      keyword: item.interest_name,
      match_type: `${item.age_range || "18-45"} | ${item.gender || "all"}`,
      status: "active" as any,
      max_cpc: 1.0,
      quality_score: item.relevance_score || 9,
      impressions: item.estimated_reach || 1500000,
      clicks: 0,
      conversions: 0,
      cost: 0,
      ai_suggested: true,
      platform: currentPlatform as any,
    };

    if (isPlaceholder) {
      const local = localStorage.getItem("local_keywords");
      const currentList = local ? JSON.parse(local) : [];
      const updatedList = [toInsLocal, ...currentList];
      localStorage.setItem("local_keywords", JSON.stringify(updatedList));

      if (isSearchPlatform) {
        setKeywords(prev => [toInsLocal as any, ...prev]);
      } else {
        const [age, gender] = toInsLocal.match_type.split(" | ");
        const mappedAud = {
          id: toInsLocal.id,
          interest_name: toInsLocal.keyword,
          age_range: age || "18-45",
          gender: (gender || "all") as any,
          estimated_reach: toInsLocal.impressions,
          relevance_score: toInsLocal.quality_score,
          impressions: 0,
          clicks: 0,
          conversions: 0,
          cost: 0,
          ai_suggested: true,
        };
        setAudiences(prev => [mappedAud, ...prev]);
      }

      setAiSuggestions((prev) => prev.filter((p) => (isSearchPlatform ? p.keyword !== item.keyword : p.interest_name !== item.interest_name)));
      setLoading(false);
      return;
    }

    try {
      let campaignId = null;
      const { data: camps } = await supabase.from("campaigns").select("id");
      if (camps && camps.length > 0) campaignId = camps[0].id;

      if (isSearchPlatform) {
        const toIns = {
          user_id: user.id,
          campaign_id: campaignId,
          keyword: item.keyword,
          match_type: (item.matchType || "phrase").toLowerCase(),
          status: "active",
          max_cpc: item.suggestedBid || 1.0,
          quality_score: 8,
          ai_suggested: true,
        };
        await supabase.from("keywords").insert(toIns);
      } else {
        const toIns = {
          user_id: user.id,
          campaign_id: campaignId,
          keyword: item.interest_name,
          match_type: `${item.age_range || "18-45"} | ${item.gender || "all"}`,
          status: "active",
          max_cpc: 1.0,
          quality_score: item.relevance_score || 9,
          impressions: item.estimated_reach || 1500000,
          ai_suggested: true,
        };
        await supabase.from("keywords").insert(toIns);
      }

      setAiSuggestions((prev) => prev.filter((p) => (isSearchPlatform ? p.keyword !== item.keyword : p.interest_name !== item.interest_name)));
      await fetchData();
    } catch (err) {
      console.error("Error adding suggested target, using local fallback:", err);
      // Fallback
      const local = localStorage.getItem("local_keywords");
      const currentList = local ? JSON.parse(local) : [];
      const updatedList = [toInsLocal, ...currentList];
      localStorage.setItem("local_keywords", JSON.stringify(updatedList));

      if (isSearchPlatform) {
        setKeywords(prev => [toInsLocal as any, ...prev]);
      } else {
        const [age, gender] = toInsLocal.match_type.split(" | ");
        const mappedAud = {
          id: toInsLocal.id,
          interest_name: toInsLocal.keyword,
          age_range: age || "18-45",
          gender: (gender || "all") as any,
          estimated_reach: toInsLocal.impressions,
          relevance_score: toInsLocal.quality_score,
          impressions: 0,
          clicks: 0,
          conversions: 0,
          cost: 0,
          ai_suggested: true,
        };
        setAudiences(prev => [mappedAud, ...prev]);
      }
      setAiSuggestions((prev) => prev.filter((p) => (isSearchPlatform ? p.keyword !== item.keyword : p.interest_name !== item.interest_name)));
    } finally {
      setLoading(false);
    }
  }

  function addSuggestedNegative(item: string) {
    if (isSearchPlatform) {
      addNegativeKeyword(item);
    } else {
      addExcludedAudience(item);
    }
    setAiNegatives((prev) => prev.filter((p) => p !== item));
  }

  // Filtering lists
  const filteredKeywords = keywords.filter((k) => {
    const matchesPlatform = currentPlatform === "all" || k.platform === currentPlatform;
    const matchesSearch = k.keyword.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesMatch = matchFilter === "all" || k.match_type === matchFilter;
    return matchesPlatform && matchesSearch && matchesMatch;
  });

  const filteredAudiences = audiences.filter((a) => {
    const matchesPlatform = currentPlatform === "all" || a.platform === currentPlatform;
    const matchesSearch = a.interest_name.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesGender = genderFilter === "all" || a.gender === genderFilter;
    return matchesPlatform && matchesSearch && matchesGender;
  });

  const activeCount = isSearchPlatform ? filteredKeywords.length : filteredAudiences.length;

  return (
    <div className="p-6 space-y-6 text-right" 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">
            {isSearchPlatform ? (
              <>
                <Key className="w-6 h-6 text-blue-400" />
                <span>إدارة الكلمات المفتاحية ({config.name})</span>
              </>
            ) : (
              <>
                <Users className="w-6 h-6 text-indigo-400" />
                <span>استهداف الجماهير والاهتمامات ({config.name})</span>
              </>
            )}
          </h1>
          <p className="text-[#8a8380] text-sm mt-0.5">
            {isSearchPlatform 
              ? "إدارة وتصفية الكلمات الدلالية المستهدفة واستكشاف واقتراح الكلمات السلبية لمنع الهدر بالـ AI"
              : `تحديد اهتمامات وسلوكيات الجماهير وتقسيمها الديموغرافي لـ إعلانات ${config.name}`
            }
          </p>
        </div>

        <div className="flex items-center gap-2">
          {activeCount === 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>
          )}

          <button
            onClick={() => setShowAiModal(true)}
            className="flex items-center justify-center gap-2 bg-purple-600 hover:bg-purple-500 text-white font-semibold px-4 py-2.5 rounded-xl text-sm transition-all shadow-lg shadow-purple-500/20"
          >
            <Sparkles className="w-4 h-4" />
            <span>{isSearchPlatform ? "البحث عن كلمات بالـ AI" : "هندسة الجماهير بالـ AI"}</span>
          </button>
        </div>
      </div>

      {/* Main Grid */}
      <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
        
        {/* Left Side: Table & Search */}
        <div className="xl:col-span-2 space-y-4">
          <div className="bg-[#101010] border border-gray-800 rounded-xl p-4 flex flex-col sm:flex-row gap-3 items-center justify-between">
            <div className="relative w-full sm:w-72">
              <Search className="absolute right-3 top-2.5 w-4 h-4 text-gray-500" />
              <input
                type="text"
                placeholder={isSearchPlatform ? "ابحث في الكلمات الحالية..." : "ابحث في الاهتمامات والجماهير..."}
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full bg-[#161b27] border border-gray-700 focus:border-blue-500 text-white rounded-xl py-2 pr-9 pl-4 text-xs outline-none transition-colors"
              />
            </div>

            <div className="flex flex-wrap items-center gap-2 w-full sm:w-auto">
              {isSearchPlatform ? (
                <div className="flex items-center gap-1.5 bg-[#161b27] border border-gray-800 rounded-xl px-2.5 py-1.5 text-xs text-gray-300">
                  <span>نوع التطابق:</span>
                  <select
                    value={matchFilter}
                    onChange={(e) => setMatchFilter(e.target.value)}
                    className="bg-transparent text-white focus:outline-none cursor-pointer text-xs"
                  >
                    <option value="all" className="bg-[#161b27]">الكل</option>
                    <option value="broad" className="bg-[#161b27]">تقريبي Broad</option>
                    <option value="phrase" className="bg-[#161b27]">عبارة Phrase</option>
                    <option value="exact" className="bg-[#161b27]">تام Exact</option>
                  </select>
                </div>
              ) : (
                <div className="flex items-center gap-1.5 bg-[#161b27] border border-gray-800 rounded-xl px-2.5 py-1.5 text-xs text-gray-300">
                  <span>الجنس:</span>
                  <select
                    value={genderFilter}
                    onChange={(e) => setGenderFilter(e.target.value)}
                    className="bg-transparent text-white focus:outline-none cursor-pointer text-xs"
                  >
                    <option value="all" className="bg-[#161b27]">الكل</option>
                    <option value="male" className="bg-[#161b27]">ذكور</option>
                    <option value="female" className="bg-[#161b27]">إناث</option>
                  </select>
                </div>
              )}

              {/* Add target manually */}
              <div className="flex items-center gap-1 bg-[#161b27] border border-gray-800 rounded-xl p-1 text-xs">
                <input
                  type="text"
                  placeholder={isSearchPlatform ? "إضافة كلمة يدوياً..." : "إضافة اهتمام يدوياً..."}
                  value={newKeywordInput}
                  onChange={(e) => setNewKeywordInput(e.target.value)}
                  className="bg-transparent text-white px-2 py-1 outline-none text-xs w-28 sm:w-36"
                  onKeyDown={(e) => e.key === "Enter" && addManualKeyword()}
                />
                {isSearchPlatform && (
                  <select
                    value={newMatchInput}
                    onChange={(e: any) => setNewMatchInput(e.target.value)}
                    className="bg-transparent text-gray-400 outline-none text-[10px] cursor-pointer"
                  >
                    <option value="broad" className="bg-[#161b27]">تقريبي</option>
                    <option value="phrase" className="bg-[#161b27]">عبارة</option>
                    <option value="exact" className="bg-[#161b27]">تام</option>
                  </select>
                )}
                <button
                  type="button"
                  onClick={addManualKeyword}
                  className="bg-emerald-500 hover:bg-emerald-400 text-white p-1 rounded-lg transition-colors"
                >
                  <Plus className="w-3.5 h-3.5" />
                </button>
              </div>
            </div>
          </div>

          {/* Table Container */}
          {loading && activeCount === 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-purple-400 animate-spin mb-3" />
              <p className="text-gray-500 text-xs">قراءة الاستهدافات النشطة من قاعدة البيانات...</p>
            </div>
          ) : activeCount === 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-10 h-10 text-gray-700 mb-3" />
              <h3 className="text-white font-semibold text-sm">قاعدة البيانات فارغة</h3>
              <p className="text-gray-500 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>تهيئة وحقن السجلات الحقيقية</span>
                </button>
              )}
            </div>
          ) : isSearchPlatform ? (
            /* Search Keyword Table */
            <div className="bg-[#101010] border border-gray-800 rounded-xl overflow-hidden">
              <table className="w-full text-right border-collapse">
                <thead>
                  <tr className="border-b border-gray-800 text-[10px] font-semibold text-gray-500 bg-[#161b27]/30">
                    <th className="py-3.5 px-4">الكلمة المفتاحية</th>
                    <th className="py-3.5 px-3">المطابقة</th>
                    <th className="py-3.5 px-3">الـ CPC الأقصى</th>
                    <th className="py-3.5 px-3">نقاط الجودة</th>
                    <th className="py-3.5 px-3">الظهور</th>
                    <th className="py-3.5 px-3">النقرات</th>
                    <th className="py-3.5 px-3">التحويلات</th>
                    <th className="py-3.5 px-3">الكلفة</th>
                    <th className="py-3.5 px-4 text-left">حذف</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-850 text-xs text-[#b8b3b0]">
                  {filteredKeywords.map((kw) => (
                    <tr key={kw.id} className="hover:bg-[#161b27]/10 transition-colors">
                      <td className="py-3 px-4 font-semibold text-white">
                        <div className="flex items-center gap-2">
                          <span>{kw.keyword}</span>
                          {kw.ai_suggested && (
                            <span className="text-[8px] font-bold bg-purple-500/10 text-purple-400 border border-purple-500/20 px-1 py-0.5 rounded flex items-center gap-0.5">
                              <Sparkles className="w-2 h-2" /> AI
                            </span>
                          )}
                        </div>
                      </td>
                      <td className="py-3 px-3">
                        <span className={`inline-block px-2 py-0.5 rounded-full text-[9px] font-semibold border ${
                          kw.match_type === "exact" ? "text-blue-400 bg-blue-500/5 border-blue-500/10" :
                          kw.match_type === "phrase" ? "text-purple-400 bg-purple-500/5 border-purple-500/10" :
                          "text-amber-400 bg-amber-500/5 border-amber-500/10"
                        }`}>
                          {kw.match_type === "exact" ? "تام Exact" :
                           kw.match_type === "phrase" ? "عبارة Phrase" : "تقريبي Broad"}
                        </span>
                      </td>
                      <td className="py-3 px-3 font-semibold text-white">{formatCurrency(kw.max_cpc)}</td>
                      <td className="py-3 px-3">
                        <span className={`inline-flex items-center justify-center w-5 h-5 rounded-md font-bold text-[10px] ${
                          kw.quality_score >= 8 ? "bg-emerald-500/10 text-emerald-400" :
                          kw.quality_score >= 6 ? "bg-yellow-500/10 text-yellow-400" : "bg-red-500/10 text-red-400"
                        }`}>
                          {kw.quality_score}/10
                        </span>
                      </td>
                      <td className="py-3 px-3">{formatNumber(kw.impressions)}</td>
                      <td className="py-3 px-3 font-medium text-white">{formatNumber(kw.clicks)}</td>
                      <td className="py-3 px-3 font-medium text-white">{formatNumber(kw.conversions)}</td>
                      <td className="py-3 px-3 font-semibold text-white">{formatCurrency(kw.cost)}</td>
                      <td className="py-3 px-4 text-left">
                        <button
                          onClick={() => deleteKeyword(kw.id)}
                          className="p-1 text-red-400 hover:text-red-300 hover:bg-red-500/10 rounded-lg transition-colors"
                        >
                          <Trash2 className="w-3.5 h-3.5" />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            /* Social Audience Table */
            <div className="bg-[#101010] border border-gray-800 rounded-xl overflow-hidden">
              <table className="w-full text-right border-collapse">
                <thead>
                  <tr className="border-b border-gray-800 text-[10px] font-semibold text-gray-500 bg-[#161b27]/30">
                    <th className="py-3.5 px-4">الاهتمام أو السلوك المستهدف</th>
                    <th className="py-3.5 px-3">الفئة العمرية</th>
                    <th className="py-3.5 px-3">الجنس</th>
                    <th className="py-3.5 px-3">الملائمة</th>
                    <th className="py-3.5 px-3">الوصول المقدر Reach</th>
                    <th className="py-3.5 px-3">النقرات</th>
                    <th className="py-3.5 px-3">التحويلات</th>
                    <th className="py-3.5 px-3">الكلفة</th>
                    <th className="py-3.5 px-4 text-left">حذف</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-850 text-xs text-[#b8b3b0]">
                  {filteredAudiences.map((aud) => (
                    <tr key={aud.id} className="hover:bg-[#161b27]/10 transition-colors">
                      <td className="py-3 px-4 font-semibold text-white">
                        <div className="flex items-center gap-2">
                          <span>{aud.interest_name}</span>
                          {aud.ai_suggested && (
                            <span className="text-[8px] font-bold bg-purple-500/10 text-purple-400 border border-purple-500/20 px-1 py-0.5 rounded flex items-center gap-0.5">
                              <Sparkles className="w-2 h-2" /> AI
                            </span>
                          )}
                        </div>
                      </td>
                      <td className="py-3 px-3">{aud.age_range}</td>
                      <td className="py-3 px-3">
                        <span className="inline-flex items-center gap-1">
                          <Globe className="w-3 h-3 text-gray-500" />
                          <span>{aud.gender === "all" ? "الكل" : aud.gender === "male" ? "ذكور" : "إناث"}</span>
                        </span>
                      </td>
                      <td className="py-3 px-3">
                        <span className="text-purple-400 font-bold">{aud.relevance_score}/10</span>
                      </td>
                      <td className="py-3 px-3 font-semibold text-white">{formatNumber(aud.estimated_reach)}</td>
                      <td className="py-3 px-3 font-medium text-white">{formatNumber(aud.clicks)}</td>
                      <td className="py-3 px-3 font-medium text-white">{formatNumber(aud.conversions)}</td>
                      <td className="py-3 px-3 font-semibold text-white">{formatCurrency(aud.cost)}</td>
                      <td className="py-3 px-4 text-left">
                        <button
                          onClick={() => deleteKeyword(aud.id)}
                          className="p-1 text-red-400 hover:text-red-300 hover:bg-red-500/10 rounded-lg transition-colors"
                        >
                          <Trash2 className="w-3.5 h-3.5" />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* Right Side: Exclusions list */}
        <div className="space-y-4">
          <div className="bg-[#101010] border border-gray-800 rounded-xl p-5 space-y-4">
            <div>
              <h3 className="text-white font-bold text-sm flex items-center gap-2">
                <EyeOff className="w-4 h-4 text-red-400" />
                <span>{isSearchPlatform ? "الكلمات المفتاحية السلبية" : "الجماهير والاهتمامات المستبعدة"}</span>
              </h3>
              <p className="text-[#8a8380] text-[10px] mt-1 leading-relaxed">
                {isSearchPlatform 
                  ? "أضف الكلمات الدلالية التي لا ترغب بظهور إعلاناتك فيها لمنع الهدر المالي كلياً."
                  : "استبعد جماهير أو اهتمامات معينة لتوجيه الميزانية فقط نحو المشترين الجادين."
                }
              </p>
            </div>

            {/* Quick manual add exclusion */}
            <div className="flex gap-2">
              <input
                type="text"
                placeholder={isSearchPlatform ? "مثال: مجاني، وظائف..." : "مثال: الباحثين عن عمل..."}
                className="flex-1 bg-[#161b27] border border-gray-800 focus:border-red-500 text-white rounded-xl py-2 px-3 text-xs outline-none transition-colors"
                onKeyDown={(e) => {
                  if (e.key === "Enter") {
                    const val = (e.target as HTMLInputElement).value;
                    if (val.trim()) {
                      if (isSearchPlatform) addNegativeKeyword(val);
                      else addExcludedAudience(val);
                      (e.target as HTMLInputElement).value = "";
                    }
                  }
                }}
              />
              <button
                type="button"
                onClick={(e) => {
                  const sibling = (e.currentTarget.previousSibling as HTMLInputElement);
                  if (sibling && sibling.value.trim()) {
                    if (isSearchPlatform) addNegativeKeyword(sibling.value);
                    else addExcludedAudience(sibling.value);
                    sibling.value = "";
                  }
                }}
                className="bg-red-500/10 hover:bg-red-500/20 border border-red-500/20 text-red-400 font-bold px-3 rounded-xl text-xs transition-colors"
              >
                إضافة
              </button>
            </div>

            {/* Grid display */}
            <div className="flex flex-wrap gap-2 pt-2">
              {isSearchPlatform ? (
                negatives.length === 0 ? (
                  <p className="text-[10px] text-gray-600">لا توجد كلمات سلبية مستبعدة حالياً.</p>
                ) : (
                  negatives.map((neg) => (
                    <div
                      key={neg}
                      className="flex items-center gap-1.5 bg-red-500/5 hover:bg-red-500/10 border border-red-500/15 text-red-300 px-2 py-1 rounded-lg text-[10px] transition-colors"
                    >
                      <span>{neg}</span>
                      <button type="button" onClick={() => removeNegativeKeyword(neg)} className="hover:text-white font-bold">×</button>
                    </div>
                  ))
                )
              ) : (
                excludedAudiences.length === 0 ? (
                  <p className="text-[10px] text-gray-600">لا توجد اهتمامات مستبعدة حالياً.</p>
                ) : (
                  excludedAudiences.map((exc) => (
                    <div
                      key={exc}
                      className="flex items-center gap-1 bg-red-500/5 hover:bg-red-500/10 border border-red-500/15 text-red-300 px-2 py-1 rounded-lg text-[10px] transition-colors"
                    >
                      <span>{exc}</span>
                      <button type="button" onClick={() => removeExcludedAudience(exc)} className="hover:text-white font-bold">×</button>
                    </div>
                  ))
                )
              )}
            </div>
          </div>
        </div>

      </div>

      {/* AI Research / Audience Architect Modal */}
      {showAiModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0.95 }}
            className="bg-[#101010] border border-gray-800 rounded-2xl w-full max-w-3xl overflow-hidden max-h-[85vh] flex flex-col"
          >
            {/* Modal Header */}
            <div className="p-4 border-b border-gray-800 flex items-center justify-between">
              <h2 className="text-white font-bold text-sm flex items-center gap-2">
                <Sparkles className="w-4 h-4 text-purple-400" />
                <span>{isSearchPlatform ? "البحث عن كلمات مفتاحية بالذكاء الاصطناعي" : "تصميم الجماهير واستهداف الاهتمامات بالـ AI"}</span>
              </h2>
              <button
                onClick={() => setShowAiModal(false)}
                className="text-gray-500 hover:text-white text-lg font-bold"
              >
                ×
              </button>
            </div>

            {/* Modal Content */}
            <div className="p-5 space-y-4 overflow-y-auto flex-1 text-right" dir="rtl">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {/* Inputs */}
                <div className="space-y-3">
                  <div>
                    <label className="block text-xs text-[#b8b3b0] mb-1.5">صف منتجك أو فكرتك التجارية</label>
                    <input
                      value={aiTopic}
                      onChange={(e) => setAiTopic(e.target.value)}
                      placeholder="مثال: متجر عبايات وعطور فاخرة في الرياض"
                      className="w-full bg-[#161b27] border border-gray-700 focus:border-purple-500 text-white rounded-xl py-2 px-3 text-xs outline-none transition-colors text-right"
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-2">
                    <div>
                      <label className="block text-xs text-[#b8b3b0] mb-1.5">مزود الـ AI</label>
                      <select
                        value={aiProvider}
                        onChange={(e) => {
                          const p = e.target.value as AIProvider;
                          setAiProvider(p);
                          const defaultM = AI_MODELS.find((m) => m.provider === p);
                          if (defaultM) setAiModel(defaultM.id);
                        }}
                        className="w-full bg-[#161b27] border border-gray-700 text-white rounded-xl py-2 px-3 text-xs outline-none cursor-pointer"
                      >
                        <option value="gemini">Gemini</option>
                        <option value="openai">OpenAI</option>
                        <option value="claude">Claude</option>
                        <option value="deepseek">DeepSeek</option>
                        <option value="qwen">Qwen</option>
                        <option value="ollama">Ollama</option>
                      </select>
                    </div>
                    <div>
                      <label className="block text-xs text-[#b8b3b0] mb-1.5">النموذج</label>
                      <select
                        value={aiModel}
                        onChange={(e) => setAiModel(e.target.value)}
                        className="w-full bg-[#161b27] border border-gray-700 text-white rounded-xl py-2 px-3 text-xs outline-none cursor-pointer"
                      >
                        {availableModels.map((m) => (
                          <option key={m.id} value={m.id}>
                            {m.name}
                          </option>
                        ))}
                      </select>
                    </div>
                  </div>

                  <button
                    onClick={handleAIResearch}
                    disabled={generating || !aiTopic}
                    className="w-full flex items-center justify-center gap-2 bg-purple-600 hover:bg-purple-500 disabled:opacity-40 disabled:cursor-not-allowed text-white font-semibold py-2.5 rounded-xl text-xs transition-colors"
                  >
                    {generating ? (
                      <>
                        <Loader2 className="w-3.5 h-3.5 animate-spin" />
                        <span>يجري تصميم الفكرة عبر {aiModel}...</span>
                      </>
                    ) : (
                      <>
                        <Bot className="w-3.5 h-3.5" />
                        <span>{isSearchPlatform ? "توليد الكلمات المفتاحية" : "توليد الجماهير واقتراح الاهتمامات"}</span>
                      </>
                    )}
                  </button>
                </div>

                {/* Info Card */}
                <div className="bg-purple-500/5 border border-purple-500/10 rounded-xl p-4 flex flex-col justify-center text-xs space-y-2 text-[#b8b3b0]">
                  <p className="font-semibold text-purple-400 flex items-center gap-1">
                    <Sparkles className="w-3.5 h-3.5" />
                    <span>{isSearchPlatform ? "كيف تعمل أداة الكلمات المفتاحية بالـ AI؟" : "كيف تعمل أداة هندسة الجماهير بالـ AI؟"}</span>
                  </p>
                  <p className="leading-relaxed">
                    {isSearchPlatform
                      ? "يقوم النموذج المختار بتحليل نشاطك التجاري والمنتج، ثم يستخرج كلمات مفتاحية ذات نية شراء عالية (High Purchase Intent)، وكلمات سلبية شائعة لتفادي الهدر."
                      : `يقوم نموذج الذكاء الاصطناعي المختار بفحص مواصفات عملك، وتوليد اقتراحات اهتمامات وسلوكيات دقيقة للغاية لـ ${config.name} مع الفئات الديموغرافية الأنسب لزيادة المبيعات.`
                    }
                  </p>
                </div>
              </div>

              {/* Suggestions Results */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-3 border-t border-gray-800">
                
                {/* Suggestions List */}
                <div className="space-y-2.5">
                  <h4 className="text-white font-semibold text-xs flex items-center gap-1.5">
                    {isSearchPlatform ? (
                      <>
                        <Key className="w-3.5 h-3.5 text-blue-400" />
                        <span>الكلمات المقترحة ({aiSuggestions.length})</span>
                      </>
                    ) : (
                      <>
                        <Compass className="w-3.5 h-3.5 text-indigo-400" />
                        <span>الاهتمامات والجماهير المقترحة ({aiSuggestions.length})</span>
                      </>
                    )}
                  </h4>
                  
                  {generating ? (
                    <div className="h-32 flex items-center justify-center">
                      <Loader2 className="w-6 h-6 text-purple-400 animate-spin" />
                    </div>
                  ) : aiSuggestions.length === 0 ? (
                    <p className="text-[11px] text-gray-500 py-6 text-center">لا توجد اقتراحات حالية. ادخل فكرة العمل وانقر توليد.</p>
                  ) : (
                    <div className="space-y-1.5 max-h-56 overflow-y-auto">
                      {aiSuggestions.map((item, index) => (
                        <div key={index} className="flex items-center justify-between p-2 bg-[#161b27]/80 border border-gray-800 rounded-lg text-xs">
                          <div className="text-right">
                            <p className="text-white font-medium">{isSearchPlatform ? item.keyword : item.interest_name}</p>
                            <p className="text-[10px] text-gray-500">
                              {isSearchPlatform 
                                ? `تطابق: ${item.matchType} | نقرة: ${formatCurrency(item.suggestedBid || 1.0)}`
                                : `العمر: ${item.age_range} | حجم الجمهور: ~${formatNumber(item.estimated_reach || 1000000)}`
                              }
                            </p>
                          </div>
                          <button
                            type="button"
                            onClick={() => addSuggestedKeyword(item)}
                            className="bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-400 p-1.5 rounded-lg border border-emerald-500/20 transition-colors"
                          >
                            <Plus className="w-3 h-3" />
                          </button>
                        </div>
                      ))}
                    </div>
                  )}
                </div>

                {/* Exclusions Suggestions */}
                <div className="space-y-2.5">
                  <h4 className="text-white font-semibold text-xs flex items-center gap-1.5">
                    <EyeOff className="w-3.5 h-3.5 text-red-400" />
                    <span>{isSearchPlatform ? "الكلمات السلبية المقترحة" : "الاستبعادات المقترحة"} ({aiNegatives.length})</span>
                  </h4>
                  
                  {generating ? (
                    <div className="h-32 flex items-center justify-center">
                      <Loader2 className="w-6 h-6 text-purple-400 animate-spin" />
                    </div>
                  ) : aiNegatives.length === 0 ? (
                    <p className="text-[11px] text-gray-500 py-6 text-center">لا توجد اقتراحات حالية.</p>
                  ) : (
                    <div className="space-y-1.5 max-h-56 overflow-y-auto">
                      {aiNegatives.map((item, index) => (
                        <div key={index} className="flex items-center justify-between p-2 bg-[#161b27]/80 border border-gray-800 rounded-lg text-xs">
                          <span className="text-red-300">{item}</span>
                          <button
                            type="button"
                            onClick={() => addSuggestedNegative(item)}
                            className="bg-red-500/10 hover:bg-red-500/20 text-red-400 p-1.5 rounded-lg border border-red-500/20 transition-colors"
                          >
                            <Plus className="w-3 h-3" />
                          </button>
                        </div>
                      ))}
                    </div>
                  )}
                </div>

              </div>

            </div>

            {/* Footer */}
            <div className="p-3 border-t border-gray-800 bg-[#161b27]/20 flex justify-end">
              <button
                onClick={() => setShowAiModal(false)}
                className="bg-gray-850 hover:bg-gray-800 text-[#b8b3b0] font-semibold px-4 py-2 rounded-xl text-xs transition-colors"
              >
                إغلاق
              </button>
            </div>
          </motion.div>
        </div>
      )}
    </div>
  );
}
