'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import {
  Palette, Paintbrush, RotateCcw, Save, Monitor, Globe, Bell,
  Shield, Database, Image as ImageIcon, Upload, X, Loader2,
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Badge } from '@/components/ui/badge';
import { useAppStore } from '@/lib/store';
import { useToast } from '@/hooks/use-toast';

const ORANGE_BTN = 'bg-gradient-to-r from-orange-600 to-amber-500 shadow-sm';

interface AppSettings {
  appName: string; appTagline: string; appDescription: string;
  primaryColor: string; accentColor: string; backgroundColor: string;
  logoText: string; fontFamily: string; borderRadius: string;
  darkMode: boolean; rtl: boolean;
  maintenanceMode: boolean; registrationOpen: boolean; emailVerification: boolean;
  maxUploadSize: string; defaultLanguage: string; currency: string;
  enableChat: boolean; enableCommunity: boolean; enableMCQ: boolean;
  enableHouses: boolean; enableShops: boolean; enableProducts: boolean;
  seoTitle: string; seoDescription: string;
  googleAnalyticsId: string;
  notificationEmail: boolean; notificationPush: boolean; notificationSMS: boolean;
  // Media URLs
  appLogoUrl: string; faviconUrl: string; splashLogoUrl: string; ogImage: string;
}

interface UploadState {
  loading: boolean;
  error: string;
  success: boolean;
}

const defaultSettings: AppSettings = {
  appName: 'Needyfy', appTagline: 'Bangladesh Super App', appDescription: 'Your all-in-one platform for housing, shopping, education and more in Bangladesh',
  primaryColor: '#ea580c', accentColor: '#f59e0b', backgroundColor: '#ffffff',
  logoText: 'Needyfy', fontFamily: 'Inter', borderRadius: '12',
  darkMode: true, rtl: false,
  maintenanceMode: false, registrationOpen: true, emailVerification: false,
  maxUploadSize: '5', defaultLanguage: 'bn', currency: 'BDT',
  enableChat: true, enableCommunity: true, enableMCQ: true,
  enableHouses: true, enableShops: true, enableProducts: true,
  seoTitle: 'Needyfy - Bangladesh Super App', seoDescription: 'Find houses, shops, products and educational content',
  googleAnalyticsId: '',
  notificationEmail: true, notificationPush: true, notificationSMS: false,
  appLogoUrl: '', faviconUrl: '', splashLogoUrl: '', ogImage: '',
};

// ============ IMAGE UPLOAD CARD ============
function ImageUploadCard({
  label,
  description,
  settingKey,
  currentUrl,
  category,
  previewClassName,
  onUploadSuccess,
  adminToken,
}: {
  label: string;
  description: string;
  settingKey: string;
  currentUrl: string;
  category: string;
  previewClassName?: string;
  onUploadSuccess: (key: string, url: string) => void;
  adminToken: string | null;
}) {
  const { toast } = useToast();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploading(true);
    onUploadSuccess(settingKey, '__uploading__');

    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('category', category);

      const uploadHeaders: Record<string, string> = {};
      if (adminToken) uploadHeaders['x-admin-token'] = adminToken;

      const uploadRes = await fetch('/api/admin/upload', {
        method: 'POST',
        headers: uploadHeaders,
        body: formData,
      });

      const uploadData = await uploadRes.json();

      if (!uploadData.success) {
        onUploadSuccess(settingKey, currentUrl); // revert
        toast({ title: 'Upload failed', description: uploadData.error || 'Could not upload file', variant: 'destructive' });
        return;
      }

      // Save URL to settings
      const settingsRes = await fetch('/api/admin/settings', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json', ...(adminToken ? { 'x-admin-token': adminToken } : {}) },
        body: JSON.stringify({ key: settingKey, value: uploadData.url, category: 'branding' }),
      });

      const settingsData = await settingsRes.json();

      if (settingsData.success) {
        onUploadSuccess(settingKey, uploadData.url);
        toast({ title: `${label} uploaded successfully`, duration: 2000 });
      } else {
        onUploadSuccess(settingKey, currentUrl); // revert
        toast({ title: 'Failed to save setting', variant: 'destructive' });
      }
    } catch {
      onUploadSuccess(settingKey, currentUrl); // revert
      toast({ title: 'Upload error', description: 'Network error occurred', variant: 'destructive' });
    } finally {
      setUploading(false);
      // Reset file input
      if (fileInputRef.current) fileInputRef.current.value = '';
    }
  };

  const handleRemove = async () => {
    try {
      await fetch('/api/admin/settings', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json', ...(adminToken ? { 'x-admin-token': adminToken } : {}) },
        body: JSON.stringify({ key: settingKey, value: '', category: 'branding' }),
      });
      onUploadSuccess(settingKey, '');
      toast({ title: `${label} removed`, duration: 2000 });
    } catch {
      // ignore
    }
  };

  return (
    <div className="rounded-xl border bg-slate-50 p-4 dark:bg-slate-800/50">
      <div className="flex items-start justify-between gap-3">
        <div className="flex-1 min-w-0">
          <Label className="text-sm font-medium">{label}</Label>
          <p className="text-xs text-muted-foreground mt-0.5">{description}</p>
        </div>
        {currentUrl && currentUrl !== '__uploading__' && (
          <Button
            variant="ghost"
            size="icon"
            className="h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive"
            onClick={handleRemove}
            title="Remove"
          >
            <X className="h-3.5 w-3.5" />
          </Button>
        )}
      </div>

      {/* Preview / Upload Area */}
      <div className="mt-3">
        {currentUrl && currentUrl !== '__uploading__' ? (
          <div className="relative group">
            <div className={`overflow-hidden rounded-lg border bg-white dark:bg-slate-900 ${previewClassName || 'h-24 flex items-center justify-center'}`}>
              <img
                src={currentUrl}
                alt={label}
                className="max-h-full max-w-full object-contain"
                onError={(e) => {
                  (e.target as HTMLImageElement).style.display = 'none';
                }}
              />
            </div>
            <div className="mt-2 flex items-center gap-2">
              <p className="text-[10px] text-muted-foreground truncate flex-1">{currentUrl}</p>
              <Button
                variant="outline"
                size="sm"
                className="h-6 text-[10px] shrink-0"
                onClick={() => fileInputRef.current?.click()}
              >
                Replace
              </Button>
            </div>
          </div>
        ) : currentUrl === '__uploading__' ? (
          <div className={`rounded-lg border-2 border-dashed border-orange-300 bg-orange-50/50 dark:border-orange-700 dark:bg-orange-950/20 ${previewClassName || 'h-24'} flex items-center justify-center`}>
            <div className="flex flex-col items-center gap-1">
              <Loader2 className="h-6 w-6 animate-spin text-orange-500" />
              <p className="text-[10px] text-orange-600 dark:text-orange-400">Uploading...</p>
            </div>
          </div>
        ) : (
          <button
            onClick={() => fileInputRef.current?.click()}
            className={`w-full rounded-lg border-2 border-dashed border-slate-300 bg-slate-100/50 hover:border-orange-400 hover:bg-orange-50/50 dark:border-slate-600 dark:bg-slate-800/30 dark:hover:border-orange-600 dark:hover:bg-orange-950/20 transition-colors cursor-pointer ${previewClassName || 'h-24'} flex flex-col items-center justify-center gap-1.5`}
          >
            <Upload className="h-5 w-5 text-muted-foreground" />
            <p className="text-xs text-muted-foreground">Click to upload</p>
            <p className="text-[10px] text-muted-foreground/60">PNG, JPG, SVG, ICO (max 5MB)</p>
          </button>
        )}
      </div>

      <input
        ref={fileInputRef}
        type="file"
        accept="image/png,image/jpeg,image/jpg,image/gif,image/webp,image/svg+xml,image/x-icon,image/vnd.microsoft.icon"
        onChange={handleFileChange}
        className="hidden"
      />
    </div>
  );
}

export function AdminSettings() {
  const { adminToken } = useAppStore();
  const { toast } = useToast();
  const [settings, setSettings] = useState<AppSettings>(defaultSettings);
  const [saving, setSaving] = useState(false);
  const [activeSection, setActiveSection] = useState('branding');
  const [loading, setLoading] = useState(true);
  const [uploadStates, setUploadStates] = useState<Record<string, UploadState>>({});

  // Load settings from API on mount
  useEffect(() => {
    const loadSettings = async () => {
      try {
        const headers: Record<string, string> = { 'Content-Type': 'application/json' };
        if (adminToken) headers['x-admin-token'] = adminToken;
        const res = await fetch('/api/admin/settings', { headers });
        const data = await res.json();
        if (data.success && data.flat) {
          const flat = data.flat;
          setSettings(prev => ({
            ...prev,
            appName: flat.appName || prev.appName,
            appTagline: flat.appTagline || prev.appTagline,
            appDescription: flat.appDescription || prev.appDescription,
            primaryColor: flat.primaryColor || prev.primaryColor,
            accentColor: flat.accentColor || prev.accentColor,
            backgroundColor: flat.backgroundColor || prev.backgroundColor,
            logoText: flat.appLogo || prev.logoText,
            fontFamily: flat.fontFamily || prev.fontFamily,
            borderRadius: flat.borderRadius || prev.borderRadius,
            darkMode: flat.darkMode === 'true',
            rtl: prev.rtl,
            maintenanceMode: flat.maintenanceMode === 'true',
            registrationOpen: flat.registrationOpen !== 'false',
            emailVerification: flat.emailVerification === 'true',
            maxUploadSize: flat.maxUploadSize || prev.maxUploadSize,
            defaultLanguage: flat.defaultLanguage || prev.defaultLanguage,
            currency: flat.currencySymbol === '৳' ? 'BDT' : 'USD',
            enableChat: flat.enableMessaging !== 'false',
            enableCommunity: flat.enableCommunity !== 'false',
            enableMCQ: flat.enableEducation !== 'false',
            enableHouses: flat.enableHouseRental !== 'false',
            enableShops: flat.enableShopRental !== 'false',
            enableProducts: flat.enableMarketplace !== 'false',
            seoTitle: flat.seoTitle || prev.seoTitle,
            seoDescription: flat.seoDescription || prev.seoDescription,
            googleAnalyticsId: flat.googleAnalyticsId || prev.googleAnalyticsId,
            notificationEmail: flat.notificationEmail !== 'false',
            notificationPush: flat.notificationPush !== 'false',
            notificationSMS: flat.notificationSMS === 'true',
            // Media URLs
            appLogoUrl: flat.appLogoUrl || flat.appLogo || '',
            faviconUrl: flat.faviconUrl || '',
            splashLogoUrl: flat.splashLogoUrl || '',
            ogImage: flat.ogImage || '',
          }));
        }
      } catch { /* use defaults */ }
      finally {
        setLoading(false);
      }
    };
    loadSettings();
  }, [adminToken]);

  const update = (key: keyof AppSettings, value: any) => setSettings(prev => ({ ...prev, [key]: value }));

  const handleUploadSuccess = useCallback((key: string, url: string) => {
    setSettings(prev => ({ ...prev, [key]: url }));
  }, []);

  const handleSave = async () => {
    setSaving(true);
    try {
      const headers: Record<string, string> = { 'Content-Type': 'application/json' };
      if (adminToken) headers['x-admin-token'] = adminToken;
      // Convert flat settings object to array format expected by API
      const settingsArray = Object.entries(settings).map(([key, value]) => ({
        key,
        value: String(typeof value === 'boolean' ? value : value),
        category: key.startsWith('enable') || key.startsWith('notification') ? 'modules' :
                  key.includes('Color') || key === 'fontFamily' || key === 'borderRadius' || key === 'darkMode' || key === 'rtl' || key === 'backgroundColor' ? 'appearance' :
                  key.startsWith('seo') || key === 'googleAnalyticsId' ? 'seo' :
                  key.startsWith('maintenance') || key.startsWith('registration') || key.startsWith('email') || key === 'maxUploadSize' ? 'auth' :
                  key === 'appLogoUrl' || key === 'faviconUrl' || key === 'splashLogoUrl' || key === 'ogImage' ? 'branding' :
                  'branding',
      }));
      const res = await fetch('/api/admin/settings', { method: 'POST', headers, body: JSON.stringify({ settings: settingsArray }) });
      const data = await res.json();
      if (data.success) {
        toast({ title: 'Settings saved successfully!', duration: 2000 });
        // Also save customizations to localStorage for immediate UI effect
        try {
          localStorage.setItem('needyfy_customizations', JSON.stringify({
            primaryColor: settings.primaryColor,
            accentColor: settings.accentColor,
            fontFamily: settings.fontFamily,
          }));
          // Apply CSS variables immediately
          const root = document.documentElement;
          if (settings.primaryColor) root.style.setProperty('--primary', settings.primaryColor);
          if (settings.accentColor) root.style.setProperty('--accent', settings.accentColor);
        } catch { /* ignore */ }
      }
    } catch {
      toast({ title: 'Failed to save settings', variant: 'destructive' });
    }
    setSaving(false);
  };

  const handleReset = () => {
    setSettings(defaultSettings);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <span className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
      </div>
    );
  }

  const sections = [
    { id: 'branding', label: 'Branding', icon: Palette },
    { id: 'media', label: 'Media & Logo', icon: ImageIcon },
    { id: 'appearance', label: 'Appearance', icon: Paintbrush },
    { id: 'features', label: 'Features', icon: Monitor },
    { id: 'auth', label: 'Auth & Security', icon: Shield },
    { id: 'seo', label: 'SEO & Meta', icon: Globe },
    { id: 'notifications', label: 'Notifications', icon: Bell },
    { id: 'advanced', label: 'Advanced', icon: Database },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold">Customization Settings</h3>
          <p className="text-sm text-muted-foreground">Full control over your app&apos;s appearance and behavior</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm" className="gap-2 text-xs" onClick={handleReset}>
            <RotateCcw className="h-3.5 w-3.5" />Reset
          </Button>
          <Button className={`gap-2 ${ORANGE_BTN} text-xs`} size="sm" onClick={handleSave} disabled={saving}>
            <Save className="h-3.5 w-3.5" />{saving ? 'Saving...' : 'Save All'}
          </Button>
        </div>
      </div>

      <div className="flex gap-6">
        {/* Settings Sidebar */}
        <div className="hidden md:flex flex-col w-48 shrink-0 space-y-1">
          {sections.map((s) => (
            <button
              key={s.id}
              onClick={() => setActiveSection(s.id)}
              className={`flex items-center gap-2.5 rounded-lg px-3 py-2 text-sm transition-all ${
                activeSection === s.id
                  ? 'bg-orange-50 font-semibold text-orange-600 dark:bg-orange-950/20 dark:text-orange-400'
                  : 'text-muted-foreground hover:bg-slate-50 dark:hover:bg-slate-800'
              }`}
            >
              <s.icon className="h-4 w-4" />{s.label}
            </button>
          ))}
        </div>

        {/* Settings Content */}
        <div className="flex-1 space-y-4">
          {/* Mobile Section Selector */}
          <div className="md:hidden flex gap-2 overflow-x-auto pb-1">
            {sections.map((s) => (
              <Button
                key={s.id}
                variant={activeSection === s.id ? 'default' : 'outline'}
                size="sm"
                className={`shrink-0 text-xs ${activeSection === s.id ? ORANGE_BTN : ''}`}
                onClick={() => setActiveSection(s.id)}
              >
                {s.label}
              </Button>
            ))}
          </div>

          {/* ============ BRANDING ============ */}
          {activeSection === 'branding' && (
            <Card className="border-0 shadow-sm">
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-sm">
                  <Palette className="h-4 w-4 text-orange-500" />Branding
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <Label className="text-xs font-medium">App Name</Label>
                    <Input value={settings.appName} onChange={(e) => update('appName', e.target.value)} />
                  </div>
                  <div className="space-y-1.5">
                    <Label className="text-xs font-medium">Logo Text</Label>
                    <Input value={settings.logoText} onChange={(e) => update('logoText', e.target.value)} />
                  </div>
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs font-medium">Tagline</Label>
                  <Input value={settings.appTagline} onChange={(e) => update('appTagline', e.target.value)} />
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs font-medium">Description</Label>
                  <Input value={settings.appDescription} onChange={(e) => update('appDescription', e.target.value)} />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <Label className="text-xs font-medium">Default Language</Label>
                    <select value={settings.defaultLanguage} onChange={(e) => update('defaultLanguage', e.target.value)} className="w-full rounded-lg border bg-background px-3 py-2 text-sm">
                      <option value="bn">বাংলা (Bengali)</option>
                      <option value="en">English</option>
                    </select>
                  </div>
                  <div className="space-y-1.5">
                    <Label className="text-xs font-medium">Currency</Label>
                    <select value={settings.currency} onChange={(e) => update('currency', e.target.value)} className="w-full rounded-lg border bg-background px-3 py-2 text-sm">
                      <option value="BDT">৳ BDT (Taka)</option>
                      <option value="USD">$ USD</option>
                    </select>
                  </div>
                </div>
              </CardContent>
            </Card>
          )}

          {/* ============ MEDIA & LOGO ============ */}
          {activeSection === 'media' && (
            <Card className="border-0 shadow-sm">
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-sm">
                  <ImageIcon className="h-4 w-4 text-orange-500" />Media & Logo
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="rounded-xl border border-orange-200 bg-orange-50 p-3 dark:border-orange-900/50 dark:bg-orange-950/20">
                  <p className="text-xs font-medium text-orange-700 dark:text-orange-400">
                    Upload your app branding assets. Changes are saved immediately and reflected across the app.
                  </p>
                </div>

                <div className="grid gap-4 sm:grid-cols-2">
                  {/* App Logo */}
                  <ImageUploadCard
                    label="App Logo"
                    description="Main logo displayed in the header & sidebar (recommended: 512x512px, PNG/SVG)"
                    settingKey="appLogoUrl"
                    currentUrl={settings.appLogoUrl}
                    category="logo"
                    previewClassName="h-28"
                    onUploadSuccess={handleUploadSuccess}
                    adminToken={adminToken}
                  />

                  {/* Favicon */}
                  <ImageUploadCard
                    label="Favicon"
                    description="Browser tab icon (recommended: 32x32 or 64x64px, ICO/PNG/SVG)"
                    settingKey="faviconUrl"
                    currentUrl={settings.faviconUrl}
                    category="favicon"
                    previewClassName="h-28"
                    onUploadSuccess={handleUploadSuccess}
                    adminToken={adminToken}
                  />

                  {/* Splash Logo */}
                  <ImageUploadCard
                    label="Splash Screen Logo"
                    description="Logo shown on the loading/splash screen (recommended: 1024x1024px, PNG)"
                    settingKey="splashLogoUrl"
                    currentUrl={settings.splashLogoUrl}
                    category="splash"
                    previewClassName="h-28"
                    onUploadSuccess={handleUploadSuccess}
                    adminToken={adminToken}
                  />

                  {/* OG Image */}
                  <ImageUploadCard
                    label="OG / Social Share Image"
                    description="Image shown when sharing links on Facebook, Twitter, etc. (recommended: 1200x630px, PNG/JPG)"
                    settingKey="ogImage"
                    currentUrl={settings.ogImage}
                    category="og"
                    previewClassName="h-28"
                    onUploadSuccess={handleUploadSuccess}
                    adminToken={adminToken}
                  />
                </div>

                {/* Live Preview */}
                <div className="mt-4 rounded-xl border bg-white dark:bg-slate-900 p-4">
                  <p className="text-xs font-medium mb-3">Live Preview</p>
                  <div className="flex items-center gap-4">
                    {/* Header Preview */}
                    <div className="flex items-center gap-2 rounded-lg border bg-slate-50 px-3 py-2 dark:bg-slate-800">
                      {settings.appLogoUrl ? (
                        <img
                          src={settings.appLogoUrl}
                          alt="Logo Preview"
                          className="h-8 w-8 rounded object-cover"
                          onError={(e) => {
                            (e.target as HTMLImageElement).src = '/logo-needyfy.png';
                          }}
                        />
                      ) : (
                        <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-orange-500 text-white text-xs font-bold">
                          {settings.logoText?.charAt(0) || 'N'}
                        </div>
                      )}
                      <span className="text-sm font-semibold">{settings.appName || 'Needyfy'}</span>
                    </div>
                    {/* Favicon Preview */}
                    <div className="flex items-center gap-2">
                      <span className="text-[10px] text-muted-foreground">Tab:</span>
                      {settings.faviconUrl ? (
                        <img
                          src={settings.faviconUrl}
                          alt="Favicon Preview"
                          className="h-4 w-4"
                          onError={(e) => {
                            (e.target as HTMLImageElement).style.display = 'none';
                          }}
                        />
                      ) : (
                        <div className="h-4 w-4 rounded-sm bg-orange-500 flex items-center justify-center text-white text-[8px] font-bold">N</div>
                      )}
                      <span className="text-[10px] text-muted-foreground">{settings.appName || 'Needyfy'}</span>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          )}

          {/* ============ APPEARANCE ============ */}
          {activeSection === 'appearance' && (
            <Card className="border-0 shadow-sm">
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-sm">
                  <Paintbrush className="h-4 w-4 text-orange-500" />Appearance
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-3 gap-4">
                  <div className="space-y-1.5">
                    <Label className="text-xs font-medium">Primary Color</Label>
                    <div className="flex gap-2">
                      <input type="color" value={settings.primaryColor} onChange={(e) => update('primaryColor', e.target.value)} className="h-9 w-12 rounded border cursor-pointer" />
                      <Input value={settings.primaryColor} onChange={(e) => update('primaryColor', e.target.value)} className="flex-1" />
                    </div>
                  </div>
                  <div className="space-y-1.5">
                    <Label className="text-xs font-medium">Accent Color</Label>
                    <div className="flex gap-2">
                      <input type="color" value={settings.accentColor} onChange={(e) => update('accentColor', e.target.value)} className="h-9 w-12 rounded border cursor-pointer" />
                      <Input value={settings.accentColor} onChange={(e) => update('accentColor', e.target.value)} className="flex-1" />
                    </div>
                  </div>
                  <div className="space-y-1.5">
                    <Label className="text-xs font-medium">Background Color</Label>
                    <div className="flex gap-2">
                      <input type="color" value={settings.backgroundColor} onChange={(e) => update('backgroundColor', e.target.value)} className="h-9 w-12 rounded border cursor-pointer" />
                      <Input value={settings.backgroundColor} onChange={(e) => update('backgroundColor', e.target.value)} className="flex-1" />
                    </div>
                  </div>
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <Label className="text-xs font-medium">Font Family</Label>
                    <select value={settings.fontFamily} onChange={(e) => update('fontFamily', e.target.value)} className="w-full rounded-lg border bg-background px-3 py-2 text-sm">
                      <option value="Inter">Inter</option>
                      <option value="Poppins">Poppins</option>
                      <option value="Noto Sans Bengali">Noto Sans Bengali</option>
                      <option value="Hind Siliguri">Hind Siliguri</option>
                    </select>
                  </div>
                  <div className="space-y-1.5">
                    <Label className="text-xs font-medium">Border Radius</Label>
                    <select value={settings.borderRadius} onChange={(e) => update('borderRadius', e.target.value)} className="w-full rounded-lg border bg-background px-3 py-2 text-sm">
                      <option value="0">None (0px)</option>
                      <option value="6">Small (6px)</option>
                      <option value="8">Medium (8px)</option>
                      <option value="12">Large (12px)</option>
                      <option value="16">Extra Large (16px)</option>
                      <option value="9999">Full (Pill)</option>
                    </select>
                  </div>
                </div>
                <div className="space-y-3 pt-2">
                  <div className="flex items-center justify-between">
                    <div>
                      <Label className="text-sm font-medium">Dark Mode</Label>
                      <p className="text-xs text-muted-foreground">Enable dark mode by default</p>
                    </div>
                    <Switch checked={settings.darkMode} onCheckedChange={(v) => update('darkMode', v)} />
                  </div>
                  <div className="flex items-center justify-between">
                    <div>
                      <Label className="text-sm font-medium">RTL Support</Label>
                      <p className="text-xs text-muted-foreground">Right-to-left layout for Bengali</p>
                    </div>
                    <Switch checked={settings.rtl} onCheckedChange={(v) => update('rtl', v)} />
                  </div>
                </div>
                <Card className="bg-slate-50 dark:bg-slate-800/50">
                  <CardContent className="p-4">
                    <p className="text-xs font-medium mb-3">Preview</p>
                    <div className="flex items-center gap-3">
                      <div className="h-10 w-10 rounded-lg flex items-center justify-center text-white text-xs font-bold" style={{ backgroundColor: settings.primaryColor, borderRadius: `${settings.borderRadius}px` }}>N</div>
                      <div className="h-8 w-24 rounded-lg" style={{ backgroundColor: settings.accentColor, borderRadius: `${settings.borderRadius}px` }} />
                      <div className="h-6 w-16 rounded border-2" style={{ borderColor: settings.primaryColor, borderRadius: `${settings.borderRadius}px` }} />
                    </div>
                  </CardContent>
                </Card>
              </CardContent>
            </Card>
          )}

          {/* ============ FEATURES ============ */}
          {activeSection === 'features' && (
            <Card className="border-0 shadow-sm">
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-sm">
                  <Monitor className="h-4 w-4 text-orange-500" />Feature Modules
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                {[
                  { key: 'enableHouses' as const, label: 'House Rental', desc: 'House listing and rental management' },
                  { key: 'enableShops' as const, label: 'Shop Rental', desc: 'Shop listing and rental management' },
                  { key: 'enableProducts' as const, label: 'Product Marketplace', desc: 'Product buying and selling' },
                  { key: 'enableMCQ' as const, label: 'MCQ Education', desc: 'Educational quiz system' },
                  { key: 'enableCommunity' as const, label: 'Community', desc: 'Community posts and discussions' },
                  { key: 'enableChat' as const, label: 'Live Chat', desc: 'Real-time messaging between users' },
                ].map((f) => (
                  <div key={f.key} className="flex items-center justify-between rounded-xl bg-slate-50 p-4 dark:bg-slate-800/50">
                    <div>
                      <Label className="text-sm font-medium">{f.label}</Label>
                      <p className="text-xs text-muted-foreground">{f.desc}</p>
                    </div>
                    <Switch checked={settings[f.key]} onCheckedChange={(v) => update(f.key, v)} />
                  </div>
                ))}
              </CardContent>
            </Card>
          )}

          {/* ============ AUTH & SECURITY ============ */}
          {activeSection === 'auth' && (
            <Card className="border-0 shadow-sm">
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-sm">
                  <Shield className="h-4 w-4 text-orange-500" />Auth & Security
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="flex items-center justify-between rounded-xl bg-slate-50 p-4 dark:bg-slate-800/50">
                  <div>
                    <Label className="text-sm font-medium">Maintenance Mode</Label>
                    <p className="text-xs text-muted-foreground">Show maintenance page to all users</p>
                  </div>
                  <Switch checked={settings.maintenanceMode} onCheckedChange={(v) => update('maintenanceMode', v)} />
                </div>
                <div className="flex items-center justify-between rounded-xl bg-slate-50 p-4 dark:bg-slate-800/50">
                  <div>
                    <Label className="text-sm font-medium">Open Registration</Label>
                    <p className="text-xs text-muted-foreground">Allow new users to sign up</p>
                  </div>
                  <Switch checked={settings.registrationOpen} onCheckedChange={(v) => update('registrationOpen', v)} />
                </div>
                <div className="flex items-center justify-between rounded-xl bg-slate-50 p-4 dark:bg-slate-800/50">
                  <div>
                    <Label className="text-sm font-medium">Email Verification</Label>
                    <p className="text-xs text-muted-foreground">Require email verification on signup</p>
                  </div>
                  <Switch checked={settings.emailVerification} onCheckedChange={(v) => update('emailVerification', v)} />
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs font-medium">Max Upload Size (MB)</Label>
                  <Input type="number" value={settings.maxUploadSize} onChange={(e) => update('maxUploadSize', e.target.value)} />
                </div>
              </CardContent>
            </Card>
          )}

          {/* ============ SEO & META ============ */}
          {activeSection === 'seo' && (
            <Card className="border-0 shadow-sm">
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-sm">
                  <Globe className="h-4 w-4 text-orange-500" />SEO & Meta
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-1.5">
                  <Label className="text-xs font-medium">SEO Title</Label>
                  <Input value={settings.seoTitle} onChange={(e) => update('seoTitle', e.target.value)} />
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs font-medium">SEO Description</Label>
                  <Input value={settings.seoDescription} onChange={(e) => update('seoDescription', e.target.value)} />
                </div>
                <div className="space-y-1.5">
                  <Label className="text-xs font-medium">Google Analytics ID</Label>
                  <Input value={settings.googleAnalyticsId} onChange={(e) => update('googleAnalyticsId', e.target.value)} placeholder="G-XXXXXXXXXX" />
                </div>
              </CardContent>
            </Card>
          )}

          {/* ============ NOTIFICATIONS ============ */}
          {activeSection === 'notifications' && (
            <Card className="border-0 shadow-sm">
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-sm">
                  <Bell className="h-4 w-4 text-orange-500" />Notifications
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                {[
                  { key: 'notificationEmail' as const, label: 'Email Notifications', desc: 'Send notifications via email' },
                  { key: 'notificationPush' as const, label: 'Push Notifications', desc: 'Browser push notifications' },
                  { key: 'notificationSMS' as const, label: 'SMS Notifications', desc: 'SMS alerts (requires gateway)' },
                ].map((n) => (
                  <div key={n.key} className="flex items-center justify-between rounded-xl bg-slate-50 p-4 dark:bg-slate-800/50">
                    <div>
                      <Label className="text-sm font-medium">{n.label}</Label>
                      <p className="text-xs text-muted-foreground">{n.desc}</p>
                    </div>
                    <Switch checked={settings[n.key]} onCheckedChange={(v) => update(n.key, v)} />
                  </div>
                ))}
              </CardContent>
            </Card>
          )}

          {/* ============ ADVANCED ============ */}
          {activeSection === 'advanced' && (
            <Card className="border-0 shadow-sm">
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-sm">
                  <Database className="h-4 w-4 text-orange-500" />Advanced
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="rounded-xl border border-amber-200 bg-amber-50 p-4 dark:border-amber-900/50 dark:bg-amber-950/20">
                  <p className="text-xs font-medium text-amber-700 dark:text-amber-400">⚠️ Advanced settings can affect app stability. Proceed with caution.</p>
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <Card className="bg-slate-50 dark:bg-slate-800/50">
                    <CardContent className="p-4">
                      <p className="text-xs font-medium">Database</p>
                      <Badge variant="outline" className="mt-1 text-[10px]">SQLite</Badge>
                      <p className="mt-2 text-[10px] text-muted-foreground">Using Prisma ORM with SQLite</p>
                    </CardContent>
                  </Card>
                  <Card className="bg-slate-50 dark:bg-slate-800/50">
                    <CardContent className="p-4">
                      <p className="text-xs font-medium">Framework</p>
                      <Badge variant="outline" className="mt-1 text-[10px]">Next.js 16</Badge>
                      <p className="mt-2 text-[10px] text-muted-foreground">App Router + Turbopack</p>
                    </CardContent>
                  </Card>
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <Card className="bg-slate-50 dark:bg-slate-800/50">
                    <CardContent className="p-4">
                      <p className="text-xs font-medium">API Routes</p>
                      <Badge variant="outline" className="mt-1 text-[10px]">14 Active</Badge>
                      <p className="mt-2 text-[10px] text-muted-foreground">All admin APIs running</p>
                    </CardContent>
                  </Card>
                  <Card className="bg-slate-50 dark:bg-slate-800/50">
                    <CardContent className="p-4">
                      <p className="text-xs font-medium">Cache</p>
                      <Badge variant="outline" className="mt-1 text-[10px]">Memory</Badge>
                      <p className="mt-2 text-[10px] text-muted-foreground">In-memory caching active</p>
                    </CardContent>
                  </Card>
                </div>
              </CardContent>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}
