"use client";

import React, { useState, useEffect } from "react";
import { useApp } from "@/context/AppContext";
import { Navbar } from "@/components/Navbar";
import { Footer } from "@/components/Footer";
import { FloatingWhatsApp } from "@/components/FloatingWhatsApp";
import { AIAssistant } from "@/components/AIAssistant";
import { mockProducts, mockReviews, Product, mockCoupons } from "@/data/mockData";
import {
  BarChart,
  DollarSign,
  Package,
  Users,
  Percent,
  Plus,
  Trash2,
  CheckCircle,
  Truck,
  Send,
  AlertCircle,
  TrendingUp,
  Globe,
  Upload,
  Link as LinkIcon,
  LogOut,
  LineChart,
  Settings
} from "lucide-react";
import Image from "next/image";

export default function AdminDashboardPage() {
  const { formatPrice, siteConfig, updateSiteConfig } = useApp();

  // Admin Lock States
  const [isAdminLoggedIn, setIsAdminLoggedIn] = useState(false);
  const [adminEmail, setAdminEmail] = useState("");
  const [adminPassword, setAdminPassword] = useState("");
  const [adminLoginError, setAdminLoginError] = useState("");

  // Dashboard state tabs
  const [adminTab, setAdminTab] = useState<"analytics" | "products" | "orders" | "marketing" | "settings">("analytics");

  // Site Config Form State
  const [configForm, setConfigForm] = useState<any>({
    contactPhone: "",
    whatsappNumber: "",
    address: "",
    instagram: "",
    facebook: "",
    tiktok: "",
    paymentMethods: {
      cod: true,
      bankTransfer: true,
      easypaisa: true,
      jazzcash: true,
      stripe: true,
    },
    deliveryIntegrations: {
      tcs: true,
      leopards: true,
      postex: true,
    },
    courierConfig: {
      tcs: { apiKey: "", merchantId: "", clientName: "", isSandbox: true },
      leopards: { apiKey: "", apiPassword: "", merchantId: "", isSandbox: true },
      postex: { apiKey: "", clientId: "", isSandbox: true }
    },
    paymentConfig: {
      stripe: { publishableKey: "", secretKey: "" },
      easypaisa: { storeId: "", hashKey: "", receiverPhone: "" },
      jazzcash: { merchantId: "", password: "", integritySalt: "" },
      bankTransfer: { bankName: "", accountTitle: "", accountNumber: "", iban: "" },
      cod: { instructions: "" }
    }
  });

  const [settingsSuccess, setSettingsSuccess] = useState(false);

  // Sync from siteConfig on load or change
  useEffect(() => {
    if (siteConfig) {
      setConfigForm({ ...siteConfig });
    }
  }, [siteConfig]);

  const handleSettingsSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    updateSiteConfig(configForm);
    setSettingsSuccess(true);
    setTimeout(() => setSettingsSuccess(false), 3000);
  };

  // Products list
  const [productsList, setProductsList] = useState<Product[]>([]);
  // Orders list
  const [ordersList, setOrdersList] = useState<any[]>([]);
  // Coupons list
  const [coupons, setCoupons] = useState<any[]>([]);

  // Create Product Form State
  const [newProduct, setNewProduct] = useState({
    name: "",
    price: 3890,
    discount: 0,
    category: "Essentials",
    gsm: 240,
    description: "",
    craftsmanship: "",
    colors: "Matte Black, Warm White, Sand Grey",
    sizes: "S, M, L, XL",
    image: "/essentials_black_tee.png",
    hoverImage: "/craftsmanship_details.png",
    galleryImage3: "/craftsmanship_details.png"
  });

  // Campaign Simulator State
  const [campaignType, setCampaignType] = useState<"email" | "sms">("email");
  const [campaignText, setCampaignText] = useState("");
  const [campaignLogs, setCampaignLogs] = useState<string[]>([]);

  useEffect(() => {
    // Check local storage for admin login session
    const savedLogin = localStorage.getItem("starboy_admin_logged_in");
    if (savedLogin === "true") {
      setIsAdminLoggedIn(true);
    }

    setProductsList(mockProducts);
    setCoupons(mockCoupons);

    // Sync placed orders from local storage
    const localOrders = localStorage.getItem("starboy_orders");
    if (localOrders) {
      setOrdersList(JSON.parse(localOrders));
    } else {
      const defaultOrders = [
        {
          orderId: "SB-284028",
          customerEmail: "ahmed.customer@gmail.com",
          customerName: "Ahmed Raza",
          city: "Karachi",
          items: [{ name: "Starboy Heavyweight Tee", quantity: 2, price: 3500, size: "M", color: "Matte Black" }],
          total: 7250,
          orderStatus: "Processing",
          courier: "TCS",
          trackingNumber: "TCS-92840283-PK"
        },
        {
          orderId: "SB-839218",
          customerEmail: "sara.k@outlook.com",
          customerName: "Sara Khan",
          city: "Lahore",
          items: [{ name: "Oversized Utility Hoodie", quantity: 1, price: 8490, size: "S", color: "Sand Grey" }],
          total: 8740,
          orderStatus: "Shipped",
          courier: "Leopards Courier",
          trackingNumber: "LEO-83921023-PK"
        },
        {
          orderId: "SB-920194",
          customerEmail: "mustafa.stylist@gmail.com",
          customerName: "Mustafa Kamal",
          city: "Islamabad",
          items: [{ name: "Signature Loopback Sweatpants", quantity: 1, price: 5490, size: "L", color: "Off-White" }],
          total: 5740,
          orderStatus: "Delivered",
          courier: "Call Courier",
          trackingNumber: "CAL-92840294-PK"
        }
      ];
      setOrdersList(defaultOrders);
      localStorage.setItem("starboy_orders", JSON.stringify(defaultOrders));
    }
  }, []);

  const handleAdminLogin = (e: React.FormEvent) => {
    e.preventDefault();
    setAdminLoginError("");
    const emailClean = adminEmail.trim();
    const passwordClean = adminPassword.trim();
    if (emailClean.toLowerCase() === "mustafa@admin.com" && passwordClean === "@Black0x22@") {
      setIsAdminLoggedIn(true);
      localStorage.setItem("starboy_admin_logged_in", "true");
    } else {
      setAdminLoginError("Access Denied. Invalid Admin Credentials.");
    }
  };

  const handleAdminLogout = () => {
    setIsAdminLoggedIn(false);
    localStorage.removeItem("starboy_admin_logged_in");
  };

  // Simulated local file uploader
  const handleLocalImageUpload = (
    e: React.ChangeEvent<HTMLInputElement>,
    field: "image" | "hoverImage" | "galleryImage3"
  ) => {
    const file = e.target.files?.[0];
    if (file) {
      setNewProduct((prev) => ({
        ...prev,
        [field]: `/uploads/${file.name}`
      }));
    }
  };

  // Add Product to list
  const handleCreateProduct = (e: React.FormEvent) => {
    e.preventDefault();
    const created: Product = {
      id: `prod-${Date.now()}`,
      name: newProduct.name.toUpperCase(),
      price: Number(newProduct.price),
      discount: Number(newProduct.discount),
      category: newProduct.category,
      gsm: Number(newProduct.gsm),
      description: newProduct.description,
      craftsmanship: newProduct.craftsmanship,
      sizes: newProduct.sizes.split(",").map((s) => s.trim()),
      colors: newProduct.colors.split(",").map((c) => c.trim()),
      image: newProduct.image,
      hoverImage: newProduct.hoverImage,
      stock: 50,
      rating: 5.0,
      reviewsCount: 0
    };

    setProductsList([created, ...productsList]);

    // Reset Form
    setNewProduct({
      name: "",
      price: 3890,
      discount: 0,
      category: "Essentials",
      gsm: 240,
      description: "",
      craftsmanship: "",
      colors: "Matte Black, Warm White, Sand Grey",
      sizes: "S, M, L, XL",
      image: "/essentials_black_tee.png",
      hoverImage: "/craftsmanship_details.png",
      galleryImage3: "/craftsmanship_details.png"
    });
  };

  const handleDeleteProduct = (productId: string) => {
    setProductsList(productsList.filter((p) => p.id !== productId));
  };

  const handleUpdateOrderStatus = (orderId: string, newStatus: string) => {
    const updated = ordersList.map((ord) => {
      if (ord.orderId === orderId) {
        return { ...ord, orderStatus: newStatus };
      }
      return ord;
    });
    setOrdersList(updated);
    localStorage.setItem("starboy_orders", JSON.stringify(updated));
  };

  const handleBookCourier = (orderId: string, courierName: string) => {
    const courierKey = courierName.toLowerCase() as "tcs" | "leopards" | "postex";
    const config = siteConfig.courierConfig?.[courierKey];
    const prefix = courierName === "PostEx" ? "PEX" : courierName === "TCS" ? "TCS" : "LP";
    const generatedTracking = `${prefix}-${Math.floor(10000000 + Math.random() * 90000000)}-PK`;

    const configAny = config as any;
    alert(
      `[COURIER API INTEGRATION]\n\n` +
      `Booking request sent to ${courierName.toUpperCase()} API\n` +
      `Merchant ID: ${configAny?.merchantId || configAny?.clientId || "STARBOY-M001"}\n` +
      `API Key/Token: ${configAny?.apiKey ? (configAny.apiKey.substring(0, 10) + "...") : "Default-Key-Activated"}\n` +
      `Mode: ${configAny?.isSandbox ? "SANDBOX/TESTING" : "PRODUCTION"}\n\n` +
      `SUCCESS: Waybill generated!\n` +
      `Tracking Code: ${generatedTracking}`
    );

    const updated = ordersList.map((ord) => {
      if (ord.orderId === orderId) {
        return {
          ...ord,
          orderStatus: "Shipped",
          courier: courierName,
          trackingNumber: generatedTracking
        };
      }
      return ord;
    });

    setOrdersList(updated);
    localStorage.setItem("starboy_orders", JSON.stringify(updated));
  };

  const handleTriggerCampaign = (e: React.FormEvent) => {
    e.preventDefault();
    if (campaignText.trim()) {
      const timeStr = new Date().toLocaleTimeString();
      const log = `[${timeStr}] Campaign launched successfully via ${campaignType.toUpperCase()}. Target: 4,500 active contacts. Content: "${campaignText}"`;
      setCampaignLogs([log, ...campaignLogs]);
      setCampaignText("");
    }
  };

  // Compute key analytics
  const ordersBaseCount = 45;
  const totalOrdersCount = ordersList.length + ordersBaseCount;
  const ordersBaseRev = 192800;
  const totalRevenue = ordersList.reduce((acc, ord) => acc + ord.total, 0) + ordersBaseRev;
  const avgOrderVal = totalOrdersCount > 0 ? totalRevenue / totalOrdersCount : 0;
  const netProfit = totalRevenue * 0.42; // assume 42% net profit margin after COGS/shipping
  const totalVisitors = 12450;
  const bounceRate = 26.4; // percentage

  // MOCK LOGIN GUARD VIEW
  if (!isAdminLoggedIn) {
    return (
      <div className="flex min-h-screen flex-col bg-[#0A0A0A] text-[#F8F7F2]">
        <Navbar />
        <div className="flex-1 flex items-center justify-center p-6">
          <div className="max-w-md w-full border border-neutral-800 bg-[#0E0E0E] p-8 space-y-6">
            <div className="text-center space-y-2 border-b border-neutral-900 pb-4">
              <span className="text-[9px] font-bold text-[#D4AF37] uppercase tracking-[0.35em] block">SECURITY BARRIER</span>
              <h2 className="font-serif text-xl font-bold uppercase tracking-widest text-[#F8F7F2]">
                ADMIN CONTROL LOG
              </h2>
              <p className="text-[10px] text-neutral-400 font-sans font-light">
                Enter your credentials to unlock inventory controls and tracking databases.
              </p>
            </div>

            <form onSubmit={handleAdminLogin} className="space-y-4">
              <div className="space-y-1.5">
                <label className="text-[9px] font-bold uppercase tracking-wider text-neutral-400">Admin Email</label>
                <input
                  type="email"
                  required
                  value={adminEmail}
                  onChange={(e) => setAdminEmail(e.target.value)}
                  placeholder="Mustafa@admin.com"
                  className="w-full bg-[#141414] border border-neutral-800 text-xs px-4 py-2.5 outline-none focus:border-[#D4AF37] text-white"
                />
              </div>

              <div className="space-y-1.5">
                <label className="text-[9px] font-bold uppercase tracking-wider text-neutral-400">Security Password</label>
                <input
                  type="password"
                  required
                  value={adminPassword}
                  onChange={(e) => setAdminPassword(e.target.value)}
                  placeholder="••••••••"
                  className="w-full bg-[#141414] border border-neutral-800 text-xs px-4 py-2.5 outline-none focus:border-[#D4AF37] text-white"
                />
              </div>

              {adminLoginError && (
                <div className="text-[10px] text-red-600 font-semibold flex items-center gap-1.5">
                  <AlertCircle className="w-3.5 h-3.5" /> {adminLoginError}
                </div>
              )}

              <button
                type="submit"
                className="w-full bg-[#D4AF37] hover:bg-[#F8F7F2] text-black hover:text-black font-semibold text-xs tracking-widest py-3.5 border border-[#D4AF37] hover:border-white transition-all uppercase"
              >
                Authenticate Access
              </button>
            </form>
          </div>
        </div>
        <Footer />
      </div>
    );
  }

  return (
    <div className="flex min-h-screen flex-col bg-[#F8F7F2]">
      <Navbar />

      <main className="flex-1 py-12 px-6 md:px-12 mx-auto max-w-7xl w-full">
        {/* Header */}
        <div className="mb-10 flex flex-col md:flex-row md:items-center justify-between border-b border-[#1A1A1A]/10 pb-6 gap-4">
          <div className="text-left space-y-1">
            <span className="text-[9px] font-bold tracking-[0.35em] text-[#D4AF37] uppercase block">STARBOY PK CONTROL</span>
            <h1 className="font-serif text-2xl font-bold uppercase tracking-widest text-[#0a0a0a]">
              ENTERPRISE MANAGEMENT PANEL
            </h1>
          </div>
          <button
            onClick={handleAdminLogout}
            className="border border-[#1A1A1A]/20 hover:border-red-700 hover:text-red-700 bg-white text-[10px] font-bold uppercase tracking-widest px-4 py-2 flex items-center gap-1.5 self-start"
          >
            <LogOut className="w-3.5 h-3.5" /> Sign Out
          </button>
        </div>

        {/* Navigation Toggles */}
        <div className="flex flex-wrap border border-[#1A1A1A]/10 bg-white mb-8 divide-x divide-[#1A1A1A]/10 text-xs uppercase font-bold tracking-widest">
          <button
            onClick={() => setAdminTab("analytics")}
            className={`flex-1 py-4 text-center hover:bg-[#F8F7F2] transition-colors ${
              adminTab === "analytics" ? "bg-[#0A0A0A] text-[#F8F7F2]" : "text-black"
            }`}
          >
            Analytics & Reports
          </button>
          <button
            onClick={() => setAdminTab("products")}
            className={`flex-1 py-4 text-center hover:bg-[#F8F7F2] transition-colors ${
              adminTab === "products" ? "bg-[#0A0A0A] text-[#F8F7F2]" : "text-black"
            }`}
          >
            Product Inventory
          </button>
          <button
            onClick={() => setAdminTab("orders")}
            className={`flex-1 py-4 text-center hover:bg-[#F8F7F2] transition-colors ${
              adminTab === "orders" ? "bg-[#0A0A0A] text-[#F8F7F2]" : "text-black"
            }`}
          >
            Order Fulfillments
          </button>
          <button
            onClick={() => setAdminTab("marketing")}
            className={`flex-1 py-4 text-center hover:bg-[#F8F7F2] transition-colors ${
              adminTab === "marketing" ? "bg-[#0A0A0A] text-[#F8F7F2]" : "text-black"
            }`}
          >
            Campaign Desk
          </button>
          <button
            onClick={() => setAdminTab("settings")}
            className={`flex-1 py-4 text-center hover:bg-[#F8F7F2] transition-colors ${
              adminTab === "settings" ? "bg-[#0A0A0A] text-[#F8F7F2]" : "text-black"
            }`}
          >
            Site Configs
          </button>
        </div>

        {/* TAB 1: Detailed Analytics */}
        {adminTab === "analytics" && (
          <div className="space-y-8">
            {/* Stats Counter Matrix */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-4">
              {/* Revenue */}
              <div className="border border-[#1A1A1A]/10 bg-white p-4 flex flex-col justify-between h-28">
                <span className="text-[8px] font-bold text-neutral-400 uppercase tracking-widest block">Gross Revenue</span>
                <span className="text-lg font-serif font-bold text-black">{formatPrice(totalRevenue)}</span>
                <div className="flex items-center gap-1 text-[9px] text-green-700 font-bold font-sans">
                  <TrendingUp className="w-3 h-3" /> +18.4% MoM
                </div>
              </div>

              {/* Net Profit */}
              <div className="border border-[#1A1A1A]/10 bg-white p-4 flex flex-col justify-between h-28">
                <span className="text-[8px] font-bold text-neutral-400 uppercase tracking-widest block">Est. Net Profit</span>
                <span className="text-lg font-serif font-bold text-[#D4AF37]">{formatPrice(netProfit)}</span>
                <div className="text-[8px] text-neutral-400 uppercase tracking-wider">42% margin model</div>
              </div>

              {/* Volume */}
              <div className="border border-[#1A1A1A]/10 bg-white p-4 flex flex-col justify-between h-28">
                <span className="text-[8px] font-bold text-neutral-400 uppercase tracking-widest block">Orders Placed</span>
                <span className="text-lg font-serif font-bold text-black">{totalOrdersCount} UNITS</span>
                <div className="text-[8px] text-neutral-400 uppercase tracking-wider">COD & Online payment</div>
              </div>

              {/* AOV */}
              <div className="border border-[#1A1A1A]/10 bg-white p-4 flex flex-col justify-between h-28">
                <span className="text-[8px] font-bold text-neutral-400 uppercase tracking-widest block">Avg. Order Value</span>
                <span className="text-lg font-serif font-bold text-black">{formatPrice(avgOrderVal)}</span>
                <div className="text-[8px] text-neutral-400 uppercase tracking-wider">Heavy cotton bundles</div>
              </div>

              {/* Traffic Visitors */}
              <div className="border border-[#1A1A1A]/10 bg-white p-4 flex flex-col justify-between h-28">
                <span className="text-[8px] font-bold text-neutral-400 uppercase tracking-widest block">Total Sessions</span>
                <span className="text-lg font-serif font-bold text-black">{totalVisitors.toLocaleString()}</span>
                <div className="flex items-center gap-1 text-[9px] text-green-700 font-bold font-sans">
                  <TrendingUp className="w-3 h-3" /> +12% growth
                </div>
              </div>

              {/* Bounce Rate */}
              <div className="border border-[#1A1A1A]/10 bg-white p-4 flex flex-col justify-between h-28">
                <span className="text-[8px] font-bold text-neutral-400 uppercase tracking-widest block">Bounce Rate</span>
                <span className="text-lg font-serif font-bold text-black">{bounceRate}%</span>
                <div className="text-[8px] text-green-800 font-semibold font-sans">✓ Healthy streetwear index</div>
              </div>
            </div>

            {/* Split layout: Chart vs Traffic breakdown */}
            <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
              {/* Monthly Revenue Chart */}
              <div className="lg:col-span-8 border border-[#1A1A1A]/10 bg-white p-6 space-y-6">
                <h3 className="text-xs font-bold uppercase tracking-widest text-black flex items-center gap-1.5">
                  <LineChart className="w-4 h-4 text-[#D4AF37]" /> Revenue Trajectory 2026 (PKR)
                </h3>
                <div className="flex h-56 items-end gap-6 border-l border-b border-[#1A1A1A]/10 pb-2 pl-4">
                  <div className="flex-1 flex flex-col items-center gap-1.5 h-full justify-end">
                    <div className="bg-neutral-800 w-full" style={{ height: "45%" }} />
                    <span className="text-[8px] font-bold text-neutral-500 uppercase">Jan (190k)</span>
                  </div>
                  <div className="flex-1 flex flex-col items-center gap-1.5 h-full justify-end">
                    <div className="bg-neutral-800 w-full" style={{ height: "60%" }} />
                    <span className="text-[8px] font-bold text-neutral-500 uppercase">Feb (240k)</span>
                  </div>
                  <div className="flex-1 flex flex-col items-center gap-1.5 h-full justify-end">
                    <div className="bg-neutral-800 w-full" style={{ height: "70%" }} />
                    <span className="text-[8px] font-bold text-neutral-500 uppercase">Mar (280k)</span>
                  </div>
                  <div className="flex-1 flex flex-col items-center gap-1.5 h-full justify-end">
                    <div className="bg-[#D4AF37] w-full" style={{ height: "92%" }} />
                    <span className="text-[8px] font-bold text-black uppercase">Apr (370k)</span>
                  </div>
                  <div className="flex-1 flex flex-col items-center gap-1.5 h-full justify-end">
                    <div className="bg-neutral-800 w-full" style={{ height: "98%" }} />
                    <span className="text-[8px] font-bold text-neutral-500 uppercase">May (410k)</span>
                  </div>
                </div>
              </div>

              {/* Traffic Sources */}
              <div className="lg:col-span-4 border border-[#1A1A1A]/10 bg-white p-6 space-y-6">
                <h3 className="text-xs font-bold uppercase tracking-widest text-black flex items-center gap-1.5">
                  <Globe className="w-4 h-4 text-[#D4AF37]" /> Channel Breakdown
                </h3>
                <div className="space-y-4">
                  <div>
                    <div className="flex justify-between text-[10px] font-bold uppercase tracking-wider mb-1">
                      <span>Instagram Direct Ads</span>
                      <span>45%</span>
                    </div>
                    <div className="h-2 w-full bg-[#F8F7F2] rounded-full overflow-hidden">
                      <div className="bg-[#0A0A0A] h-full" style={{ width: "45%" }} />
                    </div>
                  </div>
                  <div>
                    <div className="flex justify-between text-[10px] font-bold uppercase tracking-wider mb-1">
                      <span>Direct Browsing</span>
                      <span>30%</span>
                    </div>
                    <div className="h-2 w-full bg-[#F8F7F2] rounded-full overflow-hidden">
                      <div className="bg-[#0A0A0A] h-full" style={{ width: "30%" }} />
                    </div>
                  </div>
                  <div>
                    <div className="flex justify-between text-[10px] font-bold uppercase tracking-wider mb-1">
                      <span>WhatsApp Support Links</span>
                      <span>15%</span>
                    </div>
                    <div className="h-2 w-full bg-[#F8F7F2] rounded-full overflow-hidden">
                      <div className="bg-[#0A0A0A] h-full" style={{ width: "15%" }} />
                    </div>
                  </div>
                  <div>
                    <div className="flex justify-between text-[10px] font-bold uppercase tracking-wider mb-1">
                      <span>Google Search</span>
                      <span>10%</span>
                    </div>
                    <div className="h-2 w-full bg-[#F8F7F2] rounded-full overflow-hidden">
                      <div className="bg-[#0A0A0A] h-full" style={{ width: "10%" }} />
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* Recent Sales Activity Feed */}
            <div className="border border-[#1A1A1A]/10 bg-white p-6 space-y-4">
              <h3 className="text-xs font-bold uppercase tracking-widest text-black">RECENT ORDERS LOGS</h3>
              <div className="overflow-x-auto">
                <table className="w-full text-left text-[11px] border-collapse font-sans">
                  <thead>
                    <tr className="bg-neutral-50 uppercase text-[9px] font-bold tracking-wider border-b border-[#1A1A1A]/10">
                      <th className="p-3">Customer</th>
                      <th className="p-3">Fulfillment City</th>
                      <th className="p-3">Details</th>
                      <th className="p-3 text-right">Invoice Sum</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-neutral-100">
                    {ordersList.map((ord, idx) => (
                      <tr key={idx} className="hover:bg-neutral-50/50">
                        <td className="p-3">
                          <span className="font-bold block text-black">{ord.customerName}</span>
                          <span className="text-[9px] text-neutral-400 block">{ord.customerEmail}</span>
                        </td>
                        <td className="p-3">
                          <span className="bg-neutral-100 text-black border border-neutral-300 text-[8px] font-bold px-2 py-0.5 rounded tracking-widest uppercase">
                            {ord.city || "LAHORE"}
                          </span>
                        </td>
                        <td className="p-3 text-neutral-600 max-w-xs truncate">
                          {ord.items.map((it: any) => `${it.name} (x${it.quantity})`).join(", ")}
                        </td>
                        <td className="p-3 text-right font-bold text-black">{formatPrice(ord.total)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>

          </div>
        )}

        {/* TAB 2: Product Inventory & Image uploads */}
        {adminTab === "products" && (
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
            
            {/* Create Product Form */}
            <form onSubmit={handleCreateProduct} className="lg:col-span-5 border border-[#1A1A1A]/10 bg-white p-6 space-y-4">
              <h3 className="text-xs font-bold uppercase tracking-widest text-black border-b pb-2 flex items-center gap-1">
                <Plus className="w-4 h-4" /> Add Streetwear Apparel
              </h3>

              <div className="space-y-1.5">
                <label className="text-[9px] font-bold uppercase tracking-wider text-neutral-400">Name</label>
                <input
                  type="text"
                  required
                  value={newProduct.name}
                  onChange={(e) => setNewProduct({ ...newProduct, name: e.target.value })}
                  placeholder="e.g. Starboy Cargo Joggers"
                  className="w-full bg-[#F8F7F2] border border-[#1A1A1A]/10 text-xs px-3 py-2 outline-none focus:border-[#D4AF37]"
                />
              </div>

              <div className="grid grid-cols-2 gap-2">
                <div className="space-y-1.5">
                  <label className="text-[9px] font-bold uppercase tracking-wider text-neutral-400">Price (PKR)</label>
                  <input
                    type="number"
                    required
                    value={newProduct.price}
                    onChange={(e) => setNewProduct({ ...newProduct, price: Number(e.target.value) })}
                    className="w-full bg-[#F8F7F2] border border-[#1A1A1A]/10 text-xs px-3 py-2 outline-none"
                  />
                </div>
                <div className="space-y-1.5">
                  <label className="text-[9px] font-bold uppercase tracking-wider text-neutral-400">Discount %</label>
                  <input
                    type="number"
                    value={newProduct.discount}
                    onChange={(e) => setNewProduct({ ...newProduct, discount: Number(e.target.value) })}
                    className="w-full bg-[#F8F7F2] border border-[#1A1A1A]/10 text-xs px-3 py-2 outline-none"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-2">
                <div className="space-y-1.5">
                  <label className="text-[9px] font-bold uppercase tracking-wider text-neutral-400">Category</label>
                  <select
                    value={newProduct.category}
                    onChange={(e) => setNewProduct({ ...newProduct, category: e.target.value })}
                    className="w-full bg-[#F8F7F2] border border-[#1A1A1A]/10 text-xs px-3 py-2 outline-none cursor-pointer"
                  >
                    <option value="Essentials">Essentials</option>
                    <option value="Oversized">Oversized</option>
                    <option value="Premium Cotton">Premium Cotton</option>
                  </select>
                </div>
                <div className="space-y-1.5">
                  <label className="text-[9px] font-bold uppercase tracking-wider text-neutral-400">Fabric Weight (GSM)</label>
                  <input
                    type="number"
                    value={newProduct.gsm}
                    onChange={(e) => setNewProduct({ ...newProduct, gsm: Number(e.target.value) })}
                    className="w-full bg-[#F8F7F2] border border-[#1A1A1A]/10 text-xs px-3 py-2 outline-none"
                  />
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[9px] font-bold uppercase tracking-wider text-neutral-400">Description</label>
                <textarea
                  required
                  rows={2}
                  value={newProduct.description}
                  onChange={(e) => setNewProduct({ ...newProduct, description: e.target.value })}
                  placeholder="Apparel cut, fit silhouette..."
                  className="w-full bg-[#F8F7F2] border border-[#1A1A1A]/10 text-xs px-3 py-2.5 outline-none resize-none"
                />
              </div>

              <div className="space-y-1.5">
                <label className="text-[9px] font-bold uppercase tracking-wider text-neutral-400">Craftsmanship Details</label>
                <input
                  type="text"
                  value={newProduct.craftsmanship}
                  onChange={(e) => setNewProduct({ ...newProduct, craftsmanship: e.target.value })}
                  placeholder="Double stitching, pre-shrunk..."
                  className="w-full bg-[#F8F7F2] border border-[#1A1A1A]/10 text-xs px-3 py-2 outline-none"
                />
              </div>

              {/* Multiple Images Upload & Link System */}
              <div className="border border-[#1A1A1A]/10 p-4 bg-[#F8F7F2]/40 space-y-4">
                <span className="text-[9px] font-bold uppercase tracking-widest text-neutral-400 block border-b pb-1.5">
                  Multiple Product Images (Uploader / Links)
                </span>

                {/* 1. Main Image */}
                <div className="space-y-1.5">
                  <label className="text-[8px] font-bold uppercase tracking-wider text-black block">1. Main Hero Image</label>
                  <div className="flex gap-2">
                    <input
                      type="text"
                      value={newProduct.image}
                      onChange={(e) => setNewProduct({ ...newProduct, image: e.target.value })}
                      placeholder="Paste link (e.g. /product.png)"
                      className="bg-white border border-[#1A1A1A]/10 text-[10px] px-3 py-2 outline-none flex-1"
                    />
                    <label className="bg-[#0A0A0A] hover:bg-[#D4AF37] text-white hover:text-black px-3 py-2 text-[10px] font-bold cursor-pointer transition-colors flex items-center justify-center gap-1 uppercase tracking-wider">
                      <Upload className="w-3.5 h-3.5" /> Upload Local
                      <input
                        type="file"
                        accept="image/*"
                        onChange={(e) => handleLocalImageUpload(e, "image")}
                        className="hidden"
                      />
                    </label>
                  </div>
                </div>

                {/* 2. Hover Image */}
                <div className="space-y-1.5">
                  <label className="text-[8px] font-bold uppercase tracking-wider text-black block">2. Hover Alternate Image</label>
                  <div className="flex gap-2">
                    <input
                      type="text"
                      value={newProduct.hoverImage}
                      onChange={(e) => setNewProduct({ ...newProduct, hoverImage: e.target.value })}
                      placeholder="Paste link (e.g. /hover.png)"
                      className="bg-white border border-[#1A1A1A]/10 text-[10px] px-3 py-2 outline-none flex-1"
                    />
                    <label className="bg-[#0A0A0A] hover:bg-[#D4AF37] text-white hover:text-black px-3 py-2 text-[10px] font-bold cursor-pointer transition-colors flex items-center justify-center gap-1 uppercase tracking-wider">
                      <Upload className="w-3.5 h-3.5" /> Upload Local
                      <input
                        type="file"
                        accept="image/*"
                        onChange={(e) => handleLocalImageUpload(e, "hoverImage")}
                        className="hidden"
                      />
                    </label>
                  </div>
                </div>

                {/* 3. Detail Gallery Image */}
                <div className="space-y-1.5">
                  <label className="text-[8px] font-bold uppercase tracking-wider text-black block">3. Detail Gallery Image</label>
                  <div className="flex gap-2">
                    <input
                      type="text"
                      value={newProduct.galleryImage3}
                      onChange={(e) => setNewProduct({ ...newProduct, galleryImage3: e.target.value })}
                      placeholder="Paste link (e.g. /gallery3.png)"
                      className="bg-white border border-[#1A1A1A]/10 text-[10px] px-3 py-2 outline-none flex-1"
                    />
                    <label className="bg-[#0A0A0A] hover:bg-[#D4AF37] text-white hover:text-black px-3 py-2 text-[10px] font-bold cursor-pointer transition-colors flex items-center justify-center gap-1 uppercase tracking-wider">
                      <Upload className="w-3.5 h-3.5" /> Upload Local
                      <input
                        type="file"
                        accept="image/*"
                        onChange={(e) => handleLocalImageUpload(e, "galleryImage3")}
                        className="hidden"
                      />
                    </label>
                  </div>
                </div>
              </div>

              <button
                type="submit"
                className="w-full bg-[#0A0A0A] hover:bg-[#D4AF37] text-white hover:text-black font-semibold text-xs tracking-widest py-3.5 border border-black hover:border-[#D4AF37] transition-all uppercase"
              >
                Add To Inventory
              </button>
            </form>

            {/* Products Inventory List Table */}
            <div className="lg:col-span-7 border border-[#1A1A1A]/10 bg-white overflow-x-auto">
              <table className="w-full text-left text-xs border-collapse">
                <thead>
                  <tr className="bg-[#0A0A0A] text-white uppercase text-[10px] tracking-widest font-bold border-b">
                    <th className="p-4">Product Info</th>
                    <th className="p-4 text-center">Category</th>
                    <th className="p-4 text-right">Price</th>
                    <th className="p-4 text-center">Stock</th>
                    <th className="p-4 text-center">Action</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-[#1A1A1A]/10">
                  {productsList.map((p) => (
                    <tr key={p.id} className="hover:bg-neutral-50/50">
                      <td className="p-4 flex gap-3 min-w-[200px]">
                        <div className="relative h-10 w-8 bg-neutral-100 flex-shrink-0">
                          <Image src={p.image} alt={p.name} fill className="object-cover" />
                        </div>
                        <div className="my-auto">
                          <span className="font-bold text-black uppercase block truncate max-w-[150px]">{p.name}</span>
                          <span className="text-[8px] text-neutral-400 uppercase tracking-widest">{p.gsm} GSM Weight</span>
                        </div>
                      </td>
                      <td className="p-4 text-center font-bold text-neutral-600 uppercase tracking-wider">{p.category}</td>
                      <td className="p-4 text-right font-sans font-bold text-black">{formatPrice(p.price)}</td>
                      <td className="p-4 text-center font-sans font-bold text-neutral-800">{p.stock} units</td>
                      <td className="p-4 text-center">
                        <button
                          onClick={() => handleDeleteProduct(p.id)}
                          className="text-neutral-400 hover:text-red-600 transition-colors"
                        >
                          <Trash2 className="w-4.5 h-4.5 mx-auto" />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

          </div>
        )}

        {/* TAB 3: Order Dispatch Status Manager */}
        {adminTab === "orders" && (
          <div className="border border-[#1A1A1A]/10 bg-white overflow-x-auto">
            <table className="w-full text-left text-xs border-collapse">
              <thead>
                <tr className="bg-[#0A0A0A] text-white uppercase text-[10px] tracking-widest font-bold">
                  <th className="p-4">OrderID</th>
                  <th className="p-4">Customer Details</th>
                  <th className="p-4">Purchased Items</th>
                  <th className="p-4 text-right">Invoice</th>
                  <th className="p-4 text-center">Fulfillment State</th>
                  <th className="p-4">Courier Link</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-[#1A1A1A]/10">
                {ordersList.map((ord) => (
                  <tr key={ord.orderId}>
                    <td className="p-4 font-bold text-black uppercase tracking-wider">{ord.orderId}</td>
                    <td className="p-4 space-y-0.5">
                      <span className="font-bold block">{ord.customerName}</span>
                      <span className="text-[9px] text-neutral-400 font-sans block">{ord.customerEmail}</span>
                    </td>
                    <td className="p-4 max-w-xs truncate">
                      {ord.items.map((it: any, idx: number) => (
                        <div key={idx} className="text-[10px] text-neutral-600 font-sans">
                          {it.name} ({it.size}/{it.color}) x{it.quantity}
                        </div>
                      ))}
                    </td>
                    <td className="p-4 text-right font-sans font-bold text-black">{formatPrice(ord.total)}</td>
                    <td className="p-4 text-center">
                      <select
                        value={ord.orderStatus}
                        onChange={(e) => handleUpdateOrderStatus(ord.orderId, e.target.value)}
                        className={`text-[9px] font-extrabold uppercase border px-2 py-1 outline-none cursor-pointer tracking-wider ${
                          ord.orderStatus === "Delivered"
                            ? "bg-green-50 border-green-200 text-green-700"
                            : ord.orderStatus === "Shipped"
                            ? "bg-blue-50 border-blue-200 text-blue-700"
                            : "bg-yellow-50 border-yellow-200 text-yellow-700"
                        }`}
                      >
                        <option value="Pending">Pending</option>
                        <option value="Processing">Processing</option>
                        <option value="Shipped">Shipped</option>
                        <option value="Delivered">Delivered</option>
                        <option value="Returned">Returned</option>
                      </select>
                    </td>
                    <td className="p-4 text-[10px] font-sans text-neutral-500">
                      {ord.trackingNumber ? (
                        <div>
                          <span className="block font-bold text-black uppercase tracking-wide">{ord.trackingNumber}</span>
                          <span className="block text-[8px] text-green-600 font-bold uppercase">{ord.courier} Integrated</span>
                        </div>
                      ) : (
                        <div className="space-y-1">
                          <select
                            id={`courier-select-${ord.orderId}`}
                            className="bg-[#F8F7F2] border border-[#1A1A1A]/10 text-[9px] font-bold p-1 outline-none w-full uppercase cursor-pointer"
                          >
                            {siteConfig.deliveryIntegrations?.postex && <option value="PostEx">PostEx Logistics</option>}
                            {siteConfig.deliveryIntegrations?.tcs && <option value="TCS">TCS Express</option>}
                            {siteConfig.deliveryIntegrations?.leopards && <option value="Leopards">Leopards Courier</option>}
                          </select>
                          <button
                            onClick={() => {
                              const selectEl = document.getElementById(`courier-select-${ord.orderId}`) as HTMLSelectElement;
                              const courier = selectEl?.value || "PostEx";
                              handleBookCourier(ord.orderId, courier);
                            }}
                            className="w-full bg-[#0A0A0A] hover:bg-[#D4AF37] text-white hover:text-black font-semibold text-[8px] tracking-widest py-1 border border-black hover:border-[#D4AF37] uppercase transition-all"
                          >
                            Generate Slip
                          </button>
                        </div>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* TAB 4: Campaigns simulator */}
        {adminTab === "marketing" && (
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
            {/* Promo coupons manager */}
            <div className="lg:col-span-5 border border-[#1A1A1A]/10 bg-white p-6 space-y-6">
              <h3 className="text-xs font-bold uppercase tracking-widest text-black border-b pb-2 flex items-center gap-1.5">
                <Percent className="w-4 h-4 text-[#D4AF37]" /> Active Vouchers Database
              </h3>
              
              <div className="space-y-3">
                {coupons.map((c, i) => (
                  <div key={i} className="flex justify-between items-center border border-[#1A1A1A]/10 p-3 bg-[#F8F7F2]/40 text-xs">
                    <span className="font-bold text-black uppercase tracking-wider">{c.code}</span>
                    <span className="text-[10px] font-extrabold bg-green-100 text-green-700 px-2 py-0.5 uppercase">
                      -{c.discount}% Discount
                    </span>
                  </div>
                ))}
              </div>
            </div>

            {/* Campaign SMS dispatch simulator */}
            <div className="lg:col-span-7 border border-[#1A1A1A]/10 bg-white p-6 space-y-6">
              <h3 className="text-xs font-bold uppercase tracking-widest text-black border-b pb-2 flex items-center gap-1.5">
                <Send className="w-4 h-4 text-[#D4AF37]" /> Campaign Dispatch Simulator
              </h3>

              <form onSubmit={handleTriggerCampaign} className="space-y-4">
                <div className="flex gap-4 text-xs font-bold uppercase tracking-widest">
                  <label className="flex items-center gap-1.5 cursor-pointer">
                    <input
                      type="radio"
                      name="campType"
                      checked={campaignType === "email"}
                      onChange={() => setCampaignType("email")}
                      className="accent-black h-3.5 w-3.5"
                    /> Email Campaign
                  </label>
                  <label className="flex items-center gap-1.5 cursor-pointer">
                    <input
                      type="radio"
                      name="campType"
                      checked={campaignType === "sms"}
                      onChange={() => setCampaignType("sms")}
                      className="accent-black h-3.5 w-3.5"
                    /> SMS Broadcast
                  </label>
                </div>

                <div className="space-y-1.5">
                  <label className="text-[9px] font-bold uppercase tracking-wider text-neutral-400">Broadcast Content</label>
                  <textarea
                    required
                    rows={4}
                    value={campaignText}
                    onChange={(e) => setCampaignText(e.target.value)}
                    placeholder={
                      campaignType === "email"
                        ? "STARBOY: Our New Collection is officially live. Get 10% off with coupon code WELCOME10..."
                        : "STARBOY PK: New Collection Live! Code FLASH20 gets you 20% off. Shop now: starboypakistan.com"
                    }
                    className="w-full bg-[#F8F7F2] border border-[#1A1A1A]/10 text-xs px-3 py-2.5 outline-none resize-none"
                  />
                </div>

                <button
                  type="submit"
                  className="bg-[#0A0A0A] hover:bg-[#D4AF37] text-white hover:text-black font-semibold text-xs tracking-widest px-8 py-3 transition-colors uppercase border border-black hover:border-[#D4AF37]"
                >
                  Launch Broadcast
                </button>
              </form>

              {/* Logs */}
              {campaignLogs.length > 0 && (
                <div className="border border-[#1A1A1A]/10 p-4 bg-neutral-900 rounded space-y-2">
                  <span className="text-[8px] font-bold text-[#D4AF37] uppercase tracking-wider block">DISPATCH TRACE LOGS</span>
                  <div className="max-h-36 overflow-y-auto space-y-1.5 pr-2 font-mono text-[9px] text-green-400 leading-normal">
                    {campaignLogs.map((log, i) => (
                      <p key={i}>{log}</p>
                    ))}
                  </div>
                </div>
              )}
            </div>

          </div>
        )}

        {/* TAB 5: Site Settings */}
        {adminTab === "settings" && (
          <div className="bg-white border border-[#1A1A1A]/10 p-6 md:p-8 space-y-8">
            <div className="border-b border-[#1A1A1A]/10 pb-4 flex items-center justify-between">
              <div>
                <h3 className="font-serif text-lg font-bold uppercase tracking-widest text-[#0A0A0A]">
                  Site Configuration Control
                </h3>
                <p className="text-[10px] text-neutral-400 font-sans mt-0.5">
                  Manage contact details, social links, payment options, and courier service APIs.
                </p>
              </div>
              <Settings className="w-5 h-5 text-neutral-400" />
            </div>

            {settingsSuccess && (
              <div className="bg-[#D4AF37]/10 border border-[#D4AF37]/30 text-black px-4 py-3 text-xs font-bold uppercase tracking-wider flex items-center gap-2">
                <CheckCircle className="w-4 h-4 text-[#D4AF37]" /> Configurations saved successfully and updated globally!
              </div>
            )}

            <form onSubmit={handleSettingsSubmit} className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                
                {/* Contact section */}
                <div className="space-y-4">
                  <h4 className="text-[10px] font-bold uppercase tracking-widest text-neutral-400 border-b border-neutral-100 pb-1.5">
                    01. Contact Channels
                  </h4>
                  <div className="space-y-3">
                    <div className="space-y-1.5">
                      <label className="text-[9px] font-bold uppercase tracking-wider text-neutral-500">Contact phone</label>
                      <input
                        type="text"
                        value={configForm.contactPhone}
                        onChange={(e) => setConfigForm({ ...configForm, contactPhone: e.target.value })}
                        required
                        className="w-full bg-[#F8F7F2] border border-[#1A1A1A]/10 text-xs px-3 py-2.5 outline-none font-sans"
                      />
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-[9px] font-bold uppercase tracking-wider text-neutral-500">WhatsApp number</label>
                      <input
                        type="text"
                        value={configForm.whatsappNumber}
                        onChange={(e) => setConfigForm({ ...configForm, whatsappNumber: e.target.value })}
                        required
                        className="w-full bg-[#F8F7F2] border border-[#1A1A1A]/10 text-xs px-3 py-2.5 outline-none font-sans"
                      />
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-[9px] font-bold uppercase tracking-wider text-neutral-500">Corporate Address</label>
                      <textarea
                        rows={2}
                        value={configForm.address}
                        onChange={(e) => setConfigForm({ ...configForm, address: e.target.value })}
                        required
                        className="w-full bg-[#F8F7F2] border border-[#1A1A1A]/10 text-xs px-3 py-2.5 outline-none font-sans resize-none"
                      />
                    </div>
                  </div>
                </div>

                {/* Social media section */}
                <div className="space-y-4">
                  <h4 className="text-[10px] font-bold uppercase tracking-widest text-neutral-400 border-b border-neutral-100 pb-1.5">
                    02. Social Channels
                  </h4>
                  <div className="space-y-3">
                    <div className="space-y-1.5">
                      <label className="text-[9px] font-bold uppercase tracking-wider text-neutral-500">Instagram Handle</label>
                      <input
                        type="text"
                        value={configForm.instagram}
                        onChange={(e) => setConfigForm({ ...configForm, instagram: e.target.value })}
                        className="w-full bg-[#F8F7F2] border border-[#1A1A1A]/10 text-xs px-3 py-2.5 outline-none font-sans"
                        placeholder="starboypakistan"
                      />
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-[9px] font-bold uppercase tracking-wider text-neutral-500">Facebook Slug</label>
                      <input
                        type="text"
                        value={configForm.facebook}
                        onChange={(e) => setConfigForm({ ...configForm, facebook: e.target.value })}
                        className="w-full bg-[#F8F7F2] border border-[#1A1A1A]/10 text-xs px-3 py-2.5 outline-none font-sans"
                        placeholder="starboy.pk"
                      />
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-[9px] font-bold uppercase tracking-wider text-neutral-500">TikTok Username</label>
                      <input
                        type="text"
                        value={configForm.tiktok}
                        onChange={(e) => setConfigForm({ ...configForm, tiktok: e.target.value })}
                        className="w-full bg-[#F8F7F2] border border-[#1A1A1A]/10 text-xs px-3 py-2.5 outline-none font-sans"
                        placeholder="starboypakistan"
                      />
                    </div>
                  </div>
                </div>

              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                
                {/* Payment toggles */}
                <div className="space-y-4">
                  <h4 className="text-[10px] font-bold uppercase tracking-widest text-neutral-400 border-b border-neutral-100 pb-1.5">
                    03. Payment Gateway Controls
                  </h4>
                  <div className="space-y-2 bg-[#F8F7F2] border border-[#1A1A1A]/5 p-4 font-sans text-xs">
                    <label className="flex items-center gap-3 cursor-pointer py-1.5">
                      <input
                        type="checkbox"
                        checked={configForm.paymentMethods.cod}
                        onChange={(e) => setConfigForm({
                          ...configForm,
                          paymentMethods: { ...configForm.paymentMethods, cod: e.target.checked }
                        })}
                        className="accent-black h-4 w-4"
                      />
                      <div>
                        <span className="font-bold text-black block">Cash On Delivery (COD)</span>
                        <span className="text-[10px] text-neutral-400">Enable cash orders confirmation at checkout</span>
                      </div>
                    </label>
                    <label className="flex items-center gap-3 cursor-pointer py-1.5 border-t border-neutral-200/50">
                      <input
                        type="checkbox"
                        checked={configForm.paymentMethods.easypaisa}
                        onChange={(e) => setConfigForm({
                          ...configForm,
                          paymentMethods: { ...configForm.paymentMethods, easypaisa: e.target.checked }
                        })}
                        className="accent-black h-4 w-4"
                      />
                      <div>
                        <span className="font-bold text-black block">Easypaisa Payments</span>
                        <span className="text-[10px] text-neutral-400">Allow customers to pay through mobile wallet transfer</span>
                      </div>
                    </label>
                    <label className="flex items-center gap-3 cursor-pointer py-1.5 border-t border-neutral-200/50">
                      <input
                        type="checkbox"
                        checked={configForm.paymentMethods.jazzcash}
                        onChange={(e) => setConfigForm({
                          ...configForm,
                          paymentMethods: { ...configForm.paymentMethods, jazzcash: e.target.checked }
                        })}
                        className="accent-black h-4 w-4"
                      />
                      <div>
                        <span className="font-bold text-black block">JazzCash Payments</span>
                        <span className="text-[10px] text-neutral-400">Allow customers to select JazzCash mobile transfer</span>
                      </div>
                    </label>
                    <label className="flex items-center gap-3 cursor-pointer py-1.5 border-t border-neutral-200/50">
                      <input
                        type="checkbox"
                        checked={configForm.paymentMethods.bankTransfer}
                        onChange={(e) => setConfigForm({
                          ...configForm,
                          paymentMethods: { ...configForm.paymentMethods, bankTransfer: e.target.checked }
                        })}
                        className="accent-black h-4 w-4"
                      />
                      <div>
                        <span className="font-bold text-black block">Direct Bank Transfer</span>
                        <span className="text-[10px] text-neutral-400">Display IBAN bank details for direct transfer orders</span>
                      </div>
                    </label>
                    <label className="flex items-center gap-3 cursor-pointer py-1.5 border-t border-neutral-200/50">
                      <input
                        type="checkbox"
                        checked={configForm.paymentMethods.stripe}
                        onChange={(e) => setConfigForm({
                          ...configForm,
                          paymentMethods: { ...configForm.paymentMethods, stripe: e.target.checked }
                        })}
                        className="accent-black h-4 w-4"
                      />
                      <div>
                        <span className="font-bold text-black block">Visa / Mastercard (Stripe)</span>
                        <span className="text-[10px] text-neutral-400">Enable card payment checkout (mock integration)</span>
                      </div>
                    </label>
                  </div>
                </div>

                {/* Delivery Integrations */}
                <div className="space-y-4">
                  <h4 className="text-[10px] font-bold uppercase tracking-widest text-neutral-400 border-b border-neutral-100 pb-1.5">
                    04. Courier Service Integrations
                  </h4>
                  <div className="space-y-2 bg-[#F8F7F2] border border-[#1A1A1A]/5 p-4 font-sans text-xs">
                    <label className="flex items-center gap-3 cursor-pointer py-1.5">
                      <input
                        type="checkbox"
                        checked={configForm.deliveryIntegrations.tcs}
                        onChange={(e) => setConfigForm({
                          ...configForm,
                          deliveryIntegrations: { ...configForm.deliveryIntegrations, tcs: e.target.checked }
                        })}
                        className="accent-black h-4 w-4"
                      />
                      <div>
                        <span className="font-bold text-black block">TCS Express APIs</span>
                        <span className="text-[10px] text-neutral-400">Enable automated slip generation with TCS Courier API</span>
                      </div>
                    </label>
                    <label className="flex items-center gap-3 cursor-pointer py-1.5 border-t border-neutral-200/50">
                      <input
                        type="checkbox"
                        checked={configForm.deliveryIntegrations.leopards}
                        onChange={(e) => setConfigForm({
                          ...configForm,
                          deliveryIntegrations: { ...configForm.deliveryIntegrations, leopards: e.target.checked }
                        })}
                        className="accent-black h-4 w-4"
                      />
                      <div>
                        <span className="font-bold text-black block">Leopards Courier APIs</span>
                        <span className="text-[10px] text-neutral-400">Enable logistics booking with Leopards Courier APIs</span>
                      </div>
                    </label>
                    <label className="flex items-center gap-3 cursor-pointer py-1.5 border-t border-neutral-200/50">
                      <input
                        type="checkbox"
                        checked={configForm.deliveryIntegrations.postex}
                        onChange={(e) => setConfigForm({
                          ...configForm,
                          deliveryIntegrations: { ...configForm.deliveryIntegrations, postex: e.target.checked }
                        })}
                        className="accent-black h-4 w-4"
                      />
                      <div>
                        <span className="font-bold text-black block">PostEx Logistics</span>
                        <span className="text-[10px] text-neutral-400">Enable PostEx Cash on Delivery & courier integration</span>
                      </div>
                    </label>
                  </div>
                </div>

              </div>

              {/* Courier API Keys & Configurations */}
              <div className="border-t border-[#1A1A1A]/10 pt-6">
                <h4 className="text-[11px] font-bold uppercase tracking-widest text-[#0A0A0A] mb-4">
                  05. Courier Integration Credentials
                </h4>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                  
                  {/* TCS config fields */}
                  {configForm.deliveryIntegrations?.tcs && (
                    <div className="space-y-3 p-4 bg-[#F8F7F2] border border-[#1A1A1A]/5 font-sans">
                      <span className="font-bold text-xs text-[#0A0A0A] uppercase tracking-wider block border-b border-[#1A1A1A]/10 pb-1">TCS Express Credentials</span>
                      <div className="space-y-2 text-xs">
                        <div>
                          <label className="text-[8px] font-bold uppercase text-neutral-500 block">TCS API Key</label>
                          <input
                            type="text"
                            value={configForm.courierConfig?.tcs?.apiKey || ""}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              courierConfig: {
                                ...configForm.courierConfig,
                                tcs: { ...configForm.courierConfig?.tcs, apiKey: e.target.value }
                              }
                            })}
                            className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none"
                            placeholder="Enter TCS API Key"
                          />
                        </div>
                        <div>
                          <label className="text-[8px] font-bold uppercase text-neutral-500 block">TCS Merchant ID</label>
                          <input
                            type="text"
                            value={configForm.courierConfig?.tcs?.merchantId || ""}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              courierConfig: {
                                ...configForm.courierConfig,
                                tcs: { ...configForm.courierConfig?.tcs, merchantId: e.target.value }
                              }
                            })}
                            className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none"
                            placeholder="Enter TCS Merchant ID"
                          />
                        </div>
                        <div>
                          <label className="text-[8px] font-bold uppercase text-neutral-500 block">Client Account Name</label>
                          <input
                            type="text"
                            value={configForm.courierConfig?.tcs?.clientName || ""}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              courierConfig: {
                                ...configForm.courierConfig,
                                tcs: { ...configForm.courierConfig?.tcs, clientName: e.target.value }
                              }
                            })}
                            className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none"
                            placeholder="Enter Client Name"
                          />
                        </div>
                        <label className="flex items-center gap-2 pt-1 cursor-pointer">
                          <input
                            type="checkbox"
                            checked={configForm.courierConfig?.tcs?.isSandbox ?? true}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              courierConfig: {
                                ...configForm.courierConfig,
                                tcs: { ...configForm.courierConfig?.tcs, isSandbox: e.target.checked }
                              }
                            })}
                            className="accent-black h-3.5 w-3.5"
                          />
                          <span className="text-[10px] text-neutral-500 font-bold uppercase">Sandbox Test Mode</span>
                        </label>
                      </div>
                    </div>
                  )}

                  {/* Leopards Config fields */}
                  {configForm.deliveryIntegrations?.leopards && (
                    <div className="space-y-3 p-4 bg-[#F8F7F2] border border-[#1A1A1A]/5 font-sans">
                      <span className="font-bold text-xs text-[#0A0A0A] uppercase tracking-wider block border-b border-[#1A1A1A]/10 pb-1">Leopards Credentials</span>
                      <div className="space-y-2 text-xs">
                        <div>
                          <label className="text-[8px] font-bold uppercase text-neutral-500 block">Leopards API Key</label>
                          <input
                            type="text"
                            value={configForm.courierConfig?.leopards?.apiKey || ""}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              courierConfig: {
                                ...configForm.courierConfig,
                                leopards: { ...configForm.courierConfig?.leopards, apiKey: e.target.value }
                              }
                            })}
                            className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none"
                            placeholder="Enter Leopards API Key"
                          />
                        </div>
                        <div>
                          <label className="text-[8px] font-bold uppercase text-neutral-500 block">API Password</label>
                          <input
                            type="password"
                            value={configForm.courierConfig?.leopards?.apiPassword || ""}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              courierConfig: {
                                ...configForm.courierConfig,
                                leopards: { ...configForm.courierConfig?.leopards, apiPassword: e.target.value }
                              }
                            })}
                            className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none"
                            placeholder="Enter API Password"
                          />
                        </div>
                        <div>
                          <label className="text-[8px] font-bold uppercase text-neutral-500 block">Leopards Merchant ID</label>
                          <input
                            type="text"
                            value={configForm.courierConfig?.leopards?.merchantId || ""}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              courierConfig: {
                                ...configForm.courierConfig,
                                leopards: { ...configForm.courierConfig?.leopards, merchantId: e.target.value }
                              }
                            })}
                            className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none"
                            placeholder="Enter Merchant ID"
                          />
                        </div>
                        <label className="flex items-center gap-2 pt-1 cursor-pointer">
                          <input
                            type="checkbox"
                            checked={configForm.courierConfig?.leopards?.isSandbox ?? true}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              courierConfig: {
                                ...configForm.courierConfig,
                                leopards: { ...configForm.courierConfig?.leopards, isSandbox: e.target.checked }
                              }
                            })}
                            className="accent-black h-3.5 w-3.5"
                          />
                          <span className="text-[10px] text-neutral-500 font-bold uppercase">Sandbox Test Mode</span>
                        </label>
                      </div>
                    </div>
                  )}

                  {/* PostEx Config fields */}
                  {configForm.deliveryIntegrations?.postex && (
                    <div className="space-y-3 p-4 bg-[#F8F7F2] border border-[#1A1A1A]/5 font-sans">
                      <span className="font-bold text-xs text-[#0A0A0A] uppercase tracking-wider block border-b border-[#1A1A1A]/10 pb-1">PostEx Credentials</span>
                      <div className="space-y-2 text-xs">
                        <div>
                          <label className="text-[8px] font-bold uppercase text-neutral-500 block">PostEx API Token</label>
                          <input
                            type="text"
                            value={configForm.courierConfig?.postex?.apiKey || ""}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              courierConfig: {
                                ...configForm.courierConfig,
                                postex: { ...configForm.courierConfig?.postex, apiKey: e.target.value }
                              }
                            })}
                            className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none"
                            placeholder="Enter PostEx API Token"
                          />
                        </div>
                        <div>
                          <label className="text-[8px] font-bold uppercase text-neutral-500 block">Client ID / Merchant Code</label>
                          <input
                            type="text"
                            value={configForm.courierConfig?.postex?.clientId || ""}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              courierConfig: {
                                ...configForm.courierConfig,
                                postex: { ...configForm.courierConfig?.postex, clientId: e.target.value }
                              }
                            })}
                            className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none"
                            placeholder="Enter Client ID"
                          />
                        </div>
                        <label className="flex items-center gap-2 pt-1 cursor-pointer">
                          <input
                            type="checkbox"
                            checked={configForm.courierConfig?.postex?.isSandbox ?? true}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              courierConfig: {
                                ...configForm.courierConfig,
                                postex: { ...configForm.courierConfig?.postex, isSandbox: e.target.checked }
                              }
                            })}
                            className="accent-black h-3.5 w-3.5"
                          />
                          <span className="text-[10px] text-neutral-500 font-bold uppercase">Sandbox Test Mode</span>
                        </label>
                      </div>
                    </div>
                  )}

                </div>
              </div>

              {/* Payment Gateway API Keys & merchant accounts */}
              <div className="border-t border-[#1A1A1A]/10 pt-6">
                <h4 className="text-[11px] font-bold uppercase tracking-widest text-[#0A0A0A] mb-4">
                  06. Payment Gateway Accounts & Keys
                </h4>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  
                  {/* Stripe Configuration */}
                  {configForm.paymentMethods?.stripe && (
                    <div className="space-y-3 p-4 bg-[#F8F7F2] border border-[#1A1A1A]/5 font-sans">
                      <span className="font-bold text-xs text-[#0A0A0A] uppercase tracking-wider block border-b border-[#1A1A1A]/10 pb-1">Stripe Gateway Keys</span>
                      <div className="space-y-2 text-xs">
                        <div>
                          <label className="text-[8px] font-bold uppercase text-neutral-500 block">Stripe Publishable Key</label>
                          <input
                            type="text"
                            value={configForm.paymentConfig?.stripe?.publishableKey || ""}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              paymentConfig: {
                                ...configForm.paymentConfig,
                                stripe: { ...configForm.paymentConfig?.stripe, publishableKey: e.target.value }
                              }
                            })}
                            className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none font-mono"
                            placeholder="pk_test_..."
                          />
                        </div>
                        <div>
                          <label className="text-[8px] font-bold uppercase text-neutral-500 block">Stripe Secret Key</label>
                          <input
                            type="password"
                            value={configForm.paymentConfig?.stripe?.secretKey || ""}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              paymentConfig: {
                                ...configForm.paymentConfig,
                                stripe: { ...configForm.paymentConfig?.stripe, secretKey: e.target.value }
                              }
                            })}
                            className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none font-mono"
                            placeholder="sk_test_..."
                          />
                        </div>
                      </div>
                    </div>
                  )}

                  {/* Easypaisa Merchant Account */}
                  {configForm.paymentMethods?.easypaisa && (
                    <div className="space-y-3 p-4 bg-[#F8F7F2] border border-[#1A1A1A]/5 font-sans">
                      <span className="font-bold text-xs text-[#0A0A0A] uppercase tracking-wider block border-b border-[#1A1A1A]/10 pb-1">Easypaisa Merchant Details</span>
                      <div className="space-y-2 text-xs">
                        <div>
                          <label className="text-[8px] font-bold uppercase text-neutral-500 block">Store ID / Merchant ID</label>
                          <input
                            type="text"
                            value={configForm.paymentConfig?.easypaisa?.storeId || ""}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              paymentConfig: {
                                ...configForm.paymentConfig,
                                easypaisa: { ...configForm.paymentConfig?.easypaisa, storeId: e.target.value }
                              }
                            })}
                            className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none"
                            placeholder="Enter Store ID"
                          />
                        </div>
                        <div>
                          <label className="text-[8px] font-bold uppercase text-neutral-500 block">Hash key / Integrity Key</label>
                          <input
                            type="password"
                            value={configForm.paymentConfig?.easypaisa?.hashKey || ""}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              paymentConfig: {
                                ...configForm.paymentConfig,
                                easypaisa: { ...configForm.paymentConfig?.easypaisa, hashKey: e.target.value }
                              }
                            })}
                            className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none"
                            placeholder="Enter Hash Key"
                          />
                        </div>
                        <div>
                          <label className="text-[8px] font-bold uppercase text-neutral-500 block">Receiver Phone / Account Mobile</label>
                          <input
                            type="text"
                            value={configForm.paymentConfig?.easypaisa?.receiverPhone || ""}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              paymentConfig: {
                                ...configForm.paymentConfig,
                                easypaisa: { ...configForm.paymentConfig?.easypaisa, receiverPhone: e.target.value }
                              }
                            })}
                            className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none"
                            placeholder="+92 3xx xxxxxxx"
                          />
                        </div>
                      </div>
                    </div>
                  )}

                  {/* JazzCash Merchant details */}
                  {configForm.paymentMethods?.jazzcash && (
                    <div className="space-y-3 p-4 bg-[#F8F7F2] border border-[#1A1A1A]/5 font-sans">
                      <span className="font-bold text-xs text-[#0A0A0A] uppercase tracking-wider block border-b border-[#1A1A1A]/10 pb-1">JazzCash Merchant Details</span>
                      <div className="space-y-2 text-xs">
                        <div>
                          <label className="text-[8px] font-bold uppercase text-neutral-500 block">Merchant ID</label>
                          <input
                            type="text"
                            value={configForm.paymentConfig?.jazzcash?.merchantId || ""}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              paymentConfig: {
                                ...configForm.paymentConfig,
                                jazzcash: { ...configForm.paymentConfig?.jazzcash, merchantId: e.target.value }
                              }
                            })}
                            className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none"
                            placeholder="Enter Merchant ID"
                          />
                        </div>
                        <div>
                          <label className="text-[8px] font-bold uppercase text-neutral-500 block">API Password</label>
                          <input
                            type="password"
                            value={configForm.paymentConfig?.jazzcash?.password || ""}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              paymentConfig: {
                                ...configForm.paymentConfig,
                                jazzcash: { ...configForm.paymentConfig?.jazzcash, password: e.target.value }
                              }
                            })}
                            className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none"
                            placeholder="Enter API Password"
                          />
                        </div>
                        <div>
                          <label className="text-[8px] font-bold uppercase text-neutral-500 block">Integrity Salt</label>
                          <input
                            type="password"
                            value={configForm.paymentConfig?.jazzcash?.integritySalt || ""}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              paymentConfig: {
                                ...configForm.paymentConfig,
                                jazzcash: { ...configForm.paymentConfig?.jazzcash, integritySalt: e.target.value }
                              }
                            })}
                            className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none"
                            placeholder="Enter Integrity Salt"
                          />
                        </div>
                      </div>
                    </div>
                  )}

                  {/* Bank Transfer details */}
                  {configForm.paymentMethods?.bankTransfer && (
                    <div className="space-y-3 p-4 bg-[#F8F7F2] border border-[#1A1A1A]/5 font-sans">
                      <span className="font-bold text-xs text-[#0A0A0A] uppercase tracking-wider block border-b border-[#1A1A1A]/10 pb-1">Corporate Bank Account</span>
                      <div className="space-y-2 text-xs">
                        <div className="grid grid-cols-2 gap-2">
                          <div>
                            <label className="text-[8px] font-bold uppercase text-neutral-500 block">Bank Name</label>
                            <input
                              type="text"
                              value={configForm.paymentConfig?.bankTransfer?.bankName || ""}
                              onChange={(e) => setConfigForm({
                                ...configForm,
                                paymentConfig: {
                                  ...configForm.paymentConfig,
                                  bankTransfer: { ...configForm.paymentConfig?.bankTransfer, bankName: e.target.value }
                                }
                              })}
                              className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none"
                              placeholder="e.g. Meezan Bank"
                            />
                          </div>
                          <div>
                            <label className="text-[8px] font-bold uppercase text-neutral-500 block">Account Title</label>
                            <input
                              type="text"
                              value={configForm.paymentConfig?.bankTransfer?.accountTitle || ""}
                              onChange={(e) => setConfigForm({
                                ...configForm,
                                paymentConfig: {
                                  ...configForm.paymentConfig,
                                  bankTransfer: { ...configForm.paymentConfig?.bankTransfer, accountTitle: e.target.value }
                                }
                              })}
                              className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none"
                              placeholder="e.g. Starboy Pakistan"
                            />
                          </div>
                        </div>
                        <div>
                          <label className="text-[8px] font-bold uppercase text-neutral-500 block">Account Number</label>
                          <input
                            type="text"
                            value={configForm.paymentConfig?.bankTransfer?.accountNumber || ""}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              paymentConfig: {
                                ...configForm.paymentConfig,
                                bankTransfer: { ...configForm.paymentConfig?.bankTransfer, accountNumber: e.target.value }
                              }
                            })}
                            className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none"
                            placeholder="Enter Account Number"
                          />
                        </div>
                        <div>
                          <label className="text-[8px] font-bold uppercase text-neutral-500 block">IBAN Number</label>
                          <input
                            type="text"
                            value={configForm.paymentConfig?.bankTransfer?.iban || ""}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              paymentConfig: {
                                ...configForm.paymentConfig,
                                bankTransfer: { ...configForm.paymentConfig?.bankTransfer, iban: e.target.value }
                              }
                            })}
                            className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none"
                            placeholder="e.g. PK92MEZN..."
                          />
                        </div>
                      </div>
                    </div>
                  )}

                  {/* Cash On Delivery Instructions */}
                  {configForm.paymentMethods?.cod && (
                    <div className="space-y-3 p-4 bg-[#F8F7F2] border border-[#1A1A1A]/5 font-sans md:col-span-2">
                      <span className="font-bold text-xs text-[#0A0A0A] uppercase tracking-wider block border-b border-[#1A1A1A]/10 pb-1">COD Dispatch Instructions</span>
                      <div className="space-y-2 text-xs">
                        <div>
                          <label className="text-[8px] font-bold uppercase text-neutral-500 block">Customer Facing checkout notice</label>
                          <textarea
                            rows={2}
                            value={configForm.paymentConfig?.cod?.instructions || ""}
                            onChange={(e) => setConfigForm({
                              ...configForm,
                              paymentConfig: {
                                ...configForm.paymentConfig,
                                cod: { ...configForm.paymentConfig?.cod, instructions: e.target.value }
                              }
                            })}
                            className="w-full bg-white border border-[#1A1A1A]/10 text-xs px-2.5 py-2 outline-none resize-none font-sans"
                            placeholder="Enter COD terms and conditions"
                          />
                        </div>
                      </div>
                    </div>
                  )}

                </div>
              </div>

              <div className="border-t border-[#1A1A1A]/10 pt-6">
                <button
                  type="submit"
                  className="bg-[#0A0A0A] hover:bg-[#D4AF37] text-white hover:text-black font-semibold text-xs tracking-widest px-8 py-3.5 border border-black hover:border-[#D4AF37] transition-all uppercase"
                >
                  Save Configurations
                </button>
              </div>
            </form>
          </div>
        )}

      </main>

      <Footer />
      <FloatingWhatsApp />
      <AIAssistant />
    </div>
  );
}
