"use client";

import React, { useState, useEffect, useMemo } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { useAuth } from "@/context/AuthContext";
import { useSiteSettings } from "@/context/SiteSettingsContext";
import { useResellerCart } from "@/hooks/useResellerCart";
import api from "@/lib/api";
import { Header } from "@/components/Header";
import { Footer } from "@/components/Footer";
import { motion, AnimatePresence } from "framer-motion";
import { 
  LayoutDashboard, 
  ShoppingBag, 
  ShoppingCart, 
  History, 
  Wallet, 
  Settings, 
  LogOut, 
  User, 
  Phone, 
  Mail, 
  MapPin, 
  Plus, 
  Minus, 
  Trash2, 
  CheckCircle, 
  Search, 
  Filter, 
  CreditCard,
  TrendingUp,
  Package,
  Activity,
  AlertCircle,
  X,
  Clock,
  XCircle,
  Calendar,
  Hash,
  ArrowLeft,
  ArrowRight,
  Truck,
  Star,
  Lock,
  Loader2,
  Globe,
  Send,
  MessageSquare,
  MessageCircle,
  ChevronDown
} from "lucide-react";

export default function ResellerPortal() {
  const router = useRouter();
  const { user, loading, logout, checkUser } = useAuth();
  const { settings: siteSettingsData } = useSiteSettings();
  const siteSettings = siteSettingsData?.settings || {};
  const [activeTab, setActiveTab] = useState("dashboard");
  const [profileDropdownOpen, setProfileDropdownOpen] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);

  const handleLogoutClick = async () => {
    if (confirm('Are you sure you want to logout?')) {
      await logout();
      router.push('/login');
    }
  };
  
  // Dashboard Stats State
  const [stats, setStats] = useState<any>({
    wallet_balance: 0,
    total_orders: 0,
    total_sales: 0,
    total_profit: 0,
    total_withdrawn: 0,
    package_name: "No Active Package",
    reseller_status: "pending",
    expires_at: null,
  });

  // Unified reseller cart (localStorage-backed, shared with CartDrawer + shop)
  const { cart, addItem: rAddItem, updateQty: rUpdateQty, updatePrice: rUpdatePrice, clearCart } = useResellerCart();
  const [orderSearchQuery, setOrderSearchQuery] = useState("");

  // Orders History State
  const [orders, setOrders] = useState<any[]>([]);
  const [ordersLoading, setOrdersLoading] = useState(false);

  // Client-side order history logs filter
  const filteredOrders = useMemo(() => {
    const query = orderSearchQuery.trim().toLowerCase();
    if (!query) return orders;
    return orders.filter(ord => 
      ord.order_number?.toLowerCase().includes(query) ||
      ord.customer_name?.toLowerCase().includes(query) ||
      ord.customer_phone?.toLowerCase().includes(query)
    );
  }, [orders, orderSearchQuery]);

  // Embedded Order Detail State
  const [selectedOrderNumber, setSelectedOrderNumber] = useState<string | null>(null);
  const [orderDetail, setOrderDetail] = useState<any>(null);
  const [orderDetailLoading, setOrderDetailLoading] = useState(false);
  const [orderDetailError, setOrderDetailError] = useState("");

  // Wallet Ledger State
  const [ledger, setLedger] = useState<any[]>([]);
  const [withdraws, setWithdraws] = useState<any[]>([]);
  const [withdrawAmount, setWithdrawAmount] = useState("");
  const [withdrawMethod, setWithdrawMethod] = useState("bkash");
  const [withdrawSubmitting, setWithdrawSubmitting] = useState(false);
  const [withdrawSuccess, setWithdrawSuccess] = useState("");
  const [withdrawError, setWithdrawError] = useState("");

  // Payment Settings State
  const [bkashNum, setBkashNum] = useState("");
  const [nagadNum, setNagadNum] = useState("");
  const [rocketNum, setRocketNum] = useState("");
  const [bankDetails, setBankDetails] = useState("");
  const [settingsSuccess, setSettingsSuccess] = useState("");

  // Profile & Verification State
  const [profileName, setProfileName] = useState("");
  const [profileEmail, setProfileEmail] = useState("");
  const [profilePhone, setProfilePhone] = useState("");
  const [profilePassword, setProfilePassword] = useState("");
  const [profilePasswordConfirm, setProfilePasswordConfirm] = useState("");
  
  const [storeName, setStoreName] = useState("");
  const [fbProfile, setFbProfile] = useState("");
  const [fbPage, setFbPage] = useState("");
  const [websiteUrl, setWebsiteUrl] = useState("");
  const [whatsappNum, setWhatsappNum] = useState("");
  const [telegramUser, setTelegramUser] = useState("");

  const [avatarFile, setAvatarFile] = useState<File | null>(null);
  const [nidFrontFile, setNidFrontFile] = useState<File | null>(null);
  const [nidBackFile, setNidBackFile] = useState<File | null>(null);
  const [passportFile, setPassportFile] = useState<File | null>(null);

  const [avatarPreview, setAvatarPreview] = useState("");
  const [nidFrontPreview, setNidFrontPreview] = useState("");
  const [nidBackPreview, setNidBackPreview] = useState("");
  const [passportPreview, setPassportPreview] = useState("");

  const [profileSubmitting, setProfileSubmitting] = useState(false);
  const [profileSuccess, setProfileSuccess] = useState("");
  const [profileError, setProfileError] = useState("");

  const [communityGroups, setCommunityGroups] = useState<any[]>([]);
  const [communityLoading, setCommunityLoading] = useState(false);
  const [expandedGroup, setExpandedGroup] = useState<string | null>(null);

  const fetchCommunityGroups = async (showSpinner = false) => {
    if (communityGroups.length === 0 || showSpinner) {
      setCommunityLoading(true);
    }
    try {
      const res = await api.get("/api/reseller/community-groups");
      if (res.data && res.data.success) {
        setCommunityGroups(res.data.groups || []);
      }
    } catch (err) {
      console.error("Failed to fetch community groups:", err);
    } finally {
      setCommunityLoading(false);
    }
  };

  // Guard: Redirect to landing if not logged in or not reseller
  useEffect(() => {
    if (!loading && (!user || user.role !== "reseller")) {
      router.push("/reseller");
    }
  }, [user, loading, router]);

  // Fetch Stats and Profile Settings when Logged In
  useEffect(() => {
    if (user && user.role === "reseller") {
      fetchStats();
      fetchOrders();
      fetchWalletLedger();
      fetchWithdrawRequests();
      fetchCommunityGroups();

      // Populate settings form
      setBkashNum(user.reseller_bkash_number || "");
      setNagadNum(user.reseller_nagad_number || "");
      setRocketNum(user.reseller_rocket_number || "");
      setBankDetails(user.reseller_bank_details || "");

      // Populate profile form
      setProfileName(user.name || "");
      setProfileEmail(user.email || "");
      setProfilePhone(user.phone || "");
      setStoreName(user.reseller_store_name || "");
      setFbProfile(user.reseller_fb_profile || "");
      setFbPage(user.reseller_fb_page || "");
      setWebsiteUrl(user.reseller_website || "");
      setWhatsappNum(user.reseller_whatsapp || "");
      setTelegramUser(user.reseller_telegram || "");
    }
  }, [user]);

  // Fetch stats details
  const fetchStats = () => {
    api.get("/api/reseller/stats")
      .then(res => {
        if (res.data.success) {
          setStats(res.data.data);
        }
      })
      .catch(err => console.error(err));
  };

  // Fetch orders list
  const fetchOrders = () => {
    setOrdersLoading(true);
    api.get("/api/reseller/orders")
      .then(res => {
        if (res.data.success) {
          setOrders(res.data.data.data || []);
        }
      })
      .catch(err => console.error(err))
      .finally(() => setOrdersLoading(false));
  };

  // Fetch single order detail
  const fetchOrderDetail = (orderNo: string) => {
    setOrderDetailLoading(true);
    setOrderDetailError("");
    api.get(`/api/reseller/orders/${orderNo}`)
      .then(res => {
        if (res.data.success) {
          setOrderDetail(res.data.data);
        } else {
          setOrderDetailError("Order not found.");
        }
      })
      .catch(() => setOrderDetailError("Failed to load order details."))
      .finally(() => setOrderDetailLoading(false));
  };

  useEffect(() => {
    if (selectedOrderNumber) {
      fetchOrderDetail(selectedOrderNumber);
    } else {
      setOrderDetail(null);
    }
  }, [selectedOrderNumber]);

  // Fetch wallet transactions ledger
  const fetchWalletLedger = () => {
    api.get("/api/reseller/wallet-transactions")
      .then(res => {
        if (res.data.success) {
          setLedger(res.data.data.data || []);
        }
      })
      .catch(err => console.error(err));
  };

  // Fetch withdrawal requests
  const fetchWithdrawRequests = () => {
    api.get("/api/reseller/withdraws")
      .then(res => {
        if (res.data.success) {
          setWithdraws(res.data.data.data || []);
        }
      })
      .catch(err => console.error(err));
  };



  // Submit Withdrawal Request
  const handleWithdrawSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setWithdrawError("");
    setWithdrawSuccess("");
    setWithdrawSubmitting(true);

    api.post("/api/reseller/withdraws", {
      amount: parseFloat(withdrawAmount),
      payment_method: withdrawMethod
    })
      .then(res => {
        if (res.data.success) {
          setWithdrawSuccess("Payout request submitted successfully!");
          setWithdrawAmount("");
          fetchStats();
          fetchWithdrawRequests();
          fetchWalletLedger();
        }
      })
      .catch(err => {
        setWithdrawError(err.response?.data?.message || "Failed to submit request.");
      })
      .finally(() => setWithdrawSubmitting(false));
  };

  // Submit Payment Settings updates
  const handleSettingsSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setSettingsSuccess("");

    api.post("/api/reseller/payment-settings", {
      reseller_bkash_number: bkashNum,
      reseller_nagad_number: nagadNum,
      reseller_rocket_number: rocketNum,
      reseller_bank_details: bankDetails
    })
      .then(res => {
        if (res.data.success) {
          setSettingsSuccess("Account settings saved successfully!");
          checkUser();
        }
      })
      .catch(err => {
        alert(err.response?.data?.message || "Failed to save settings.");
      });
  };

  // Submit Profile & Verification updates
  const handleProfileSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setProfileError("");
    setProfileSuccess("");
    
    if (profilePassword && profilePassword !== profilePasswordConfirm) {
      setProfileError("Passwords do not match!");
      return;
    }

    setProfileSubmitting(true);

    const formData = new FormData();
    formData.append("name", profileName);
    formData.append("email", profileEmail);
    if (profilePhone) formData.append("phone", profilePhone);
    if (profilePassword) {
      formData.append("password", profilePassword);
      formData.append("password_confirmation", profilePasswordConfirm);
    }

    formData.append("reseller_store_name", storeName || "");
    formData.append("reseller_fb_profile", fbProfile || "");
    formData.append("reseller_fb_page", fbPage || "");
    formData.append("reseller_website", websiteUrl || "");
    formData.append("reseller_whatsapp", whatsappNum || "");
    formData.append("reseller_telegram", telegramUser || "");

    if (avatarFile) formData.append("avatar", avatarFile);
    if (nidFrontFile) formData.append("reseller_nid_front", nidFrontFile);
    if (nidBackFile) formData.append("reseller_nid_back", nidBackFile);
    if (passportFile) formData.append("reseller_passport_photo", passportFile);

    api.post("/api/reseller/profile", formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      }
    })
      .then(res => {
        if (res.data.success) {
          setProfileSuccess("Profile and verification documents submitted successfully!");
          setProfilePassword("");
          setProfilePasswordConfirm("");
          setAvatarFile(null);
          setNidFrontFile(null);
          setNidBackFile(null);
          setPassportFile(null);
          
          // Revoke local preview URLs
          if (avatarPreview) URL.revokeObjectURL(avatarPreview);
          if (nidFrontPreview) URL.revokeObjectURL(nidFrontPreview);
          if (nidBackPreview) URL.revokeObjectURL(nidBackPreview);
          if (passportPreview) URL.revokeObjectURL(passportPreview);
          
          setAvatarPreview("");
          setNidFrontPreview("");
          setNidBackPreview("");
          setPassportPreview("");

          checkUser();
        }
      })
      .catch(err => {
        setProfileError(err.response?.data?.message || "Failed to update profile.");
      })
      .finally(() => setProfileSubmitting(false));
  };

  // Render Loader
  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-slate-50">
        <div className="w-12 h-12 border-4 border-emerald-500 border-t-transparent rounded-full animate-spin"></div>
      </div>
    );
  }

  // Guard: Redirecting...
  if (!user || user.role !== "reseller") {
    return null;
  }

  const apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000";
  const storeLogoUrl = siteSettings.store_logo
    ? (siteSettings.store_logo.startsWith("http") ? siteSettings.store_logo : `${apiUrl}/storage/${siteSettings.store_logo}`)
    : null;
  const siteName = siteSettings.site_name || "Sawdabazar";

  // Render Pending/Expired screen if not active
  if (user.reseller_status !== "active") {
    return (
      <>
        <Header />
        <main className="bg-slate-50 min-h-screen pb-16 relative" style={{ fontFamily: 'var(--font-open-sans), sans-serif' }}>
          {/* Background decoration elements */}
          <div className="absolute top-0 left-1/4 w-96 h-96 bg-emerald-500/5 rounded-full blur-3xl" />
          <div className="absolute bottom-10 right-1/4 w-96 h-96 bg-indigo-500/5 rounded-full blur-3xl" />

          <div className="max-w-4xl mx-auto px-4 pt-12 relative z-10">
            {/* Main verification card */}
            <div className="bg-white border border-slate-200/80 rounded-3xl shadow-xl shadow-slate-100/50 p-6 sm:p-10 space-y-8">
              
              {/* Status Header */}
              <div className="text-center space-y-3">
                <div className="inline-flex items-center justify-center p-4 rounded-full bg-amber-500/10 text-amber-500 mb-2">
                  <AlertCircle size={40} />
                </div>
                <h1 className="text-2xl sm:text-3xl font-bold text-slate-900 tracking-tight">Reseller Verification Portal</h1>
                <p className="text-slate-550 max-w-md mx-auto text-sm sm:text-base">
                  {user.reseller_status === "pending" && "Please upload your verification documents to activate your reseller account."}
                  {user.reseller_status === "rejected" && "Your verification was rejected. Please review the reason below and re-submit your documents."}
                  {user.reseller_status === "under_review" && "Your documents are currently under review by our administration team."}
                  {user.reseller_status === "suspended" && "Your reseller account has been suspended. Please contact support."}
                  {user.reseller_status === "expired" && "Your reseller account has expired. Please contact support."}
                </p>
              </div>

              {/* Rejection Warning Banner */}
              {user.reseller_status === "rejected" && user.reseller_rejection_reason && (
                <div className="p-5 bg-rose-50 border border-rose-200 rounded-2xl flex gap-3 text-left">
                  <div className="text-rose-500 flex-shrink-0 mt-0.5">
                    <XCircle size={20} />
                  </div>
                  <div>
                    <h3 className="text-sm font-semibold text-rose-800">Rejection Reason</h3>
                    <p className="text-xs text-rose-600 mt-1 leading-relaxed">{user.reseller_rejection_reason}</p>
                  </div>
                </div>
              )}

              {/* SUCCESS & ERROR MESSAGE BANNERS FOR UPLOADS */}
              {profileSuccess && (
                <div className="p-4 bg-emerald-50 border border-emerald-250 text-emerald-800 rounded-xl text-sm font-medium">
                  {profileSuccess}
                </div>
              )}
              {profileError && (
                <div className="p-4 bg-rose-50 border border-rose-250 text-rose-850 rounded-xl text-sm font-medium">
                  {profileError}
                </div>
              )}

              {/* CASE 1: PENDING OR REJECTED (UPLOAD FORM) */}
              {(user.reseller_status === "pending" || user.reseller_status === "rejected") && (
                <form onSubmit={handleProfileSubmit} className="space-y-8">
                  
                  {/* Grid of File Uploads */}
                  <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
                    {[
                      { 
                        label: "Profile Picture", 
                        field: "avatar", 
                        fileState: avatarFile, 
                        setFile: setAvatarFile,
                        preview: avatarPreview,
                        setPreview: setAvatarPreview,
                        existing: user?.avatar ? `${apiUrl}/storage/${user.avatar}` : null,
                        desc: "Square format headshot"
                      },
                      { 
                        label: "NID Card (Front)", 
                        field: "reseller_nid_front", 
                        fileState: nidFrontFile, 
                        setFile: setNidFrontFile,
                        preview: nidFrontPreview,
                        setPreview: setNidFrontPreview,
                        existing: user?.reseller_nid_front ? `${apiUrl}/storage/${user.reseller_nid_front}` : null,
                        desc: "Clear snapshot of front"
                      },
                      { 
                        label: "NID Card (Back)", 
                        field: "reseller_nid_back", 
                        fileState: nidBackFile, 
                        setFile: setNidBackFile,
                        preview: nidBackPreview,
                        setPreview: setNidBackPreview,
                        existing: user?.reseller_nid_back ? `${apiUrl}/storage/${user.reseller_nid_back}` : null,
                        desc: "Clear snapshot of back"
                      },
                      { 
                        label: "Passport Size Photo", 
                        field: "reseller_passport_photo", 
                        fileState: passportFile, 
                        setFile: setPassportFile,
                        preview: passportPreview,
                        setPreview: setPassportPreview,
                        existing: user?.reseller_passport_photo ? `${apiUrl}/storage/${user.reseller_passport_photo}` : null,
                        desc: "Standard photo with light bg"
                      },
                    ].map(doc => (
                      <div key={doc.field} className="space-y-2 flex flex-col justify-between border border-slate-200 hover:border-emerald-200 rounded-2xl p-4 bg-slate-50/20 transition-all group relative">
                        <div className="space-y-1">
                          <span className="text-xs font-semibold text-slate-800 truncate block">{doc.label}</span>
                          <p className="text-[10px] text-slate-500 leading-normal">{doc.desc}</p>
                        </div>
                        
                        {/* Drag and Drop Selector box */}
                        <div className="mt-4 relative border border-dashed border-slate-200 group-hover:border-emerald-500/50 rounded-xl p-3 flex flex-col items-center justify-center gap-2.5 min-h-[110px] bg-slate-50/40 transition-all overflow-hidden">
                          {doc.preview ? (
                            <img src={doc.preview} className="absolute inset-0 w-full h-full object-cover" />
                          ) : doc.existing ? (
                            <img src={doc.existing} className="absolute inset-0 w-full h-full object-cover opacity-80 group-hover:opacity-60 transition-opacity" />
                          ) : (
                            <Package size={20} className="text-slate-400 group-hover:text-emerald-500 transition-colors" />
                          )}

                          {/* File status overlay label */}
                          <div className={`relative px-2 py-0.5 rounded text-[8px] font-semibold uppercase tracking-wider ${
                            doc.fileState ? "bg-amber-100 text-amber-700 border border-amber-200" :
                            doc.existing ? "bg-emerald-100 text-emerald-700 border border-emerald-200" :
                            "bg-white text-slate-500 border border-slate-200"
                          }`}>
                            {doc.fileState ? "Pending Save" : doc.existing ? "Uploaded" : "No File"}
                          </div>

                          {doc.fileState && (
                            <span className="relative text-[9px] text-slate-555 font-mono font-semibold">
                              {(doc.fileState.size / (1024 * 1024)).toFixed(2)} MB
                            </span>
                          )}

                          {/* Hidden file input */}
                          <input 
                            type="file" 
                            accept="image/jpeg,image/png,image/jpg"
                            onChange={e => {
                              const file = e.target.files?.[0];
                              if (file) {
                                doc.setFile(file);
                                const url = URL.createObjectURL(file);
                                doc.setPreview(url);
                              }
                            }}
                            className="absolute inset-0 opacity-0 cursor-pointer w-full h-full z-10"
                          />
                        </div>
                      </div>
                    ))}
                  </div>

                  {/* Submission and logout buttons */}
                  <div className="flex flex-col sm:flex-row items-center justify-between gap-4 pt-6 border-t border-slate-200">
                    <button 
                      type="button"
                      onClick={logout}
                      className="px-6 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 font-medium text-sm rounded-xl transition-all w-full sm:w-auto cursor-pointer"
                    >
                      Sign Out
                    </button>
                    <button 
                      type="submit"
                      disabled={profileSubmitting}
                      className="px-8 py-3 bg-gradient-to-r from-emerald-500 to-teal-500 hover:from-emerald-400 hover:to-teal-400 disabled:from-slate-800 disabled:to-slate-800 disabled:text-slate-500 text-white font-medium text-sm rounded-xl transition-all flex items-center justify-center gap-2 w-full sm:w-auto cursor-pointer shadow-[0_0_20px_rgba(16,185,129,0.15)]"
                    >
                      {profileSubmitting && <Loader2 className="w-4 h-4 animate-spin" />}
                      Submit Documents for Verification
                    </button>
                  </div>
                </form>
              )}

              {/* CASE 2: UNDER REVIEW */}
              {user.reseller_status === "under_review" && (
                <div className="space-y-8">
                  {/* Status Banner */}
                  <div className="p-6 bg-gradient-to-r from-amber-50 to-orange-50/50 border border-amber-100 rounded-2xl flex items-center gap-4 text-left">
                    <div className="w-12 h-12 rounded-full bg-amber-500/10 flex items-center justify-center text-amber-500 flex-shrink-0 animate-pulse">
                      <Clock size={24} />
                    </div>
                    <div>
                      <h3 className="text-base font-semibold text-amber-800">Verification in Progress</h3>
                      <p className="text-sm text-amber-600 mt-1 leading-relaxed">
                        We have received your verification documents. Our team is currently reviewing your profile. 
                        This process usually takes up to 24 hours. We will notify you once approved.
                      </p>
                    </div>
                  </div>

                  {/* Read-Only Previews Grid */}
                  <div className="space-y-4">
                    <h3 className="text-sm font-semibold text-slate-800 uppercase tracking-wider">Submitted Documents</h3>
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
                      {[
                        { label: "Profile Picture", path: user.avatar },
                        { label: "NID Card (Front)", path: user.reseller_nid_front },
                        { label: "NID Card (Back)", path: user.reseller_nid_back },
                        { label: "Passport Size Photo", path: user.reseller_passport_photo },
                      ].map(doc => (
                        <div key={doc.label} className="border border-slate-200 rounded-2xl p-4 bg-slate-50/10 flex flex-col items-center justify-between min-h-[180px]">
                          <span className="text-xs font-semibold text-slate-700 mb-2 truncate block w-full text-center">{doc.label}</span>
                          <div className="relative w-full h-32 rounded-xl overflow-hidden bg-slate-100 border border-slate-200 flex items-center justify-center">
                            {doc.path ? (
                              <img src={`${apiUrl}/storage/${doc.path}`} className="w-full h-full object-cover" />
                            ) : (
                              <div className="text-center text-slate-400 p-2">
                                <Package size={24} className="mx-auto mb-1" />
                                <span className="text-[10px]">No File Submitted</span>
                              </div>
                            )}
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>

                  {/* Sign out options */}
                  <div className="flex justify-start pt-6 border-t border-slate-200">
                    <button 
                      onClick={logout}
                      className="px-6 py-2.5 bg-slate-800 hover:bg-slate-700 text-white font-medium text-sm rounded-xl transition-all cursor-pointer"
                    >
                      Sign Out
                    </button>
                  </div>
                </div>
              )}

              {/* CASE 3: EXPIRED OR SUSPENDED */}
              {(user.reseller_status === "expired" || user.reseller_status === "suspended") && (
                <div className="space-y-6 text-center max-w-md mx-auto">
                  <div className="w-16 h-16 bg-rose-100 text-rose-600 rounded-full flex items-center justify-center mx-auto">
                    <Lock size={32} />
                  </div>
                  <h2 className="text-xl font-bold text-slate-800">Access Denied</h2>
                  <p className="text-sm text-slate-550 leading-relaxed">
                    {user.reseller_status === "expired" 
                      ? "Your reseller membership has expired. Please renew your package or contact administration." 
                      : "Your reseller account has been suspended due to policy violations. Please contact administration for support."}
                  </p>
                  <div className="flex flex-col sm:flex-row gap-4 items-center justify-center pt-4">
                    <button 
                      onClick={logout}
                      className="px-6 py-2.5 bg-slate-800 hover:bg-slate-700 text-white font-medium text-sm rounded-xl transition-all w-full sm:w-auto cursor-pointer"
                    >
                      Sign Out
                    </button>
                    <a 
                      href="mailto:support@sawdabazar.com"
                      className="px-6 py-2.5 border border-slate-200 hover:bg-slate-50 text-slate-700 font-medium text-sm rounded-xl transition-all w-full sm:w-auto text-center"
                    >
                      Contact Support
                    </a>
                  </div>
                </div>
              )}

            </div>
          </div>
        </main>
        <Footer />
      </>
    );
  }

  const formatPrice = (amount: number) => {
    const val = Number(amount || 0);
    return "৳" + (val % 1 === 0 ? val.toLocaleString("en-BD") : val.toLocaleString("en-BD", { minimumFractionDigits: 2, maximumFractionDigits: 2 }));
  };

  // Render Unified Dashboard Shell
  return (
    <>
      <Header />
      <main className="bg-slate-50 min-h-screen pb-16 relative" style={{ fontFamily: 'var(--font-open-sans), sans-serif' }}>
        
        {/* Header Gradient Banner Background — Desktop only */}
        <div className="hidden lg:block w-full h-48 bg-gradient-to-r from-[#115e59] via-[#0f766e] to-[#1e1b4b] rounded-b-[40px] shadow-md relative overflow-hidden">
          {/* Elegant dynamic green glow & grid pattern overlay */}
          <div className="absolute inset-0 bg-[radial-gradient(circle_at_30%_20%,_rgba(16,185,129,0.25)_0%,_transparent_65%)]"></div>
          <div className="absolute inset-0 opacity-10 bg-[linear-gradient(to_right,#ffffff_1px,transparent_1px),linear-gradient(to_bottom,#ffffff_1px,transparent_1px)] bg-[size:4rem_4rem]"></div>
        </div>

        {/* Mobile menu floating toggle button */}
        {!mobileMenuOpen && (
          <button
            onClick={() => setMobileMenuOpen(true)}
            className="lg:hidden fixed right-0 top-1/2 -translate-y-1/2 z-50 w-12 h-12 bg-[#2C3333] text-white rounded-l-2xl shadow-[0_4px_20px_rgba(0,0,0,0.3)] flex items-center justify-center hover:bg-neutral-700 active:scale-95 transition-all duration-200"
            aria-label="Open reseller dashboard menu"
          >
            <LayoutDashboard className="h-6 w-6" />
          </button>
        )}

        {/* Mobile Sidebar Drawer Overlay */}
        {mobileMenuOpen && (
          <div
            className="lg:hidden fixed inset-0 z-40 flex"
            onClick={() => setMobileMenuOpen(false)}
          >
            <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" />
            <div
              className="relative ml-auto w-[300px] max-w-[85vw] h-full bg-white shadow-2xl flex flex-col animate-slide-in-right"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="bg-gradient-to-r from-emerald-500 via-teal-600 to-indigo-600 p-5 flex items-center justify-between">
                <div>
                  <p className="text-white font-medium text-base truncate">{user?.name}</p>
                  <p className="text-white/80 text-sm mt-0.5 truncate">
                    Reseller Portal {user?.reseller_code && `(ID: ${user.reseller_code})`} • {user?.email}
                  </p>
                </div>
                <button
                  onClick={() => setMobileMenuOpen(false)}
                  className="w-8 h-8 rounded-full bg-white/20 flex items-center justify-center text-white hover:bg-white/30 transition-colors"
                >
                  <X className="h-4 w-4" />
                </button>
              </div>

              <nav className="flex-1 overflow-y-auto py-4 px-3 space-y-1">
                {[
                  { id: "dashboard", label: "Dashboard", icon: LayoutDashboard },
                  { id: "orders", label: "Order History", icon: History },
                  { id: "wallet", label: "Wallet & Cashout", icon: Wallet },
                  { id: "settings", label: "Payment Settings", icon: Settings },
                  { id: "profile", label: "Profile & KYC Settings", icon: User },
                  { id: "community", label: "Support & Groups", icon: MessageSquare },
                ].map(item => (
                  <button
                    key={item.id}
                    onClick={() => {
                      setSelectedOrderNumber(null);
                      setActiveTab(item.id);
                      if (item.id === "wallet") { fetchWalletLedger(); fetchWithdrawRequests(); }
                      if (item.id === "community") fetchCommunityGroups();
                      setMobileMenuOpen(false);
                    }}
                    className={`w-full flex items-center justify-between px-4 py-3 rounded-xl text-[15px] font-semibold transition-all ${
                      activeTab === item.id
                        ? "bg-[#2C3333] text-white shadow-md"
                        : "text-[#767A7A] hover:bg-slate-50 hover:text-[#2C3333]"
                    }`}
                  >
                    <span className="flex items-center gap-2.5">
                      <item.icon className="h-4.5 w-4.5" />
                      {item.label}
                    </span>
                  </button>
                ))}
              </nav>

              <div className="shrink-0 p-4 pb-6 border-t border-slate-100">
                <button
                  onClick={() => { setMobileMenuOpen(false); handleLogoutClick(); }}
                  className="w-full flex items-center justify-center gap-2 py-3 text-[15px] font-medium text-white bg-[#2C3333] hover:bg-neutral-800 rounded-xl transition-all cursor-pointer shadow-md"
                >
                  <LogOut className="h-5 w-5" />
                  Logout
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Mobile-only user identity bar */}
        <div className="lg:hidden w-full bg-gradient-to-r from-emerald-500 via-teal-600 to-indigo-600 px-4 py-4 flex items-center gap-3 relative overflow-hidden">
          <div className="absolute inset-0 bg-black/10" />
          <div className="relative w-10 h-10 rounded-full bg-white/20 flex items-center justify-center shrink-0">
            <User className="h-5 w-5 text-white" />
          </div>
          <div className="relative overflow-hidden">
            <p className="text-white font-medium text-sm leading-tight truncate">{user?.name}</p>
            <p className="text-white/75 text-sm truncate">
              Reseller Portal {user?.reseller_code && `(ID: ${user.reseller_code})`} • {user?.email}
            </p>
          </div>
        </div>

        {/* Main Grid Container */}
        <div className="mx-auto max-w-7xl px-0 sm:px-6 lg:px-8 mt-4 lg:-mt-28 relative z-10">
          <div className="grid grid-cols-1 lg:grid-cols-4 gap-8 items-start">
            
            {/* Sidebar Column (Left Column) - Hidden on mobile */}
            <div className="hidden lg:flex lg:col-span-1 flex-col gap-4">
              
              {/* User Info Card */}
              <div className="bg-[#2d2d2d] text-white p-5 text-left rounded-[24px] shadow-[0_8px_30px_rgb(0,0,0,0.03)] border border-neutral-800/10 flex items-center gap-4">
                <div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-emerald-500/20 to-teal-500/20 flex items-center justify-center text-emerald-450 border border-emerald-500/20 overflow-hidden shadow-inner shrink-0">
                  {user?.avatar ? (
                    <img src={`${apiUrl}/storage/${user.avatar}`} className="w-full h-full object-cover" />
                  ) : (
                    <span className="font-medium text-base">{user?.name?.charAt(0).toUpperCase()}</span>
                  )}
                </div>
                <div className="overflow-hidden">
                  <h2 className="text-base font-medium truncate text-white leading-tight">{user?.name}</h2>
                  <span className="text-[10px] font-medium text-emerald-400 uppercase tracking-wider block mt-1.5">
                    Reseller Partner {user?.reseller_code && `· ID: ${user.reseller_code}`}
                  </span>
                </div>
              </div>

              {/* Sidebar Menu */}
              <div className="user-sidebar-menus bg-white rounded-[24px] border border-slate-200/60 shadow-[0_8px_30px_rgb(0,0,0,0.03)] pt-[20px] px-[16px] pb-[24px] text-[#2C3333]">
                <ul className="user-sidebar-menu-list flex flex-col space-y-1 text-left">
                  {[
                    { id: "dashboard", label: "Dashboard", icon: LayoutDashboard },
                    { id: "orders", label: "Order History", icon: History },
                    { id: "wallet", label: "Wallet & Cashout", icon: Wallet },
                    { id: "settings", label: "Payment Settings", icon: Settings },
                    { id: "profile", label: "Profile & KYC Settings", icon: User },
                    { id: "community", label: "Support & Groups", icon: MessageSquare },
                  ].map(item => (
                    <li key={item.id} className="w-full">
                      <button
                        onClick={() => {
                          setSelectedOrderNumber(null);
                          setActiveTab(item.id);
                          if (item.id === "wallet") { fetchWalletLedger(); fetchWithdrawRequests(); }
                          if (item.id === "community") fetchCommunityGroups();
                        }}
                        className={`w-full flex items-center justify-between px-4 py-[12px] text-[15px] font-semibold rounded-xl transition-all cursor-pointer font-sans ${
                          activeTab === item.id
                            ? "bg-[#2C3333] text-white shadow-md"
                            : "text-[#767A7A] hover:bg-slate-50 hover:text-[#2C3333]"
                        }`}
                      >
                        <span className="flex items-center gap-2.5">
                          <item.icon className="h-4.5 w-4.5" />
                          {item.label}
                        </span>
                        {activeTab === item.id && <ArrowRight className="h-3.5 w-3.5 text-white" />}
                      </button>
                    </li>
                  ))}
                  
                  {/* Logout Button */}
                  <li className="w-full pt-3 border-t border-slate-100 mt-2">
                    <button
                      onClick={handleLogoutClick}
                      className="w-full flex items-center gap-2.5 px-4 py-[12px] text-[15px] font-semibold rounded-xl text-rose-600 hover:bg-rose-50 transition-all cursor-pointer"
                    >
                      <LogOut className="h-4.5 w-4.5" />
                      Logout
                    </button>
                  </li>
                </ul>
              </div>
            </div>

            {/* Right Column: Main Content area */}
            <div className="lg:col-span-3 space-y-6">

              {/* Dynamic Pages tab views */}
              <div className="bg-white rounded-2xl sm:rounded-[24px] border border-slate-200/60 shadow-[0_8px_30px_rgb(0,0,0,0.02)] p-4 sm:p-6 text-[#2C3333]">
                <AnimatePresence mode="wait">

            
            {/* TAB 1: Dashboard overview */}
            {activeTab === "dashboard" && (
              <motion.div 
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="space-y-8"
              >
                {/* Reseller Verification Banners */}
                {user && user.reseller_status !== 'active' && (
                  <div className="p-4 sm:p-5 rounded-2xl border flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 transition-all"
                       style={{
                         fontFamily: 'var(--font-open-sans), sans-serif',
                         backgroundColor: user.reseller_status === 'under_review' ? '#fef3c7' : (user.reseller_status === 'rejected' || user.reseller_status === 'suspended' ? '#fef2f2' : '#f8fafc'),
                         borderColor: user.reseller_status === 'under_review' ? '#fde68a' : (user.reseller_status === 'rejected' || user.reseller_status === 'suspended' ? '#fca5a5' : '#e2e8f0'),
                       }}
                  >
                    <div className="flex gap-3.5 items-start">
                      <div className="mt-0.5 shrink-0">
                        {user.reseller_status === 'under_review' ? (
                          <div className="w-9 h-9 rounded-xl bg-amber-100 text-amber-600 flex items-center justify-center">
                            <Clock size={18} />
                          </div>
                        ) : user.reseller_status === 'rejected' || user.reseller_status === 'suspended' ? (
                          <div className="w-9 h-9 rounded-xl bg-rose-100 text-rose-600 flex items-center justify-center">
                            <AlertCircle size={18} />
                          </div>
                        ) : (
                          <div className="w-9 h-9 rounded-xl bg-slate-100 text-slate-600 flex items-center justify-center">
                            <Lock size={18} />
                          </div>
                        )}
                      </div>
                      <div>
                        <h4 className="font-semibold text-sm text-slate-800">
                          {user.reseller_status === 'under_review' ? 'Verification Pending Approval' : 
                           user.reseller_status === 'rejected' ? 'Verification Rejected' : 
                           user.reseller_status === 'suspended' ? 'Account Suspended' : 
                           'Account Verification Required'}
                        </h4>
                        <p className="text-xs text-slate-600 mt-1 font-normal leading-relaxed">
                          {user.reseller_status === 'under_review' ? (
                            'Your documents are under review. Account verification normally takes up to 24 hours. We will notify you once approved.'
                          ) : user.reseller_status === 'rejected' ? (
                            `Reason: ${user.reseller_rejection_reason || 'Please upload clear verification documents.'}`
                          ) : user.reseller_status === 'suspended' ? (
                            'Your account has been suspended by admin. Please contact support to resolve this issue.'
                          ) : (
                            'You must complete your profile and upload verification documents (NID card & passport photo) to place reseller orders and join support groups.'
                          )}
                        </p>
                      </div>
                    </div>
                    {/* Action button */}
                    {['pending', 'rejected'].includes(user.reseller_status || '') && (
                      <button 
                        onClick={() => setActiveTab('settings')}
                        className="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-white font-medium text-xs rounded-xl shadow transition-all shrink-0"
                      >
                        Upload Documents
                      </button>
                    )}
                  </div>
                )}

                {/* Stats row cards */}
                <div className="grid grid-cols-2 md:grid-cols-4 gap-3 sm:gap-6">
                  {[
                    { 
                      label: "Wallet Balance", 
                      val: formatPrice(stats.wallet_balance), 
                      desc: "Available for withdrawal", 
                      color: "from-teal-400 to-emerald-600", 
                      shadow: "shadow-teal-500/25 hover:shadow-teal-500/40",
                      icon: Wallet 
                    },
                    { 
                      label: "Total Orders Placed", 
                      val: stats.total_orders, 
                      desc: "Successful shipments", 
                      color: "from-indigo-400 to-blue-600", 
                      shadow: "shadow-indigo-500/25 hover:shadow-indigo-500/40",
                      icon: ShoppingCart 
                    },
                    { 
                      label: "Total Sales Value", 
                      val: formatPrice(stats.total_sales), 
                      desc: "Customer gross value", 
                      color: "from-orange-400 to-amber-600", 
                      shadow: "shadow-orange-500/25 hover:shadow-orange-500/40",
                      icon: TrendingUp 
                    },
                    { 
                      label: "Accumulated Profit", 
                      val: formatPrice(stats.total_profit), 
                      desc: "Net reseller profit margin", 
                      color: "from-emerald-400 to-teal-600", 
                      shadow: "shadow-emerald-500/25 hover:shadow-emerald-500/40",
                      icon: Activity 
                    },
                  ].map((card, i) => (
                    <div 
                      key={i} 
                      className={`p-4 sm:p-6 bg-gradient-to-br ${card.color} rounded-2xl sm:rounded-[28px] relative overflow-hidden shadow-lg ${card.shadow} hover:-translate-y-1.5 transition-all duration-300 border-t border-white/25`}
                    >
                      {/* Glass decorative blobs */}
                      <div className="absolute -right-4 -bottom-4 w-20 h-20 bg-white/10 rounded-full blur-xl"></div>
                      <div className="absolute -left-4 -top-4 w-14 h-14 bg-white/10 rounded-full blur-lg"></div>

                      <div className="flex justify-between items-start mb-4 relative z-10">
                        <span className="text-xs sm:text-sm font-medium text-white/80 uppercase tracking-wider">{card.label}</span>
                        <div className="bg-white/20 p-2 rounded-xl text-white shadow-inner">
                          <card.icon size={18} />
                        </div>
                      </div>
                      
                      <div className="relative z-10 space-y-1 text-left">
                        <h3 className="text-2xl font-semibold text-white tracking-tight font-sans">{card.val}</h3>
                        <p className="text-[10px] text-white/70 font-medium">{card.desc}</p>
                      </div>
                    </div>
                  ))}
                </div>

                {/* Main panel info section */}
                <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                  
                  {/* Package info card */}
                  <div className="lg:col-span-2 p-5 sm:p-7 bg-gradient-to-br from-emerald-50/20 via-slate-50/10 to-teal-50/10 border border-slate-200/80 rounded-2xl sm:rounded-3xl flex flex-col justify-between shadow-sm">
                    <div className="space-y-4">
                      <div className="flex items-center justify-between">
                        <span className="bg-emerald-500/10 text-emerald-600 border border-emerald-500/25 px-3 py-1 text-[10px] font-semibold uppercase rounded-lg tracking-wider">
                          Membership Status
                        </span>
                        <div className="w-8 h-8 rounded-full bg-emerald-500/10 flex items-center justify-center text-emerald-600 shrink-0">
                          <Star size={16} fill="currentColor" />
                        </div>
                      </div>
                      <div>
                        <h3 className="text-lg sm:text-xl font-semibold text-slate-800 tracking-tight">
                          Active Plan: <span className="text-emerald-650">{stats.package_name}</span>
                        </h3>
                        <p className="text-slate-500 text-sm sm:text-sm mt-2 max-w-lg leading-relaxed font-medium">
                          Your account is currently fully active. You have full access to wholesale product pricing. All orders will be printed without branding and shipped directly to customers.
                        </p>
                      </div>
                    </div>

                    <div className="grid grid-cols-2 gap-4 mt-6 pt-5 border-t border-slate-200/60">
                      <div className="bg-white/40 p-3.5 rounded-2xl border border-slate-200/50 shadow-[0_2px_8px_rgba(0,0,0,0.01)]">
                        <span className="text-[10px] text-slate-500 font-medium uppercase tracking-wider block">Plan Validity Ends</span>
                        <p className="text-sm sm:text-sm font-semibold text-slate-800 mt-1">
                          {stats.expires_at ? new Date(stats.expires_at).toLocaleDateString() : "Never Expires"}
                        </p>
                      </div>
                      <div className="bg-white/40 p-3.5 rounded-2xl border border-slate-200/50 shadow-[0_2px_8px_rgba(0,0,0,0.01)]">
                        <span className="text-[10px] text-slate-500 font-medium uppercase tracking-wider block">Total Profit Withdrawn</span>
                        <p className="text-sm sm:text-sm font-semibold text-emerald-600 mt-1">
                          {formatPrice(stats.total_withdrawn)}
                        </p>
                      </div>
                    </div>
                  </div>

                  {/* Payment instructions settings shortcuts */}
                  <div className="p-5 sm:p-7 bg-slate-50/50 border border-slate-200/80 rounded-2xl sm:rounded-3xl flex flex-col justify-between shadow-sm">
                    <div className="space-y-4">
                      <div className="flex items-center justify-between">
                        <div>
                          <h4 className="font-semibold text-slate-800 text-sm">Payout Credentials</h4>
                          <p className="text-[11px] text-slate-500 mt-0.5">Accounts for receiving payouts.</p>
                        </div>
                        <div className="w-8 h-8 rounded-full bg-slate-100 flex items-center justify-center text-slate-500 shrink-0">
                          <Wallet size={16} />
                        </div>
                      </div>
                      
                      <div className="space-y-2.5 mt-3">
                        {/* bKash */}
                        <div className="flex items-center justify-between px-3.5 py-3 bg-white border border-slate-200/60 rounded-xl hover:border-pink-500/20 transition-all shadow-sm">
                          <div className="flex items-center gap-2.5">
                            <span className="w-2 h-2 rounded-full bg-[#E2125B]" />
                            <span className="text-sm font-medium text-slate-700">bKash Personal</span>
                          </div>
                          <span className="font-mono text-sm font-semibold text-slate-800">
                            {user?.reseller_bkash_number || (
                              <span className="text-[10px] text-slate-400 font-sans font-normal">Not Configured</span>
                            )}
                          </span>
                        </div>
                        {/* Nagad */}
                        <div className="flex items-center justify-between px-3.5 py-3 bg-white border border-slate-200/60 rounded-xl hover:border-orange-500/20 transition-all shadow-sm">
                          <div className="flex items-center gap-2.5">
                            <span className="w-2 h-2 rounded-full bg-[#F47321]" />
                            <span className="text-sm font-medium text-slate-700">Nagad Personal</span>
                          </div>
                          <span className="font-mono text-sm font-semibold text-slate-800">
                            {user?.reseller_nagad_number || (
                              <span className="text-[10px] text-slate-400 font-sans font-normal">Not Configured</span>
                            )}
                          </span>
                        </div>
                      </div>
                    </div>

                    <button 
                      onClick={() => setActiveTab("settings")}
                      className="w-full mt-5 py-2.5 bg-white hover:bg-slate-50 text-slate-800 text-sm font-semibold rounded-xl transition-all cursor-pointer border border-slate-200 shadow-sm hover:shadow active:scale-[0.98]"
                    >
                      Update Account Settings
                    </button>
                  </div>

                </div>
              </motion.div>
            )}

            {/* TAB 4: Order History List */}
            {activeTab === "orders" && (
              selectedOrderNumber ? (
                <motion.div 
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -10 }}
                  className="space-y-6"
                >
                  {/* Top Bar with Back Button */}
                  <div className="flex items-center gap-4">
                    <button
                      onClick={() => setSelectedOrderNumber(null)}
                      className="p-2 rounded-lg bg-white border border-slate-200 hover:bg-slate-100 text-slate-500 hover:text-white transition-all flex items-center justify-center cursor-pointer"
                    >
                      <ArrowLeft size={16} />
                    </button>
                    <div>
                      <h3 className="text-lg font-medium text-slate-800">Order Detail</h3>
                      <p className="text-sm text-slate-500 mt-1 font-mono">{selectedOrderNumber}</p>
                    </div>

                    {orderDetail && (
                      <div className="ml-auto flex items-center gap-2">
                        {/* Status Badge */}
                        <span className={`inline-flex items-center gap-1.5 px-3.5 py-1.5 rounded-full text-sm font-semibold border ${
                          orderDetail.status === "completed" || orderDetail.status === "delivered" ? "border-emerald-500/30 bg-emerald-500/10 text-emerald-300" :
                          orderDetail.status === "pending"   ? "border-amber-500/30 bg-amber-500/10 text-amber-300" :
                          orderDetail.status === "processing" ? "border-blue-500/30 bg-blue-500/10 text-blue-300" :
                          orderDetail.status === "shipped"    ? "border-indigo-500/30 bg-indigo-500/10 text-indigo-300" :
                                                              "border-red-500/30 bg-red-500/10 text-red-300"
                        }`}>
                          {orderDetail.status}
                        </span>
                      </div>
                    )}
                  </div>

                  {orderDetailLoading && (
                    <div className="text-center py-12 bg-slate-50/50 border border-slate-200 rounded-3xl">
                      <div className="w-8 h-8 border-3 border-emerald-500 border-t-transparent rounded-full animate-spin mx-auto mb-3"></div>
                      <p className="text-sm text-slate-500">Loading order details...</p>
                    </div>
                  )}

                  {!orderDetailLoading && orderDetailError && (
                    <div className="text-center py-12 bg-slate-50/50 border border-slate-200 rounded-3xl space-y-2">
                      <XCircle size={32} className="text-red-400 mx-auto" />
                      <p className="text-sm font-semibold text-slate-700">Failed to load order details</p>
                      <p className="text-sm text-slate-500">{orderDetailError}</p>
                    </div>
                  )}

                  {!orderDetailLoading && orderDetail && (() => {
                    const profitVal = orderDetail.total_reseller_profit ?? (orderDetail.subtotal - orderDetail.total_reseller_price);
                    const statusSteps = ["Pending", "Processing", "Shipped", "Delivered"];
                    const currentStepVal = orderDetail.status === "pending" ? 0 :
                                           orderDetail.status === "processing" ? 1 :
                                           orderDetail.status === "shipped" ? 2 :
                                           orderDetail.status === "completed" || orderDetail.status === "delivered" ? 3 : -1;
                    
                    return (
                      <div className="space-y-6">
                        {/* Hero Profit Banner */}
                        <div className="relative rounded-2xl sm:rounded-3xl overflow-hidden border border-emerald-100 bg-gradient-to-br from-emerald-50/60 via-[#f0fdf4] to-teal-50/40 p-4 sm:p-6 shadow-sm">
                          <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top_left,rgba(16,185,129,0.06),transparent_60%)]" />
                          <div className="relative flex flex-col md:flex-row md:items-center justify-between gap-6">
                            <div>
                              <p className="text-emerald-800/80 text-[10px] font-medium uppercase tracking-widest mb-1">Your Profit on This Order</p>
                              <p className="text-4xl font-semibold text-emerald-600 font-mono tracking-tight">+{formatPrice(profitVal)}</p>
                              <p className="text-emerald-700/80 text-sm mt-2 font-medium">
                                Margin: {orderDetail.subtotal > 0 ? ((profitVal / orderDetail.subtotal) * 100).toFixed(1) : 0}% &nbsp;·&nbsp;
                                {orderDetail.items?.length} product{orderDetail.items?.length !== 1 ? "s" : ""}
                              </p>
                            </div>
                            <div className="grid grid-cols-2 md:flex gap-6 text-left md:text-right border-t border-emerald-100/50 md:border-t-0 pt-4 md:pt-0">
                              <div>
                                <p className="text-[10px] text-slate-500 uppercase tracking-wider mb-0.5 font-medium">Retail Total</p>
                                <p className="text-lg font-medium text-slate-800 font-mono">{formatPrice(orderDetail.grand_total)}</p>
                              </div>
                              <div>
                                <p className="text-[10px] text-slate-500 uppercase tracking-wider mb-0.5 font-medium">Your Cost</p>
                                <p className="text-lg font-medium text-slate-700 font-mono">{formatPrice(orderDetail.total_reseller_price)}</p>
                              </div>
                            </div>
                          </div>
                        </div>

                        {/* Order Progress Tracker */}
                        {orderDetail.status !== "cancelled" && (
                          <div className="rounded-3xl border border-slate-200 bg-slate-50/50 p-6">
                            <p className="text-[10px] text-slate-500 uppercase tracking-widest font-semibold mb-6">Order Progress</p>
                            <div className="flex items-center justify-between">
                              {statusSteps.map((step, idx) => {
                                const done = idx <= currentStepVal;
                                const isLast = idx === statusSteps.length - 1;
                                return (
                                  <div key={step} className="flex items-center flex-1">
                                    <div className="flex flex-col items-center">
                                      <div className={`w-8 h-8 rounded-full flex items-center justify-center border-2 transition-all ${
                                        done ? "border-emerald-500 bg-emerald-500/20" : "border-slate-700 bg-slate-800"
                                      }`}>
                                        {done ? <CheckCircle size={15} className="text-emerald-400" /> : <div className="w-1.5 h-1.5 rounded-full bg-slate-600" />}
                                      </div>
                                      <p className={`text-[10px] font-semibold mt-2 whitespace-nowrap ${done ? "text-emerald-400" : "text-slate-600"}`}>
                                        {step}
                                      </p>
                                    </div>
                                    {!isLast && (
                                      <div className={`h-0.5 flex-1 mx-2 rounded transition-all ${idx < currentStepVal ? "bg-emerald-500/50" : "bg-slate-800"}`} />
                                    )}
                                  </div>
                                );
                              })}
                            </div>
                          </div>
                        )}

                        {/* Customer & Shipping Row */}
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                          {/* Customer */}
                          <div className="rounded-2xl sm:rounded-3xl border border-slate-200 bg-slate-50/50 p-4 sm:p-6 space-y-4">
                            <div className="flex items-center gap-2">
                              <div className="w-7 h-7 rounded-lg bg-violet-500/15 flex items-center justify-center">
                                <User size={13} className="text-violet-400" />
                              </div>
                              <p className="text-sm font-semibold text-slate-500 uppercase tracking-wider">Customer Details</p>
                            </div>
                            <div className="space-y-3 text-sm text-slate-700">
                              <div className="flex items-center gap-3">
                                <div className="w-8 h-8 rounded-full bg-gradient-to-br from-violet-500/20 to-purple-600/20 flex items-center justify-center text-violet-300 font-medium text-sm border border-violet-500/20 shrink-0">
                                  {orderDetail.customer_name?.charAt(0)?.toUpperCase()}
                                </div>
                                <div>
                                  <p className="text-slate-800 font-medium text-sm leading-none mb-1">{orderDetail.customer_name}</p>
                                  <p className="text-[10px] text-slate-500 leading-none">Reseller End Customer</p>
                                </div>
                              </div>
                              {orderDetail.customer_phone && (
                                <div className="flex items-center gap-2.5">
                                  <Phone size={12} className="text-slate-500" />
                                  <span className="font-mono">{orderDetail.customer_phone}</span>
                                </div>
                              )}
                              {orderDetail.customer_email && (
                                <div className="flex items-center gap-2.5">
                                  <Mail size={12} className="text-slate-500" />
                                  <span className="truncate">{orderDetail.customer_email}</span>
                                </div>
                              )}
                            </div>
                          </div>

                          {/* Shipping */}
                          <div className="rounded-2xl sm:rounded-3xl border border-slate-200 bg-slate-50/50 p-4 sm:p-6 space-y-4">
                            <div className="flex items-center gap-2">
                              <div className="w-7 h-7 rounded-lg bg-blue-500/15 flex items-center justify-center">
                                <MapPin size={13} className="text-blue-400" />
                              </div>
                              <p className="text-sm font-semibold text-slate-500 uppercase tracking-wider">Delivery Details</p>
                            </div>
                            <p className="text-slate-800 text-sm leading-relaxed">{orderDetail.shipping_address || "—"}</p>
                            <div className="grid grid-cols-2 gap-4 pt-3 border-t border-slate-200 text-sm">
                              <div>
                                <p className="text-[10px] text-slate-500 uppercase tracking-wider mb-0.5">Shipping Method</p>
                                <div className="flex items-center gap-1.5 text-slate-700">
                                  <Truck size={12} className="text-blue-400" />
                                  <span className="font-semibold">{orderDetail.shipping_method || "Standard"}</span>
                                </div>
                              </div>
                              <div>
                                <p className="text-[10px] text-slate-500 uppercase tracking-wider mb-0.5">Payment Method</p>
                                <div className="flex items-center gap-1.5 text-slate-700">
                                  <CreditCard size={12} className="text-emerald-400" />
                                  <span className="font-semibold uppercase">{orderDetail.payment_method || "COD"}</span>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>

                        {/* Order Items */}
                        <div className="rounded-3xl border border-slate-200 bg-slate-50/50 overflow-hidden">
                          <div className="px-6 py-4 border-b border-slate-200 flex items-center justify-between">
                            <div className="flex items-center gap-2">
                              <div className="w-7 h-7 rounded-lg bg-amber-500/15 flex items-center justify-center">
                                <ShoppingBag size={13} className="text-amber-400" />
                              </div>
                              <p className="text-sm font-semibold text-slate-500 uppercase tracking-wider">Order Items</p>
                            </div>
                          </div>

                          <div className="grid grid-cols-12 px-6 py-3 text-[10px] font-medium text-slate-500 uppercase tracking-wider border-b border-slate-200 bg-slate-50/20">
                            <div className="col-span-6">Product</div>
                            <div className="col-span-2 text-center">Quantity</div>
                            <div className="col-span-2 text-right">Cost Price</div>
                            <div className="col-span-2 text-right">Retail Price</div>
                          </div>

                          <div className="divide-y divide-slate-850">
                            {orderDetail.items?.map((item: any, idx: number) => (
                              <div key={idx} className="grid grid-cols-12 items-center px-6 py-4 hover:bg-white/10 transition-all">
                                <div className="col-span-6 flex items-center gap-3">
                                  {item.image ? (
                                    <img src={item.image} alt={item.product_name} className="w-10 h-10 rounded-xl object-cover border border-slate-200 shrink-0" />
                                  ) : (
                                    <div className="w-10 h-10 rounded-xl bg-slate-100 flex items-center justify-center shrink-0 border border-slate-200">
                                      <Package size={16} className="text-slate-400" />
                                    </div>
                                  )}
                                  <div className="min-w-0">
                                    <p className="text-slate-800 text-sm font-medium truncate">{item.product_name}</p>
                                    <p className="text-slate-500 text-[10px] font-mono mt-0.5">{item.product_sku}</p>
                                  </div>
                                </div>
                                <div className="col-span-2 text-center">
                                  <span className="w-7 h-7 rounded-lg bg-slate-100 border border-slate-200 text-slate-700 text-sm font-medium flex items-center justify-center mx-auto">
                                    {item.quantity}
                                  </span>
                                </div>
                                <div className="col-span-2 text-right">
                                  <p className="text-slate-500 text-sm font-mono">{formatPrice(item.reseller_price)}</p>
                                </div>
                                <div className="col-span-2 text-right">
                                  <p className="text-slate-800 text-sm font-mono font-medium">{formatPrice(item.price)}</p>
                                </div>
                              </div>
                            ))}
                          </div>

                          <div className="border-t border-slate-200 bg-slate-50/20 px-6 py-4 space-y-2.5 text-sm text-slate-500">
                            <div className="flex justify-between">
                              <span>Subtotal</span>
                              <span className="font-mono text-slate-700">{formatPrice(orderDetail.subtotal)}</span>
                            </div>
                            <div className="flex justify-between">
                              <span>Shipping Cost</span>
                              <span className="font-mono text-slate-700">{formatPrice(orderDetail.shipping_cost)}</span>
                            </div>
                            <div className="flex justify-between items-center text-sm font-medium border-t border-slate-200 pt-3 text-slate-800">
                              <span>Grand Total</span>
                              <span className="font-mono text-slate-800 text-base">{formatPrice(orderDetail.grand_total)}</span>
                            </div>
                            <div className="flex justify-between items-center text-sm font-medium pt-1 border-t border-slate-200/20">
                              <span className="text-emerald-400 flex items-center gap-1.5"><Star size={13} fill="currentColor" /> Your Profit</span>
                              <span className="font-mono text-emerald-400 text-base">+{formatPrice(profitVal)}</span>
                            </div>
                          </div>
                        </div>
                      </div>
                    );
                  })()}
                </motion.div>
              ) : (
                <motion.div 
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -10 }}
                  className="bg-slate-50/50 border border-slate-200 rounded-2xl sm:rounded-3xl p-4 sm:p-6 overflow-hidden"
                >
                  <div className="mb-6 flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                    <div>
                      <h3 className="text-lg font-medium text-slate-800">Reseller Order Logs</h3>
                      <p className="text-sm text-slate-500 mt-1">Logs of all checkout shipments submitted by you.</p>
                    </div>
                    <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 w-full md:w-auto">
                      <div className="relative w-full sm:w-64">
                        <Search className="absolute left-3 top-2.5 text-slate-500" size={14} />
                        <input 
                          type="text"
                          value={orderSearchQuery}
                          onChange={e => setOrderSearchQuery(e.target.value)}
                          placeholder="Search order number, phone..."
                          className="w-full text-sm pl-8 pr-8 py-2 bg-slate-100/60 border border-slate-200 focus:border-emerald-500 rounded-lg outline-none text-slate-800 transition-all placeholder-slate-500"
                        />
                        {orderSearchQuery && (
                          <button
                            type="button"
                            onClick={() => setOrderSearchQuery("")}
                            className="absolute right-2.5 top-2.5 text-slate-500 hover:text-slate-700 transition-colors"
                          >
                            <X size={12} />
                          </button>
                        )}
                      </div>
                      <button 
                        onClick={fetchOrders}
                        className="px-3.5 py-2 bg-slate-800 hover:bg-slate-700 text-white text-sm font-normal rounded-lg transition-all whitespace-nowrap cursor-pointer flex items-center justify-center gap-1.5 shadow-sm"
                      >
                        Refresh Logs
                      </button>
                    </div>
                  </div>

                  {ordersLoading ? (
                    <div className="text-center py-12">
                      <div className="w-8 h-8 border-3 border-emerald-500 border-t-transparent rounded-full animate-spin mx-auto mb-3"></div>
                      <p className="text-sm text-slate-500">Loading order records...</p>
                    </div>
                  ) : orders.length === 0 ? (
                    <div className="text-center py-16 space-y-2">
                      <History className="text-slate-700 mx-auto" size={32} />
                      <p className="text-sm text-slate-500">No reseller orders found in history logs.</p>
                    </div>
                  ) : filteredOrders.length === 0 ? (
                    <div className="text-center py-16 space-y-2">
                      <Search className="text-slate-500 mx-auto" size={32} />
                      <p className="text-sm text-slate-500">No matching reseller orders found for "{orderSearchQuery}".</p>
                    </div>
                  ) : (
                    <div className="overflow-x-auto">
                      <table className="w-full text-left text-sm border-collapse">
                        <thead>
                          <tr className="border-b border-slate-200 text-slate-500 font-medium uppercase tracking-wider">
                            <th className="py-3 px-4 whitespace-nowrap">Order No</th>
                            <th className="py-3 px-4 whitespace-nowrap">Customer Details</th>
                            <th className="py-3 px-4 whitespace-nowrap">Retail Sell Price</th>
                            <th className="py-3 px-4 whitespace-nowrap">Reseller Cost</th>
                            <th className="py-3 px-4 whitespace-nowrap">Your Profit</th>
                            <th className="py-3 px-4 whitespace-nowrap">Status</th>
                            <th className="py-3 px-4 whitespace-nowrap">Date</th>
                          </tr>
                        </thead>
                        <tbody>
                          {filteredOrders.map(ord => (
                            <tr key={ord.id} className="border-b border-slate-100 hover:bg-white/20 text-slate-700 transition-all">
                              <td className="py-4 px-4 whitespace-nowrap">
                                <button
                                  onClick={() => setSelectedOrderNumber(ord.order_number)}
                                  className="font-medium font-mono text-emerald-450 hover:text-emerald-500 hover:underline transition-colors cursor-pointer text-left whitespace-nowrap"
                                >
                                  {ord.order_number}
                                </button>
                              </td>
                              <td className="py-4 px-4 whitespace-nowrap">
                                <p className="font-medium text-slate-800">{ord.customer_name}</p>
                                <span className="text-[10px] text-slate-500 block mt-0.5">{ord.customer_phone}</span>
                              </td>
                              <td className="py-4 px-4 font-mono whitespace-nowrap">{formatPrice(ord.subtotal)}</td>
                              <td className="py-4 px-4 font-mono whitespace-nowrap">{formatPrice(ord.total_reseller_price)}</td>
                              <td className="py-4 px-4 font-medium font-mono text-emerald-450 whitespace-nowrap">+{formatPrice(ord.total_reseller_profit)}</td>
                              <td className="py-4 px-4 whitespace-nowrap">
                                <span className={`px-1.5 py-0.5 text-[8px] font-semibold uppercase tracking-wider rounded-md border ${
                                  ord.status === "completed" || ord.status === "delivered" ? "bg-emerald-50 text-emerald-700 border-emerald-100" :
                                  ord.status === "pending" ? "bg-blue-50 text-blue-700 border-blue-100" :
                                  ord.status === "processing" ? "bg-amber-50 text-amber-700 border-amber-100" :
                                  ord.status === "shipped" ? "bg-sky-50 text-sky-700 border-sky-100" :
                                  "bg-rose-50 text-rose-700 border-rose-100"
                                }`}>
                                  {ord.status}
                                </span>
                              </td>
                              <td className="py-4 px-4 text-slate-500 whitespace-nowrap">{new Date(ord.created_at).toLocaleDateString()}</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  )}
                </motion.div>
              )
            )}

            {/* TAB 5: Wallet Ledgers and Withdrawal Requests */}
            {activeTab === "wallet" && (
              <motion.div 
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="grid grid-cols-1 lg:grid-cols-3 gap-8"
              >
                {/* Ledger & Transactions Table lists */}
                <div className="lg:col-span-2 space-y-6">
                  
                  {/* Ledger transactions block */}
                  <div className="bg-slate-50/50 border border-slate-200 p-4 sm:p-6 rounded-2xl sm:rounded-3xl space-y-4">
                    <h3 className="text-base font-medium text-slate-800">Wallet Transaction Ledger</h3>
                    <div className="overflow-x-auto">
                      <table className="w-full text-left text-sm border-collapse">
                        <thead>
                          <tr className="border-b border-slate-200 text-slate-500 font-medium uppercase">
                            <th className="py-3 px-2">Type</th>
                            <th className="py-3 px-4">Amount</th>
                            <th className="py-3 px-4">Description</th>
                            <th className="py-3 px-4">Status</th>
                            <th className="py-3 px-2">Date</th>
                          </tr>
                        </thead>
                        <tbody>
                          {ledger.length === 0 ? (
                            <tr>
                              <td colSpan={5} className="text-center py-8 text-slate-500">No ledger transactions found.</td>
                            </tr>
                          ) : (
                            ledger.map(tx => (
                              <tr key={tx.id} className="border-b border-slate-100 text-slate-700">
                                <td className="py-3.5 px-2">
                                  <span className={`px-2 py-0.5 text-[9px] font-medium rounded uppercase ${tx.type === "credit" ? "bg-emerald-500/10 text-emerald-400" : "bg-red-500/10 text-red-400"}`}>
                                    {tx.type}
                                  </span>
                                </td>
                                <td className={`py-3.5 px-4 font-mono font-medium ${tx.type === "credit" ? "text-emerald-400" : "text-slate-500"}`}>
                                  {tx.type === "credit" ? "+" : "-"}{formatPrice(tx.amount)}
                                </td>
                                <td className="py-3.5 px-4 max-w-xs truncate text-slate-500" title={tx.description}>{tx.description}</td>
                                <td className="py-3.5 px-4">
                                  <span className={`capitalize text-[10px] font-semibold ${tx.status === "completed" ? "text-emerald-400" : "text-amber-400"}`}>{tx.status}</span>
                                </td>
                                <td className="py-3.5 px-2 text-slate-500">{new Date(tx.created_at).toLocaleDateString()}</td>
                              </tr>
                            ))
                          )}
                        </tbody>
                      </table>
                    </div>
                  </div>

                  {/* Payout requests list block */}
                  <div className="bg-slate-50/50 border border-slate-200 p-4 sm:p-6 rounded-2xl sm:rounded-3xl space-y-4">
                    <h3 className="text-base font-medium text-slate-800">Payout Cashout History</h3>
                    <div className="overflow-x-auto">
                      <table className="w-full text-left text-sm border-collapse">
                        <thead>
                          <tr className="border-b border-slate-200 text-slate-500 font-medium uppercase">
                            <th className="py-3 px-2">Withdraw ID</th>
                            <th className="py-3 px-4">Amount</th>
                            <th className="py-3 px-4">Method</th>
                            <th className="py-3 px-4">Status</th>
                            <th className="py-3 px-2">Date</th>
                          </tr>
                        </thead>
                        <tbody>
                          {withdraws.length === 0 ? (
                            <tr>
                              <td colSpan={5} className="text-center py-8 text-slate-500">No payout records found.</td>
                            </tr>
                          ) : (
                            withdraws.map(w => (
                              <tr key={w.id} className="border-b border-slate-100 text-slate-700">
                                <td className="py-3.5 px-2 font-mono font-medium text-slate-500">#{w.id}</td>
                                <td className="py-3.5 px-4 font-mono font-semibold text-slate-800">{formatPrice(w.amount)}</td>
                                <td className="py-3.5 px-4 uppercase text-slate-500">{w.payment_method}</td>
                                <td className="py-3.5 px-4">
                                  <span className={`px-2 py-0.5 text-[9px] font-semibold capitalize rounded-md ${
                                    w.status === "approved" ? "bg-emerald-500/10 text-emerald-400" :
                                    w.status === "pending" ? "bg-amber-500/10 text-amber-400" :
                                    "bg-slate-800 text-slate-500"
                                  }`}>
                                    {w.status}
                                  </span>
                                </td>
                                <td className="py-3.5 px-2 text-slate-500">{new Date(w.created_at).toLocaleDateString()}</td>
                              </tr>
                            ))
                          )}
                        </tbody>
                      </table>
                    </div>
                  </div>

                </div>

                {/* Withdraw Submit cashier form sidebar */}
                <div className="p-4 sm:p-6 bg-slate-50/50 border border-slate-200 rounded-2xl sm:rounded-3xl h-fit space-y-6">
                  <div>
                    <h3 className="font-medium text-slate-800 flex items-center gap-2">
                      <CreditCard size={18} />
                      Request Withdrawal
                    </h3>
                    <p className="text-sm text-slate-500 mt-1">Submit profit margin balance payouts requests.</p>
                  </div>

                  {withdrawSuccess && (
                    <div className="p-4 bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 text-sm font-semibold rounded-2xl">
                      {withdrawSuccess}
                    </div>
                  )}

                  {withdrawError && (
                    <div className="p-4 bg-red-500/10 border border-red-500/20 text-red-400 text-sm font-semibold rounded-2xl">
                      {withdrawError}
                    </div>
                  )}

                  <form onSubmit={handleWithdrawSubmit} className="space-y-4">
                    <div>
                      <label className="block text-sm font-semibold text-slate-350 mb-1.5">Payout Method</label>
                      <div className="grid grid-cols-2 gap-2">
                        {[
                          { id: "bkash", label: "bKash" },
                          { id: "nagad", label: "Nagad" },
                        ].map(m => (
                          <button 
                            key={m.id}
                            type="button" 
                            onClick={() => setWithdrawMethod(m.id)}
                            className={`py-2 text-sm font-medium rounded-xl border capitalize transition-all ${withdrawMethod === m.id ? "bg-emerald-500/10 border-emerald-500 text-emerald-400" : "bg-slate-50/40 border-slate-200 text-slate-500"}`}
                          >
                            {m.label}
                          </button>
                        ))}
                      </div>
                      
                      {/* Autofill credential preview */}
                      <p className="text-[10px] text-slate-500 mt-2 italic">
                        Account: {withdrawMethod === "bkash" ? (user?.reseller_bkash_number || "Not Configured in Settings") : (user?.reseller_nagad_number || "Not Configured in Settings")}
                      </p>
                    </div>

                    <div>
                      <label className="block text-sm font-semibold text-slate-350 mb-1">Withdraw Amount (BDT) *</label>
                      <div className="relative">
                        <span className="absolute left-3 top-2.5 text-slate-500 text-sm font-medium font-mono">৳</span>
                        <input 
                          type="number" 
                          required 
                          min={100}
                          value={withdrawAmount}
                          onChange={e => setWithdrawAmount(e.target.value)}
                          placeholder="e.g. 500" 
                          className="w-full text-sm pl-8 pr-4 py-2.5 bg-slate-50/60 border border-slate-200 focus:border-emerald-500 rounded-xl outline-none text-slate-800 font-mono font-medium"
                        />
                      </div>
                    </div>

                    <button 
                      type="submit"
                      disabled={withdrawSubmitting || !withdrawAmount}
                      className="w-full py-3 bg-emerald-500 hover:bg-emerald-600 disabled:opacity-40 text-white font-medium text-sm rounded-xl shadow-lg transition-all"
                    >
                      {withdrawSubmitting ? "Submitting Payout Request..." : "Request Cashout"}
                    </button>
                  </form>
                </div>
              </motion.div>
            )}

            {/* TAB 6: Payment Settings setup form */}
            {activeTab === "settings" && (
              <motion.div 
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="max-w-2xl bg-slate-50/50 border border-slate-200 p-4 sm:p-8 rounded-2xl sm:rounded-3xl space-y-6"
              >
                <div>
                  <h3 className="text-lg font-medium text-slate-800">Payout Configuration Settings</h3>
                  <p className="text-sm text-slate-500 mt-1">Configure mobile financial accounts and bank info for receiving payments.</p>
                </div>

                {settingsSuccess && (
                  <div className="p-4 bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 text-sm font-semibold rounded-2xl">
                    {settingsSuccess}
                  </div>
                )}

                <form onSubmit={handleSettingsSubmit} className="space-y-5">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-semibold text-slate-700 mb-1">bKash Account Number (Personal)</label>
                      <input 
                        type="text" 
                        value={bkashNum}
                        onChange={e => setBkashNum(e.target.value)}
                        placeholder="e.g. 017XXXXXXXX" 
                        className="w-full px-4 py-2.5 bg-white border border-slate-700 focus:border-emerald-500 rounded-xl outline-none text-slate-900 placeholder-slate-500 text-sm font-mono"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-semibold text-slate-700 mb-1">Nagad Account Number (Personal)</label>
                      <input 
                        type="text" 
                        value={nagadNum}
                        onChange={e => setNagadNum(e.target.value)}
                        placeholder="e.g. 017XXXXXXXX" 
                        className="w-full px-4 py-2.5 bg-white border border-slate-700 focus:border-emerald-500 rounded-xl outline-none text-slate-900 placeholder-slate-500 text-sm font-mono"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-1">Rocket Account Number (Personal)</label>
                    <input 
                      type="text" 
                      value={rocketNum}
                      onChange={e => setRocketNum(e.target.value)}
                      placeholder="e.g. 017XXXXXXXXX" 
                      className="w-full px-4 py-2.5 bg-white border border-slate-700 focus:border-emerald-500 rounded-xl outline-none text-slate-900 placeholder-slate-500 text-sm font-mono"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-1">Bank Account details</label>
                    <textarea 
                      rows={3}
                      value={bankDetails}
                      onChange={e => setBankDetails(e.target.value)}
                      placeholder="Bank Name, Branch, Routing Number, Account Name and Account Number..." 
                      className="w-full px-4 py-2.5 bg-white border border-slate-700 focus:border-emerald-500 rounded-xl outline-none text-slate-900 placeholder-slate-500 text-sm resize-none"
                    />
                  </div>

                  <button 
                    type="submit"
                    className="px-6 py-2.5 bg-emerald-500 hover:bg-emerald-600 text-white font-medium text-sm rounded-xl transition-all"
                  >
                    Save Payout Accounts
                  </button>
                </form>
              </motion.div>
            )}

            {/* TAB 7: Profile & Verification */}
            {activeTab === "profile" && (
              <motion.div 
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="max-w-5xl space-y-8"
              >
                <form onSubmit={handleProfileSubmit} className="space-y-8">
                  {/* Profile Details Card */}
                  <div className="bg-slate-50/50 border border-slate-200 p-4 sm:p-8 rounded-2xl sm:rounded-3xl space-y-6 backdrop-blur-xl">
                    {/* Profile Summary Header */}
                    <div className="flex flex-col sm:flex-row items-center gap-5 pb-6 border-b border-slate-200">
                      <div className="relative group">
                        {/* Styled User Avatar */}
                        <div className="w-20 h-20 rounded-full bg-gradient-to-br from-emerald-500/20 to-teal-600/20 flex items-center justify-center text-emerald-400 border border-emerald-500/25 overflow-hidden shadow-lg shadow-emerald-500/5">
                          {avatarPreview ? (
                            <img src={avatarPreview} className="w-full h-full object-cover" />
                          ) : user?.avatar ? (
                            <img src={`${apiUrl}/storage/${user.avatar}`} className="w-full h-full object-cover" />
                          ) : (
                            <span className="text-3xl font-semibold">{profileName.charAt(0).toUpperCase()}</span>
                          )}
                        </div>
                      </div>
                      <div className="text-center sm:text-left space-y-1">
                        <h3 className="text-xl font-medium text-slate-800 leading-none">{profileName || "Reseller User"}</h3>
                        <p className="text-sm text-slate-500 font-mono">{profileEmail}</p>
                        <div className="flex flex-wrap items-center gap-2 mt-2 justify-center sm:justify-start">
                          <span className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-semibold uppercase border ${
                            user?.reseller_status === "active" ? "bg-emerald-500/10 text-emerald-400 border-emerald-500/20" :
                            user?.reseller_status === "pending" ? "bg-amber-500/10 text-amber-400 border-amber-500/20" :
                            "bg-red-500/10 text-red-400 border-red-500/20"
                          }`}>
                            {user?.reseller_status || "Pending Review"}
                          </span>
                          <span className="text-sm text-slate-500">
                            {user?.reseller_status === "active"
                              ? "— Your profile is verified. All features are active."
                              : "— Please upload required documents below to verify your profile."}
                          </span>
                        </div>
                      </div>
                    </div>

                    {profileSuccess && (
                      <div className="p-4 bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 text-sm font-semibold rounded-2xl">
                        {profileSuccess}
                      </div>
                    )}

                    {profileError && (
                      <div className="p-4 bg-red-500/10 border border-red-500/20 text-red-400 text-sm font-semibold rounded-2xl">
                        {profileError}
                      </div>
                    )}

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                      <div className="space-y-1.5">
                        <label className="block text-sm font-semibold text-slate-350">Full Name</label>
                        <div className="relative">
                          <span className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-500">
                            <User size={15} />
                          </span>
                          <input 
                            type="text" 
                            value={profileName}
                            onChange={e => setProfileName(e.target.value)}
                            required
                            className="w-full pl-10 pr-4 py-2.5 bg-slate-50/60 border border-slate-200 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500/20 rounded-xl outline-none text-slate-900 text-sm transition-all"
                          />
                        </div>
                      </div>
                      <div className="space-y-1.5">
                        <label className="block text-sm font-semibold text-slate-700">Email Address</label>
                        <div className="relative">
                          <span className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-500">
                            <Mail size={15} />
                          </span>
                          <input 
                            type="email" 
                            value={profileEmail}
                            onChange={e => setProfileEmail(e.target.value)}
                            required
                            className="w-full pl-10 pr-4 py-2.5 bg-slate-50/60 border border-slate-200 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500/20 rounded-xl outline-none text-slate-900 text-sm transition-all"
                          />
                        </div>
                      </div>
                    </div>

                    <div className="space-y-1.5">
                      <label className="block text-sm font-semibold text-slate-700">Phone Number</label>
                      <div className="relative">
                        <span className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-500">
                          <Phone size={15} />
                        </span>
                        <input 
                          type="text" 
                          value={profilePhone}
                          onChange={e => setProfilePhone(e.target.value)}
                          className="w-full pl-10 pr-4 py-2.5 bg-slate-50/60 border border-slate-200 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500/20 rounded-xl outline-none text-slate-900 text-sm font-mono transition-all"
                        />
                      </div>
                    </div>

                    {/* Store & Social Media Details */}
                    <div className="space-y-5 pt-5 border-t border-slate-200">
                      <h4 className="text-sm font-medium text-slate-800">Store & Social Profiles</h4>
                      
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <div className="space-y-1.5">
                          <label className="block text-sm font-semibold text-slate-700">Store / Page Name</label>
                          <div className="relative">
                            <span className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-500">
                              <ShoppingBag size={15} />
                            </span>
                            <input 
                              type="text" 
                              value={storeName}
                              onChange={e => setStoreName(e.target.value)}
                              placeholder="e.g. My E-commerce Store"
                              className="w-full pl-10 pr-4 py-2.5 bg-slate-50/60 border border-slate-200 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500/20 rounded-xl outline-none text-slate-900 text-sm transition-all"
                            />
                          </div>
                        </div>

                        <div className="space-y-1.5">
                          <label className="block text-sm font-semibold text-slate-700">Website URL</label>
                          <div className="relative">
                            <span className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-500">
                              <Globe size={15} />
                            </span>
                            <input 
                              type="text" 
                              value={websiteUrl}
                              onChange={e => setWebsiteUrl(e.target.value)}
                              placeholder="e.g. https://mystore.com"
                              className="w-full pl-10 pr-4 py-2.5 bg-slate-50/60 border border-slate-200 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500/20 rounded-xl outline-none text-slate-900 text-sm transition-all"
                            />
                          </div>
                        </div>
                      </div>

                      <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <div className="space-y-1.5">
                          <label className="block text-sm font-semibold text-slate-700">Facebook Profile Link</label>
                          <div className="relative">
                            <span className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-500">
                              <Globe size={15} />
                            </span>
                            <input 
                              type="text" 
                              value={fbProfile}
                              onChange={e => setFbProfile(e.target.value)}
                              placeholder="e.g. https://facebook.com/username"
                              className="w-full pl-10 pr-4 py-2.5 bg-slate-50/60 border border-slate-200 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500/20 rounded-xl outline-none text-slate-900 text-sm transition-all"
                            />
                          </div>
                        </div>

                        <div className="space-y-1.5">
                          <label className="block text-sm font-semibold text-slate-700">Facebook Page Link</label>
                          <div className="relative">
                            <span className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-500">
                              <Globe size={15} />
                            </span>
                            <input 
                              type="text" 
                              value={fbPage}
                              onChange={e => setFbPage(e.target.value)}
                              placeholder="e.g. https://facebook.com/pagename"
                              className="w-full pl-10 pr-4 py-2.5 bg-slate-50/60 border border-slate-200 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500/20 rounded-xl outline-none text-slate-900 text-sm transition-all"
                            />
                          </div>
                        </div>
                      </div>

                      <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <div className="space-y-1.5">
                          <label className="block text-sm font-semibold text-slate-700">WhatsApp Number</label>
                          <div className="relative">
                            <span className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-500">
                              <Phone size={15} />
                            </span>
                            <input 
                              type="text" 
                              value={whatsappNum}
                              onChange={e => setWhatsappNum(e.target.value)}
                              placeholder="e.g. 017XXXXXXXX"
                              className="w-full pl-10 pr-4 py-2.5 bg-slate-50/60 border border-slate-200 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500/20 rounded-xl outline-none text-slate-900 text-sm font-mono transition-all"
                            />
                          </div>
                        </div>

                        <div className="space-y-1.5">
                          <label className="block text-sm font-semibold text-slate-700">Telegram Number/Username</label>
                          <div className="relative">
                            <span className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-500">
                              <Send size={15} />
                            </span>
                            <input 
                              type="text" 
                              value={telegramUser}
                              onChange={e => setTelegramUser(e.target.value)}
                              placeholder="e.g. 017XXXXXXXX or @username"
                              className="w-full pl-10 pr-4 py-2.5 bg-slate-50/60 border border-slate-200 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500/20 rounded-xl outline-none text-slate-900 text-sm transition-all"
                            />
                          </div>
                        </div>
                      </div>
                    </div>

                    <div className="space-y-5 pt-5 border-t border-slate-200">
                      <h4 className="text-sm font-medium text-slate-800">Security Credentials</h4>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <div className="space-y-1.5">
                          <label className="block text-sm font-semibold text-slate-700">New Password (Optional)</label>
                          <div className="relative">
                            <span className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-500">
                              <Lock size={15} />
                            </span>
                            <input 
                              type="password" 
                              value={profilePassword}
                              onChange={e => setProfilePassword(e.target.value)}
                              placeholder="••••••••" 
                              className="w-full pl-10 pr-4 py-2.5 bg-slate-50/60 border border-slate-200 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500/20 rounded-xl outline-none text-slate-900 text-sm transition-all"
                            />
                          </div>
                        </div>
                        <div className="space-y-1.5">
                          <label className="block text-sm font-semibold text-slate-700">Confirm Password</label>
                          <div className="relative">
                            <span className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-500">
                              <Lock size={15} />
                            </span>
                            <input 
                              type="password" 
                              value={profilePasswordConfirm}
                              onChange={e => setProfilePasswordConfirm(e.target.value)}
                              placeholder="••••••••" 
                              className="w-full pl-10 pr-4 py-2.5 bg-slate-50/60 border border-slate-200 focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500/20 rounded-xl outline-none text-slate-900 text-sm transition-all"
                            />
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* Documents Upload Grid Card */}
                  <div className="bg-slate-50/50 border border-slate-200 p-4 sm:p-8 rounded-2xl sm:rounded-3xl space-y-6 backdrop-blur-xl">
                    <div>
                      <h3 className="text-sm font-medium text-slate-800 uppercase tracking-widest">Required Verification Documents</h3>
                      <p className="text-sm text-slate-500 mt-1">Please upload clear photos of the files below. Uploaded files will be saved when you click "Save Profile & Documents" below.</p>
                    </div>

                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
                      {[
                        { 
                          label: "Profile Picture / Avatar", 
                          field: "avatar", 
                          fileState: avatarFile, 
                          setFile: setAvatarFile,
                          preview: avatarPreview,
                          setPreview: setAvatarPreview,
                          existing: user?.avatar ? `${apiUrl}/storage/${user.avatar}` : null,
                          desc: "Square format headshot"
                        },
                        { 
                          label: "NID Card (Front Side)", 
                          field: "reseller_nid_front", 
                          fileState: nidFrontFile, 
                          setFile: setNidFrontFile,
                          preview: nidFrontPreview,
                          setPreview: setNidFrontPreview,
                          existing: user?.reseller_nid_front ? `${apiUrl}/storage/${user.reseller_nid_front}` : null,
                          desc: "Clear snapshot of NID front"
                        },
                        { 
                          label: "NID Card (Back Side)", 
                          field: "reseller_nid_back", 
                          fileState: nidBackFile, 
                          setFile: setNidBackFile,
                          preview: nidBackPreview,
                          setPreview: setNidBackPreview,
                          existing: user?.reseller_nid_back ? `${apiUrl}/storage/${user.reseller_nid_back}` : null,
                          desc: "Clear snapshot of NID back"
                        },
                        { 
                          label: "Passport Size Photo", 
                          field: "reseller_passport_photo", 
                          fileState: passportFile, 
                          setFile: setPassportFile,
                          preview: passportPreview,
                          setPreview: setPassportPreview,
                          existing: user?.reseller_passport_photo ? `${apiUrl}/storage/${user.reseller_passport_photo}` : null,
                          desc: "Standard photo with light bg"
                        },
                      ].map(doc => (
                        <div key={doc.field} className="space-y-2 flex flex-col justify-between border border-slate-200 hover:border-slate-200 rounded-2xl p-4 bg-slate-50/20 transition-all group relative">
                          <div className="space-y-1">
                            <div className="flex justify-between items-baseline gap-2">
                              <span className="text-sm font-medium text-slate-800 truncate">{doc.label}</span>
                            </div>
                            <p className="text-[10px] text-slate-500 leading-normal">{doc.desc}</p>
                          </div>
                          
                          {/* Drag and Drop Selector box */}
                          <div className="mt-4 relative border border-dashed border-slate-200 group-hover:border-emerald-500/50 rounded-xl p-3 flex flex-col items-center justify-center gap-2.5 min-h-[110px] bg-slate-50/40 transition-all overflow-hidden">
                            {doc.preview ? (
                              <img src={doc.preview} className="absolute inset-0 w-full h-full object-cover" />
                            ) : doc.existing ? (
                              <img src={doc.existing} className="absolute inset-0 w-full h-full object-cover opacity-80 group-hover:opacity-60 transition-opacity" />
                            ) : (
                              <Package size={20} className="text-slate-800 group-hover:text-slate-700 transition-colors" />
                            )}

                            {/* File status overlay label */}
                            <div className={`relative px-2 py-1 rounded text-[9px] font-semibold uppercase tracking-wider ${
                              doc.fileState ? "bg-amber-500/20 text-amber-300 border border-amber-500/30" :
                              doc.existing ? "bg-emerald-500/20 text-emerald-300 border border-emerald-500/30" :
                              "bg-white/60 text-slate-500 border border-slate-200"
                            }`}>
                              {doc.fileState ? "Pending Save" : doc.existing ? "Uploaded" : "No File"}
                            </div>

                            {doc.fileState && (
                              <span className="relative text-[9px] text-slate-500 font-mono font-semibold">
                                {(doc.fileState.size / (1024 * 1024)).toFixed(2)} MB
                              </span>
                            )}

                            {/* Hidden file input */}
                            <input 
                              type="file" 
                              accept="image/jpeg,image/png,image/jpg"
                              onChange={e => {
                                const file = e.target.files?.[0];
                                if (file) {
                                  doc.setFile(file);
                                  const url = URL.createObjectURL(file);
                                  doc.setPreview(url);
                                }
                              }}
                              className="absolute inset-0 opacity-0 cursor-pointer w-full h-full z-10"
                            />
                          </div>
                        </div>
                      ))}
                    </div>

                    {/* Submit Button at the bottom of the card */}
                    <div className="flex justify-end pt-6 border-t border-slate-200">
                      <button 
                        type="submit"
                        disabled={profileSubmitting}
                        className="px-6 py-3 bg-gradient-to-r from-emerald-500 to-teal-500 hover:from-emerald-400 hover:to-teal-400 disabled:from-slate-800 disabled:to-slate-800 disabled:text-slate-500 text-white font-medium text-sm rounded-xl transition-all flex items-center justify-center gap-2 cursor-pointer shadow-[0_0_20px_rgba(16,185,129,0.15)] hover:shadow-[0_0_25px_rgba(16,185,129,0.3)] hover:-translate-y-0.5 active:translate-y-0 disabled:translate-y-0 disabled:shadow-none"
                      >
                        {profileSubmitting && <div className="w-3.5 h-3.5 border-2 border-slate-950 border-t-transparent rounded-full animate-spin" />}
                        Save Profile & Documents
                      </button>
                    </div>
                  </div>
                </form>
              </motion.div>
            )}

            {/* TAB 8: Community Support & Groups */}
            {activeTab === "community" && (
              user?.reseller_status !== 'active' ? (
                <motion.div 
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -10 }}
                  className="bg-slate-50 border border-slate-200 rounded-3xl p-8 sm:p-12 text-center max-w-2xl mx-auto space-y-6"
                  style={{ fontFamily: 'var(--font-open-sans), sans-serif' }}
                >
                  <div className="w-16 h-16 bg-rose-100 text-rose-600 rounded-full flex items-center justify-center mx-auto shadow-md">
                    <Lock size={32} />
                  </div>
                  <div className="space-y-2">
                    <h3 className="text-xl font-bold text-slate-800">Support Communities Locked</h3>
                    <p className="text-sm text-slate-500 max-w-md mx-auto">
                      Official reseller community groups (WhatsApp & Telegram) are only accessible to verified accounts. Please upload your verification documents in profile settings to unlock access.
                    </p>
                  </div>
                  <button 
                    onClick={() => setActiveTab('profile')}
                    className="px-6 py-3 bg-slate-800 hover:bg-slate-700 text-white font-medium text-sm rounded-xl shadow-lg transition-all"
                  >
                    Upload Verification Documents
                  </button>
                </motion.div>
              ) : (
                <motion.div 
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -10 }}
                  className="max-w-3xl mx-auto space-y-6 text-left"
                >
                  <div>
                    <h3 className="text-xl font-medium text-slate-800">Support & Community Groups</h3>
                    <p className="text-sm text-slate-500 mt-1">Join our official communities to get live updates, product alerts, and direct reseller support.</p>
                  </div>

                  {communityLoading && communityGroups.length === 0 ? (
                    <div className="flex flex-col items-center justify-center py-16 gap-3">
                      <Loader2 className="animate-spin text-emerald-500" size={32} />
                      <p className="text-sm text-slate-500">Loading community groups...</p>
                    </div>
                  ) : (
                    <div className="space-y-4">
                      {communityGroups.some(g => g.type === 'whatsapp') && (
                        <div className="bg-white border border-slate-200/80 rounded-[24px] overflow-hidden shadow-sm">
                          <button 
                            onClick={() => setExpandedGroup(expandedGroup === 'whatsapp' ? null : 'whatsapp')}
                            className="w-full flex items-center justify-between p-5 bg-gradient-to-r from-emerald-50/20 to-transparent hover:bg-emerald-50/30 transition-colors text-left"
                          >
                            <div className="flex items-center gap-4">
                              <div className="w-10 h-10 rounded-full bg-emerald-500 flex items-center justify-center text-white shadow-md shadow-emerald-500/20">
                                <MessageCircle size={18} className="fill-current" />
                              </div>
                              <span className="text-base font-medium text-slate-800">WhatsApp Groups</span>
                            </div>
                            <ChevronDown 
                              size={20} 
                              className={`text-[#10b981] transition-transform duration-300 ${expandedGroup === 'whatsapp' ? 'rotate-180' : ''}`} 
                            />
                          </button>
                          
                          <AnimatePresence initial={false}>
                            {expandedGroup === 'whatsapp' && (
                              <motion.div
                                initial={{ height: 0 }}
                                animate={{ height: "auto" }}
                                exit={{ height: 0 }}
                                transition={{ duration: 0.3, ease: "easeInOut" }}
                                className="overflow-hidden border-t border-slate-100"
                              >
                                <div className="p-6 space-y-3 bg-slate-50/30">
                                  {communityGroups.filter(g => g.type === 'whatsapp').map(group => (
                                    <a 
                                      key={group.id}
                                      href={group.url}
                                      target="_blank"
                                      rel="noopener noreferrer"
                                      className="flex items-center gap-4 p-4 bg-white border border-slate-150 rounded-2xl hover:border-emerald-300 hover:shadow-sm transition-all group cursor-pointer"
                                    >
                                      <div className="w-10 h-10 rounded-full bg-emerald-100 text-emerald-600 flex items-center justify-center flex-shrink-0 transition-colors group-hover:bg-emerald-500 group-hover:text-white">
                                        <MessageCircle size={18} className="fill-current" />
                                      </div>
                                      <div>
                                        <h4 className="text-[14px] font-medium text-slate-800 transition-colors group-hover:text-emerald-650">{group.name}</h4>
                                        <span className="text-[11px] text-blue-600 font-semibold block mt-0.5">Click to join</span>
                                      </div>
                                    </a>
                                  ))}
                                </div>
                              </motion.div>
                            )}
                          </AnimatePresence>
                        </div>
                      )}

                      {communityGroups.some(g => g.type === 'telegram') && (
                        <div className="bg-white border border-slate-200/80 rounded-[24px] overflow-hidden shadow-sm">
                          <button 
                            onClick={() => setExpandedGroup(expandedGroup === 'telegram' ? null : 'telegram')}
                            className="w-full flex items-center justify-between p-5 bg-gradient-to-r from-blue-50/20 to-transparent hover:bg-blue-50/30 transition-colors text-left"
                          >
                            <div className="flex items-center gap-4">
                              <div className="w-10 h-10 rounded-full bg-blue-500 flex items-center justify-center text-white shadow-md shadow-blue-500/20">
                                <Send size={18} className="fill-current -translate-x-0.5 translate-y-0.5" />
                              </div>
                              <span className="text-base font-medium text-slate-800">Telegram Groups</span>
                            </div>
                            <ChevronDown 
                              size={20} 
                              className={`text-blue-600 transition-transform duration-300 ${expandedGroup === 'telegram' ? 'rotate-180' : ''}`} 
                            />
                          </button>
                          
                          <AnimatePresence initial={false}>
                            {expandedGroup === 'telegram' && (
                              <motion.div
                                initial={{ height: 0 }}
                                animate={{ height: "auto" }}
                                exit={{ height: 0 }}
                                transition={{ duration: 0.3, ease: "easeInOut" }}
                                className="overflow-hidden border-t border-slate-100"
                              >
                                <div className="p-6 space-y-3 bg-slate-50/30">
                                  {communityGroups.filter(g => g.type === 'telegram').map(group => (
                                    <a 
                                      key={group.id}
                                      href={group.url}
                                      target="_blank"
                                      rel="noopener noreferrer"
                                      className="flex items-center gap-4 p-4 bg-white border border-slate-150 rounded-2xl hover:border-blue-300 hover:shadow-sm transition-all group cursor-pointer"
                                    >
                                      <div className="w-10 h-10 rounded-full bg-blue-100 text-blue-650 flex items-center justify-center flex-shrink-0 transition-colors group-hover:bg-blue-500 group-hover:text-white">
                                        <Send size={18} className="fill-current -translate-x-0.5 translate-y-0.5" />
                                      </div>
                                      <div>
                                        <h4 className="text-[14px] font-medium text-slate-800 transition-colors group-hover:text-blue-600">{group.name}</h4>
                                        <span className="text-[11px] text-blue-600 font-semibold block mt-0.5">Click to join</span>
                                      </div>
                                    </a>
                                  ))}
                                </div>
                              </motion.div>
                            )}
                          </AnimatePresence>
                        </div>
                      )}
                    </div>
                  )}
                </motion.div>
              )
            )}

                </AnimatePresence>
              </div>
            </div>
          </div>
        </div>
      </main>
      <Footer />
    </>
  );
}
