"use client";

import { useState, useEffect, useCallback } from "react";
import { motion } from "framer-motion";
import {
  Check, Loader2, Link2Off, RefreshCw, AlertCircle, CheckCircle2,
  ExternalLink, Wifi, WifiOff, Settings
} from "lucide-react";
import { createClient } from "@/lib/supabase/client";

// ─── Types ───────────────────────────────────────────────────────────────────

interface PlatformConnection {
  id: string;
  platform: string;
  account_name: string;
  status: "active" | "inactive" | "error";
  updated_at: string;
}

interface Platform {
  id: string;
  name: string;
  nameEn: string;
  description: string;
  category: "ads" | "analytics";
  logo: React.ReactNode;
  authUrl: string;
  syncUrl?: string;
  envKey: string; // env var needed
  color: string;
}

// ─── SVG Logos ───────────────────────────────────────────────────────────────

const GoogleAdsLogo = () => (
  <svg className="w-6 h-6" viewBox="0 0 24 24" fill="none">
    <path d="M16.42 2.1c-.58-.33-1.32-.13-1.66.45L6.61 16.92c-.34.58-.14 1.33.45 1.66l3.62 2.09c.58.33 1.33.14 1.66-.45L20.49 5.86c.34-.58.14-1.33-.45-1.66l-3.62-2.1z" fill="#F9BC06"/>
    <path d="M7.05 16.48c-.58-.33-1.33-.14-1.66.45L.45 25.26c-.34.58-.14 1.33.45 1.66l3.62 2.09c.58.33 1.33.14 1.66-.45l4.94-8.33c.34-.58.14-1.33-.45-1.66l-3.62-2.09z" fill="#4285F4"/>
  </svg>
);

const MetaLogo = () => (
  <svg className="w-6 h-6" viewBox="0 0 24 24" fill="none">
    <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069z" fill="#E4405F"/>
    <path d="M12 6.865a5.135 5.135 0 110 10.27 5.135 5.135 0 010-10.27zm0 1.802a3.333 3.333 0 100 6.666 3.333 3.333 0 000-6.666zm5.338-3.205a1.2 1.2 0 110 2.4 1.2 1.2 0 010-2.4z" fill="white"/>
  </svg>
);

const MicrosoftLogo = () => (
  <svg className="w-5 h-5" viewBox="0 0 23 23" fill="currentColor">
    <rect x="0" y="0" width="11" height="11" fill="#F25022"/>
    <rect x="12" y="0" width="11" height="11" fill="#7FBA00"/>
    <rect x="0" y="12" width="11" height="11" fill="#00A4EF"/>
    <rect x="12" y="12" width="11" height="11" fill="#FFB900"/>
  </svg>
);

const TikTokLogo = () => (
  <svg className="w-5 h-5" viewBox="0 0 24 24" fill="currentColor">
    <path d="M19.59 6.69a4.83 4.83 0 01-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 01-2.88 2.5 2.89 2.89 0 01-2.89-2.89 2.89 2.89 0 012.89-2.89c.28 0 .54.04.79.1V9.01a6.32 6.32 0 00-.79-.05 6.34 6.34 0 00-6.34 6.34 6.34 6.34 0 006.34 6.34 6.34 6.34 0 006.33-6.34V8.69a8.16 8.16 0 004.78 1.52V6.76a4.85 4.85 0 01-1.01-.07z" fill="white"/>
  </svg>
);

const LinkedInLogo = () => (
  <svg className="w-5 h-5" viewBox="0 0 24 24" fill="#0077B5">
    <path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/>
  </svg>
);

const XLogo = () => (
  <svg className="w-5 h-5" viewBox="0 0 24 24" fill="white">
    <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/>
  </svg>
);

const SnapchatLogo = () => (
  <svg className="w-6 h-6" viewBox="0 0 24 24" fill="#FFFC00">
    <path d="M12.166.024C12.11.023 12.056.023 12 .023c-6.626 0-12 5.374-12 12s5.374 12 12 12 12-5.374 12-12c0-6.463-5.095-11.73-11.503-11.981l.003-.018zm-.17 18.957c-.1.207-.317.38-.576.38h-.003c-.282-.002-.5-.165-.608-.38a7.178 7.178 0 00-.067-.127c-.323-.589-1.08-.918-2.076-.918-.124 0-.248.005-.367.014a.54.54 0 01-.082.006.396.396 0 01-.384-.324c-.051-.244.137-.43.38-.47 1.23-.205 2.176-1.02 2.66-2.283.047-.124.183-.427.183-.427.107-.237.316-.38.574-.38.257 0 .464.143.57.38l.185.427c.485 1.263 1.43 2.078 2.66 2.283.244.04.43.226.38.47a.396.396 0 01-.384.324.54.54 0 01-.082-.006c-.12-.01-.243-.014-.367-.014-.996 0-1.753.33-2.076.918a7.178 7.178 0 00-.12.127z"/>
  </svg>
);

const GoogleAnalyticsLogo = () => (
  <svg className="w-6 h-6" viewBox="0 0 24 24" fill="none">
    <path d="M18.8 19.3c.7 0 1.2-.5 1.2-1.2V5.9c0-.7-.5-1.2-1.2-1.2s-1.2.5-1.2 1.2v12.2c0 .7.5 1.2 1.2 1.2z" fill="#E27100"/>
    <path d="M12.8 19.3c.7 0 1.2-.5 1.2-1.2V9.9c0-.7-.5-1.2-1.2-1.2s-1.2.5-1.2 1.2v8.2c0 .7.5 1.2 1.2 1.2z" fill="#F4B400"/>
    <path d="M6.8 19.3c.7 0 1.2-.5 1.2-1.2v-4.2c0-.7-.5-1.2-1.2-1.2s-1.2.5-1.2 1.2v4.2c0 .7.5 1.2 1.2 1.2z" fill="#F9AB00"/>
  </svg>
);

// ─── Platform Definitions ─────────────────────────────────────────────────────

const AD_PLATFORMS: Platform[] = [
  {
    id: "google",
    name: "إعلانات Google",
    nameEn: "Google Ads",
    description: "ربط حساب Google Ads لإدارة الحملات ومزامنة بيانات الحملات بشكل فوري.",
    category: "ads",
    logo: <GoogleAdsLogo />,
    authUrl: "/api/auth/google",
    syncUrl: "/api/sync/google-ads",
    envKey: "GOOGLE_CLIENT_ID",
    color: "#4285F4",
  },
  {
    id: "meta",
    name: "إعلانات Meta",
    nameEn: "Meta Ads",
    description: "ربط فيسبوك وإنستقرام للوصول إلى ملياري مستخدم ومزامنة حملاتك الإعلانية.",
    category: "ads",
    logo: <MetaLogo />,
    authUrl: "/api/auth/meta",
    syncUrl: "/api/sync/meta-ads",
    envKey: "META_APP_ID",
    color: "#1877F2",
  },
  {
    id: "microsoft",
    name: "إعلانات Microsoft",
    nameEn: "Microsoft Ads",
    description: "الوصول إلى جمهور Bing وMicrosoft Audience Network لتوسيع نطاق إعلاناتك.",
    category: "ads",
    logo: <MicrosoftLogo />,
    authUrl: "/api/auth/microsoft",
    syncUrl: "/api/sync/microsoft-ads",
    envKey: "MICROSOFT_CLIENT_ID",
    color: "#0078D4",
  },
  {
    id: "tiktok",
    name: "إعلانات TikTok",
    nameEn: "TikTok Ads",
    description: "استهدف جيل Z والشباب عبر TikTok Ads Manager بأفضل معدلات التفاعل.",
    category: "ads",
    logo: <TikTokLogo />,
    authUrl: "/api/auth/tiktok",
    syncUrl: "/api/sync/tiktok-ads",
    envKey: "TIKTOK_APP_ID",
    color: "#010101",
  },
  {
    id: "linkedin",
    name: "إعلانات LinkedIn",
    nameEn: "LinkedIn Ads",
    description: "وصول احترافي لصنّاع القرار والمديرين التنفيذيين عبر LinkedIn Campaign Manager.",
    category: "ads",
    logo: <LinkedInLogo />,
    authUrl: "/api/auth/linkedin",
    syncUrl: "/api/sync/linkedin-ads",
    envKey: "LINKEDIN_CLIENT_ID",
    color: "#0077B5",
  },
  {
    id: "x",
    name: "إعلانات X (تويتر)",
    nameEn: "X Ads",
    description: "إعلانات X للوصول إلى المحادثات والتوجهات العالمية في الوقت الفعلي.",
    category: "ads",
    logo: <XLogo />,
    authUrl: "/api/auth/x",
    syncUrl: "/api/sync/x-ads",
    envKey: "X_CLIENT_ID",
    color: "#000000",
  },
  {
    id: "snapchat",
    name: "إعلانات Snapchat",
    nameEn: "Snapchat Ads",
    description: "إعلانات Snap للوصول إلى الجمهور الشاب بتجارب إعلانية تفاعلية وقصص ممتعة.",
    category: "ads",
    logo: <SnapchatLogo />,
    authUrl: "/api/auth/snapchat",
    syncUrl: "/api/sync/snapchat-ads",
    envKey: "SNAPCHAT_CLIENT_ID",
    color: "#FFFC00",
  },
];

const ANALYTICS_PLATFORMS: Platform[] = [
  {
    id: "google_analytics",
    name: "Google Analytics",
    nameEn: "Google Analytics",
    description: "تتبع زوار موقعك وتحليل سلوكهم بدقة عبر GA4.",
    category: "analytics",
    logo: <GoogleAnalyticsLogo />,
    authUrl: "/api/auth/google",
    envKey: "GOOGLE_CLIENT_ID",
    color: "#E37400",
  },
];

// ─── Toast Notification ───────────────────────────────────────────────────────
function Toast({ message, type, onClose }: { message: string; type: "success" | "error"; onClose: () => void }) {
  useEffect(() => {
    const t = setTimeout(onClose, 4000);
    return () => clearTimeout(t);
  }, [onClose]);

  return (
    <motion.div
      initial={{ opacity: 0, y: 40 }}
      animate={{ opacity: 1, y: 0 }}
      exit={{ opacity: 0, y: 40 }}
      className={`fixed bottom-6 left-6 z-50 flex items-center gap-3 px-5 py-3 rounded-2xl shadow-2xl text-sm font-semibold ${
        type === "success"
          ? "bg-emerald-500/20 border border-emerald-500/40 text-emerald-300"
          : "bg-red-500/20 border border-red-500/40 text-red-300"
      }`}
    >
      {type === "success" ? (
        <CheckCircle2 className="w-4 h-4" />
      ) : (
        <AlertCircle className="w-4 h-4" />
      )}
      {message}
    </motion.div>
  );
}

// ─── Platform Card ────────────────────────────────────────────────────────────
function PlatformCard({
  platform,
  connection,
  onDisconnect,
  onSync,
  syncingId,
  disconnectingId,
}: {
  platform: Platform;
  connection?: PlatformConnection;
  onDisconnect: (platform: string, id: string) => void;
  onSync: (platform: Platform) => void;
  syncingId: string | null;
  disconnectingId: string | null;
}) {
  const isConnected = !!connection;
  const isSyncing = syncingId === platform.id;
  const isDisconnecting = disconnectingId === platform.id;

  return (
    <motion.div
      layout
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      className={`relative bg-[#101418] border rounded-2xl p-5 flex flex-col gap-4 transition-all duration-300 ${
        isConnected
          ? "border-emerald-500/30 shadow-[0_0_20px_rgba(52,211,153,0.05)]"
          : "border-gray-800/80 hover:border-gray-700"
      }`}
    >
      {/* Connected indicator strip */}
      {isConnected && (
        <div className="absolute top-0 left-0 right-0 h-0.5 rounded-t-2xl bg-gradient-to-r from-emerald-500/0 via-emerald-500/60 to-emerald-500/0" />
      )}

      {/* Header */}
      <div className="flex items-start justify-between">
        <div className="space-y-1.5">
          <h3 className="text-white font-bold text-sm">{platform.name}</h3>
          <div className="flex items-center gap-2">
            <span
              className={`w-2 h-2 rounded-full ${
                isConnected
                  ? "bg-emerald-400 animate-pulse shadow-[0_0_6px_rgba(52,211,153,0.6)]"
                  : "bg-gray-600"
              }`}
            />
            <span className={`text-[11px] font-medium ${isConnected ? "text-emerald-400" : "text-gray-500"}`}>
              {isConnected ? connection!.account_name || "متصل ونشط" : "غير متصل"}
            </span>
          </div>
        </div>
        <div
          className="p-2 rounded-xl"
          style={{
            background: isConnected
              ? `${platform.color}15`
              : "rgba(255,255,255,0.03)",
          }}
        >
          {platform.logo}
        </div>
      </div>

      {/* Description */}
      <p className="text-[11px] text-gray-500 leading-relaxed">{platform.description}</p>

      {/* Last sync info */}
      {isConnected && connection!.updated_at && (
        <div className="flex items-center gap-1.5 text-[10px] text-gray-600">
          <Wifi className="w-3 h-3" />
          <span>
            آخر مزامنة:{" "}
            {new Date(connection!.updated_at).toLocaleDateString("ar-SA", {
              day: "2-digit",
              month: "short",
              hour: "2-digit",
              minute: "2-digit",
            })}
          </span>
        </div>
      )}

      {/* Actions */}
      <div className="flex items-center gap-2 pt-2 border-t border-gray-800/60">
        {isConnected ? (
          <>
            {platform.syncUrl && (
              <button
                onClick={() => onSync(platform)}
                disabled={isSyncing}
                className="flex items-center gap-1.5 bg-emerald-500/10 hover:bg-emerald-500/20 border border-emerald-500/20 text-emerald-400 font-semibold px-3 py-1.5 rounded-xl text-[11px] transition-all cursor-pointer"
              >
                <RefreshCw className={`w-3 h-3 ${isSyncing ? "animate-spin" : ""}`} />
                {isSyncing ? "جارٍ المزامنة..." : "مزامنة الآن"}
              </button>
            )}
            <button
              onClick={() => onDisconnect(platform.id, connection!.id)}
              disabled={isDisconnecting}
              className="flex items-center gap-1.5 border border-red-500/20 bg-red-500/10 hover:bg-red-500/20 text-red-400 font-semibold px-3 py-1.5 rounded-xl text-[11px] transition-all cursor-pointer"
            >
              {isDisconnecting ? (
                <Loader2 className="w-3 h-3 animate-spin" />
              ) : (
                <Link2Off className="w-3 h-3" />
              )}
              فصل
            </button>
          </>
        ) : (
          <a
            href={platform.authUrl}
            className="flex items-center gap-1.5 bg-white hover:bg-gray-100 text-black font-bold px-4 py-1.5 rounded-xl text-[11px] transition-all"
          >
            <ExternalLink className="w-3 h-3" />
            ربط الحساب
          </a>
        )}
      </div>
    </motion.div>
  );
}

// ─── Main Page ────────────────────────────────────────────────────────────────
export default function IntegrationsPage() {
  const [connections, setConnections] = useState<PlatformConnection[]>([]);
  const [loading, setLoading] = useState(true);
  const [syncingId, setSyncingId] = useState<string | null>(null);
  const [disconnectingId, setDisconnectingId] = useState<string | null>(null);
  const [toast, setToast] = useState<{ message: string; type: "success" | "error" } | null>(null);

  const supabase = createClient();

  // ── Show toast from URL params (OAuth callbacks) ──
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const success = params.get("success");
    const error = params.get("error");

    const successMessages: Record<string, string> = {
      google: "✅ تم ربط حساب Google Ads بنجاح!",
      meta: "✅ تم ربط حساب Meta Ads بنجاح!",
      microsoft: "✅ تم ربط حساب Microsoft Ads بنجاح!",
      tiktok: "✅ تم ربط حساب TikTok Ads بنجاح!",
      linkedin: "✅ تم ربط حساب LinkedIn Ads بنجاح!",
      x: "✅ تم ربط حساب X Ads بنجاح!",
      snapchat: "✅ تم ربط حساب Snapchat Ads بنجاح!",
    };

    const errorMessages: Record<string, string> = {
      google_denied: "❌ تم رفض إذن Google Ads",
      meta_denied: "❌ تم رفض إذن Meta Ads",
      microsoft_denied: "❌ تم رفض إذن Microsoft Ads",
      tiktok_denied: "❌ تم رفض إذن TikTok Ads",
      linkedin_denied: "❌ تم رفض إذن LinkedIn Ads",
      x_denied: "❌ تم رفض إذن X Ads",
      snapchat_denied: "❌ تم رفض إذن Snapchat Ads",
    };

    if (success && successMessages[success]) {
      setToast({ message: successMessages[success], type: "success" });
      window.history.replaceState({}, "", window.location.pathname);
    } else if (error) {
      const msg = errorMessages[error] || `❌ حدث خطأ: ${error}`;
      setToast({ message: msg, type: "error" });
      window.history.replaceState({}, "", window.location.pathname);
    }
  }, []);

  // ── Load connections from Supabase ──
  const fetchConnections = useCallback(async () => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from("platform_connections")
        .select("id, platform, account_name, status, updated_at")
        .eq("status", "active");

      if (!error && data) {
        setConnections(data as PlatformConnection[]);
      }
    } catch (e) {
      console.error("Error fetching connections:", e);
    } finally {
      setLoading(false);
    }
  }, [supabase]);

  useEffect(() => {
    fetchConnections();

    // Real-time subscription
    const channel = supabase
      .channel("platform_connections_realtime")
      .on(
        "postgres_changes",
        { event: "*", schema: "public", table: "platform_connections" },
        () => fetchConnections()
      )
      .subscribe();

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

  // ── Disconnect handler ──
  async function handleDisconnect(platformId: string, connectionId: string) {
    if (!confirm(`هل أنت متأكد من فصل هذه المنصة؟ ستحتاج إلى إعادة ربطها للمزامنة.`)) return;
    setDisconnectingId(platformId);
    try {
      await supabase
        .from("platform_connections")
        .update({ status: "inactive", updated_at: new Date().toISOString() })
        .eq("id", connectionId);
      setToast({ message: "تم فصل المنصة بنجاح.", type: "success" });
      fetchConnections();
    } catch {
      setToast({ message: "فشل فصل المنصة. حاول مجدداً.", type: "error" });
    } finally {
      setDisconnectingId(null);
    }
  }

  // ── Sync handler ──
  async function handleSync(platform: Platform) {
    if (!platform.syncUrl) return;
    setSyncingId(platform.id);
    try {
      const res = await fetch(platform.syncUrl);
      const data = await res.json();
      if (res.ok && data.success) {
        setToast({ message: data.message || "تمت المزامنة بنجاح!", type: "success" });
        fetchConnections();
      } else {
        setToast({ message: data.error || "فشلت المزامنة.", type: "error" });
      }
    } catch {
      setToast({ message: "فشل الاتصال بالخادم.", type: "error" });
    } finally {
      setSyncingId(null);
    }
  }

  const getConnection = (platformId: string) =>
    connections.find((c) => c.platform === platformId);

  const connectedCount = connections.length;

  return (
    <div className="p-6 space-y-10 bg-[#0a0e19] min-h-screen text-right" dir="rtl">

      {/* Header */}
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white mb-1">التكاملات والربط</h1>
          <p className="text-gray-500 text-xs leading-relaxed max-w-lg">
            ربط حسابات الإعلانات الخاصة بك عبر OAuth الرسمي للحصول على بيانات حقيقية ومزامنة فورية.
          </p>
        </div>
        <div className="flex items-center gap-2 bg-[#101418] border border-gray-800 rounded-2xl px-4 py-2">
          <div className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse" />
          <span className="text-xs text-gray-300 font-semibold">
            {connectedCount} منصة مرتبطة
          </span>
        </div>
      </div>

      {/* Stats row */}
      <div className="grid grid-cols-3 gap-4">
        {[
          { label: "منصات مرتبطة", value: connectedCount, icon: <Wifi className="w-4 h-4 text-emerald-400" /> },
          { label: "منصات متاحة", value: AD_PLATFORMS.length, icon: <Settings className="w-4 h-4 text-blue-400" /> },
          { label: "حالة الربط", value: connectedCount > 0 ? "نشط" : "لا يوجد", icon: connectedCount > 0 ? <CheckCircle2 className="w-4 h-4 text-emerald-400" /> : <WifiOff className="w-4 h-4 text-gray-500" /> },
        ].map((stat) => (
          <div key={stat.label} className="bg-[#101418] border border-gray-800/80 rounded-2xl p-4 flex items-center gap-3">
            {stat.icon}
            <div>
              <div className="text-white font-bold text-lg">{stat.value}</div>
              <div className="text-gray-500 text-[11px]">{stat.label}</div>
            </div>
          </div>
        ))}
      </div>

      {/* Ad Platforms */}
      <div className="space-y-4">
        <div className="flex items-center justify-between border-b border-gray-800 pb-3">
          <h2 className="text-white font-bold text-sm">منصات الإعلانات</h2>
          <span className="text-[10px] text-gray-500 bg-gray-800/50 px-2 py-1 rounded-lg">
            OAuth 2.0 رسمي
          </span>
        </div>

        {loading ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
            {[...Array(7)].map((_, i) => (
              <div key={i} className="bg-[#101418] border border-gray-800/50 rounded-2xl p-5 h-48 animate-pulse" />
            ))}
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
            {AD_PLATFORMS.map((p) => (
              <PlatformCard
                key={p.id}
                platform={p}
                connection={getConnection(p.id)}
                onDisconnect={handleDisconnect}
                onSync={handleSync}
                syncingId={syncingId}
                disconnectingId={disconnectingId}
              />
            ))}
          </div>
        )}
      </div>

      {/* Analytics */}
      <div className="space-y-4">
        <div className="flex items-center justify-between border-b border-gray-800 pb-3">
          <h2 className="text-white font-bold text-sm">التحليلات والتتبع</h2>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          {ANALYTICS_PLATFORMS.map((p) => (
            <PlatformCard
              key={p.id}
              platform={p}
              connection={getConnection(p.id)}
              onDisconnect={handleDisconnect}
              onSync={handleSync}
              syncingId={syncingId}
              disconnectingId={disconnectingId}
            />
          ))}
        </div>
      </div>

      {/* Setup Guide */}
      <div className="bg-[#101418] border border-blue-500/20 rounded-2xl p-6 space-y-4">
        <div className="flex items-center gap-3">
          <div className="w-8 h-8 rounded-xl bg-blue-500/10 flex items-center justify-center">
            <Settings className="w-4 h-4 text-blue-400" />
          </div>
          <h3 className="text-white font-bold text-sm">متطلبات الإعداد</h3>
        </div>
        <p className="text-xs text-gray-500 leading-relaxed">
          لربط كل منصة، يجب إضافة متغيرات البيئة المقابلة في ملف <code className="text-blue-400 bg-blue-500/10 px-1 py-0.5 rounded">.env.local</code>:
        </p>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          {[
            { platform: "Google Ads", vars: "GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_DEVELOPER_TOKEN" },
            { platform: "Meta Ads", vars: "META_APP_ID, META_APP_SECRET" },
            { platform: "Microsoft Ads", vars: "MICROSOFT_CLIENT_ID, MICROSOFT_CLIENT_SECRET" },
            { platform: "TikTok Ads", vars: "TIKTOK_APP_ID, TIKTOK_APP_SECRET" },
            { platform: "LinkedIn Ads", vars: "LINKEDIN_CLIENT_ID, LINKEDIN_CLIENT_SECRET" },
            { platform: "X (Twitter) Ads", vars: "X_CLIENT_ID, X_CLIENT_SECRET" },
            { platform: "Snapchat Ads", vars: "SNAPCHAT_CLIENT_ID, SNAPCHAT_CLIENT_SECRET" },
          ].map((item) => (
            <div key={item.platform} className="bg-[#0a0e19] rounded-xl p-3 space-y-1">
              <div className="text-xs font-bold text-gray-300">{item.platform}</div>
              <div className="text-[10px] text-gray-600 font-mono">{item.vars}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Toast */}
      {toast && (
        <Toast
          message={toast.message}
          type={toast.type}
          onClose={() => setToast(null)}
        />
      )}
    </div>
  );
}
