import { useState, useEffect, useMemo } from 'react';
import { AdminLayout } from '@/components/admin/AdminLayout';
import { AdminPageHeader } from '@/components/admin/AdminPageHeader';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { ImagePickerField } from '@/components/admin/ImagePickerField';
import { useBrandingSettings, useUpdateBrandingSettings, useGeneralSettings, useUpdateGeneralSettings, type BrandingSettings } from '@/hooks/useSiteSettings';
import { AVAILABLE_HEADING_FONTS, AVAILABLE_BODY_FONTS } from '@/providers/BrandingProvider';
import { BrandGuideDialog } from '@/components/admin/BrandGuideDialog';
import { Loader2, Palette, Type, Image, LayoutGrid, Sparkles, Globe, Trash2, CheckCircle, XCircle, AlertCircle, RotateCcw } from 'lucide-react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { useUnsavedChanges, UnsavedChangesDialog } from '@/hooks/useUnsavedChanges';
import type { Json } from '@/integrations/supabase/types';
import { STARTER_TEMPLATES } from '@/data/templates';

interface CustomTheme {
  id: string;
  name: string;
  settings: Partial<BrandingSettings>;
};

export function BrandingSettingsContent({ embedded = false }: { embedded?: boolean }) {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const { data: savedSettings, isLoading } = useBrandingSettings();
  const { data: generalSettings } = useGeneralSettings();
  const updateSettings = useUpdateBrandingSettings();
  const updateGeneral = useUpdateGeneralSettings();
  const [settings, setSettings] = useState<BrandingSettings>({});
  const [brandGuideOpen, setBrandGuideOpen] = useState(false);

  // Get current template
  const currentTemplate = useMemo(() => {
    const selectedTemplateId = generalSettings?.selectedTemplate;
    if (!selectedTemplateId || selectedTemplateId === 'custom') return null;
    return STARTER_TEMPLATES.find(t => t.id === selectedTemplateId);
  }, [generalSettings?.selectedTemplate]);

  // Check if branding is custom (differs from template defaults)
  const isCustomBranding = useMemo(() => {
    if (!currentTemplate || !savedSettings) return false;
    const templateBranding = currentTemplate.branding;
    const currentBranding = savedSettings;
    
    // Compare key branding properties
    const keysToCompare = ['primaryColor', 'secondaryColor', 'accentColor', 'headingFont', 'bodyFont', 'borderRadius', 'shadowIntensity'] as const;
    
    return keysToCompare.some(key => {
      const templateValue = templateBranding[key];
      const currentValue = currentBranding[key];
      return templateValue !== currentValue;
    });
  }, [currentTemplate, savedSettings]);

  // Fetch custom themes
  const { data: customThemes = [] } = useQuery({
    queryKey: ['site-settings', 'custom_themes'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('site_settings')
        .select('value')
        .eq('key', 'custom_themes')
        .maybeSingle();
      if (error) throw error;
      return (data?.value as unknown as CustomTheme[]) || [];
    },
  });

  // Save custom themes mutation
  const saveCustomThemes = useMutation({
    mutationFn: async (themes: CustomTheme[]) => {
      const { data: existing } = await supabase
        .from('site_settings')
        .select('id')
        .eq('key', 'custom_themes')
        .maybeSingle();

      const jsonValue = themes as unknown as Json;

      if (existing) {
        const { error } = await supabase
          .from('site_settings')
          .update({ value: jsonValue, updated_at: new Date().toISOString() })
          .eq('key', 'custom_themes');
        if (error) throw error;
      } else {
        const { error } = await supabase
          .from('site_settings')
          .insert({ key: 'custom_themes', value: jsonValue });
        if (error) throw error;
      }
      return themes;
    },
    onSuccess: (themes) => {
      queryClient.setQueryData(['site-settings', 'custom_themes'], themes);
    },
  });

  useEffect(() => {
    if (savedSettings) {
      setSettings(savedSettings);
    }
  }, [savedSettings]);

  // Track unsaved changes
  const hasChanges = useMemo(() => {
    if (!savedSettings) return false;
    return JSON.stringify(settings) !== JSON.stringify(savedSettings);
  }, [settings, savedSettings]);

  const { blocker } = useUnsavedChanges({ hasChanges });

  const handleSave = () => {
    updateSettings.mutate(settings);
  };

  const updateField = <K extends keyof BrandingSettings>(field: K, value: BrandingSettings[K]) => {
    setSettings((prev) => ({ ...prev, [field]: value }));
  };

  // Convert HSL string to hex for color picker
  const hslToHex = (hsl: string): string => {
    if (!hsl) return '#003087';
    const [h, s, l] = hsl.split(' ').map((v) => parseFloat(v));
    const sDecimal = s / 100;
    const lDecimal = l / 100;
    const c = (1 - Math.abs(2 * lDecimal - 1)) * sDecimal;
    const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
    const m = lDecimal - c / 2;
    let r = 0, g = 0, b = 0;
    if (h < 60) { r = c; g = x; }
    else if (h < 120) { r = x; g = c; }
    else if (h < 180) { g = c; b = x; }
    else if (h < 240) { g = x; b = c; }
    else if (h < 300) { r = x; b = c; }
    else { r = c; b = x; }
    const toHex = (n: number) => Math.round((n + m) * 255).toString(16).padStart(2, '0');
    return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
  };

  // Convert hex to HSL string
  const hexToHsl = (hex: string): string => {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    if (!result) return '220 100% 26%';
    let r = parseInt(result[1], 16) / 255;
    let g = parseInt(result[2], 16) / 255;
    let b = parseInt(result[3], 16) / 255;
    const max = Math.max(r, g, b), min = Math.min(r, g, b);
    let h = 0, s = 0;
    const l = (max + min) / 2;
    if (max !== min) {
      const d = max - min;
      s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
      switch (max) {
        case r: h = ((g - b) / d + (g < b ? 6 : 0)) * 60; break;
        case g: h = ((b - r) / d + 2) * 60; break;
        case b: h = ((r - g) / d + 4) * 60; break;
      }
    }
    return `${Math.round(h)} ${Math.round(s * 100)}% ${Math.round(l * 100)}%`;
  };

  // Calculate luminance from HSL for contrast calculation
  const getLuminance = (hsl: string): number => {
    const [h, s, l] = hsl.split(' ').map((v) => parseFloat(v));
    const sDecimal = s / 100;
    const lDecimal = l / 100;
    const c = (1 - Math.abs(2 * lDecimal - 1)) * sDecimal;
    const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
    const m = lDecimal - c / 2;
    let r = 0, g = 0, b = 0;
    if (h < 60) { r = c; g = x; }
    else if (h < 120) { r = x; g = c; }
    else if (h < 180) { g = c; b = x; }
    else if (h < 240) { g = x; b = c; }
    else if (h < 300) { r = x; b = c; }
    else { r = c; b = x; }
    const toLinear = (n: number) => {
      const n2 = n + m;
      return n2 <= 0.03928 ? n2 / 12.92 : Math.pow((n2 + 0.055) / 1.055, 2.4);
    };
    return 0.2126 * toLinear(r) + 0.7152 * toLinear(g) + 0.0722 * toLinear(b);
  };

  // Calculate WCAG contrast ratio
  const getContrastRatio = (hsl1: string, hsl2: string): number => {
    const lum1 = getLuminance(hsl1);
    const lum2 = getLuminance(hsl2);
    const lighter = Math.max(lum1, lum2);
    const darker = Math.min(lum1, lum2);
    return (lighter + 0.05) / (darker + 0.05);
  };

  // Check WCAG compliance
  const checkContrastCompliance = (ratio: number) => {
    const aaNormal = ratio >= 4.5;
    const aaLarge = ratio >= 3.0;
    const aaaNormal = ratio >= 7.0;
    const aaaLarge = ratio >= 4.5;
    return { aaNormal, aaLarge, aaaNormal, aaaLarge, ratio };
  };

  // Get contrast badge component
  const ContrastBadge = ({ ratio }: { ratio: number }) => {
    const { aaNormal, aaLarge, aaaNormal, aaaLarge } = checkContrastCompliance(ratio);
    return (
      <div className="flex items-center gap-2">
        {aaaNormal ? (
          <div className="flex items-center gap-1 text-xs bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 px-2 py-1 rounded">
            <CheckCircle className="h-3 w-3" />
            <span>AAA</span>
          </div>
        ) : aaNormal ? (
          <div className="flex items-center gap-1 text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 px-2 py-1 rounded">
            <CheckCircle className="h-3 w-3" />
            <span>AA</span>
          </div>
        ) : (
          <div className="flex items-center gap-1 text-xs bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400 px-2 py-1 rounded">
            <AlertCircle className="h-3 w-3" />
            <span>Fail</span>
          </div>
        )}
        <span className="text-xs text-muted-foreground">{ratio.toFixed(2)}:1</span>
      </div>
    );
  };

  const applyCustomTheme = (theme: CustomTheme) => {
    setSettings((prev) => ({
      ...prev,
      ...theme.settings,
    }));
  };

  const handleApplyBranding = (brandingSettings: Partial<BrandingSettings>) => {
    setSettings((prev) => ({
      ...prev,
      ...brandingSettings,
    }));
  };

  // Reset to template defaults
  const handleResetToTemplateDefaults = () => {
    if (currentTemplate) {
      setSettings(currentTemplate.branding as BrandingSettings);
      toast({
        title: 'Reset to Template Defaults',
        description: `Branding reset to ${currentTemplate.name} defaults`,
      });
    }
  };

  const handleSaveAsTheme = (name: string, themeSettings: Partial<BrandingSettings>) => {
    const newTheme: CustomTheme = {
      id: `custom-${Date.now()}`,
      name,
      settings: themeSettings,
    };
    saveCustomThemes.mutate([...customThemes, newTheme]);
  };

  const handleDeleteCustomTheme = (themeId: string) => {
    const updated = customThemes.filter((t) => t.id !== themeId);
    saveCustomThemes.mutate(updated);
    toast({
      title: 'Theme removed',
      description: 'The custom theme has been removed.',
    });
  };

  // Convert HSL to hex for theme preview
  const getThemePreviewColors = (themeSettings: Partial<BrandingSettings>) => ({
    primary: hslToHex(themeSettings.primaryColor || '220 100% 26%'),
    secondary: hslToHex(themeSettings.secondaryColor || '210 40% 96%'),
    accent: hslToHex(themeSettings.accentColor || '199 89% 48%'),
  });

  if (isLoading) {
    const loader = (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
    return embedded ? loader : <AdminLayout>{loader}</AdminLayout>;
  }

  const content = (
    <div className="space-y-6">
      {!embedded && (
        <AdminPageHeader 
          title="Branding & Design"
          description="Customize the appearance of the public website"
        >
          <Button onClick={handleSave} disabled={updateSettings.isPending} className="relative">
            {hasChanges && <span className="absolute -top-1 -right-1 h-3 w-3 rounded-full bg-destructive" />}
            {updateSettings.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
            Save changes
          </Button>
        </AdminPageHeader>
      )}
      {embedded && (
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle className="font-serif">Branding & Design</CardTitle>
                <CardDescription>Customize the appearance of the public website</CardDescription>
              </div>
              <Button onClick={handleSave} disabled={updateSettings.isPending} size="sm" className="relative">
                {hasChanges && <span className="absolute -top-1 -right-1 h-3 w-3 rounded-full bg-destructive" />}
                {updateSettings.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
                Save changes
              </Button>
            </div>
          </CardHeader>
        </Card>
      )}

        {/* Current Template Indicator */}
        <div className="flex items-center justify-between p-4 bg-muted/50 rounded-lg border">
          <div className="flex items-center gap-3">
            <div>
              <p className="text-sm text-muted-foreground">Current Template</p>
              {currentTemplate ? (
                <p className="text-lg font-semibold">{currentTemplate.name}</p>
              ) : generalSettings?.selectedTemplate === 'custom' ? (
                <p className="text-lg font-semibold">Custom</p>
              ) : (
                <div className="flex items-center gap-2">
                  <p className="text-lg font-semibold text-muted-foreground">Not set</p>
                  <Select
                    value=""
                    onValueChange={(value) => {
                      updateGeneral.mutateAsync({ 
                        homepageSlug: generalSettings?.homepageSlug || 'home',
                        selectedTemplate: value 
                      });
                    }}
                  >
                    <SelectTrigger className="w-48 h-8">
                      <SelectValue placeholder="Select template..." />
                    </SelectTrigger>
                    <SelectContent>
                      {STARTER_TEMPLATES.map((t) => (
                        <SelectItem key={t.id} value={t.id}>{t.name}</SelectItem>
                      ))}
                      <SelectItem value="custom">Custom (built from scratch)</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              )}
            </div>
            {currentTemplate && isCustomBranding && (
              <Badge variant="secondary" className="ml-2">Custom</Badge>
            )}
          </div>
          {currentTemplate && isCustomBranding && (
            <Button 
              onClick={handleResetToTemplateDefaults} 
              variant="outline" 
              size="sm"
              className="gap-2"
            >
              <RotateCcw className="h-4 w-4" />
              Reset to Template Defaults
            </Button>
          )}
        </div>

        <Tabs defaultValue="themes" className="space-y-6">
          <TabsList className="grid w-full grid-cols-5 max-w-2xl">
            <TabsTrigger value="themes" className="flex items-center gap-2">
              <Sparkles className="h-4 w-4" />
              <span className="hidden sm:inline">Themes</span>
            </TabsTrigger>
            <TabsTrigger value="identity" className="flex items-center gap-2">
              <Image className="h-4 w-4" />
              <span className="hidden sm:inline">Identity</span>
            </TabsTrigger>
            <TabsTrigger value="colors" className="flex items-center gap-2">
              <Palette className="h-4 w-4" />
              <span className="hidden sm:inline">Colors</span>
            </TabsTrigger>
            <TabsTrigger value="typography" className="flex items-center gap-2">
              <Type className="h-4 w-4" />
              <span className="hidden sm:inline">Typography</span>
            </TabsTrigger>
            <TabsTrigger value="appearance" className="flex items-center gap-2">
              <LayoutGrid className="h-4 w-4" />
              <span className="hidden sm:inline">Appearance</span>
            </TabsTrigger>
          </TabsList>

          {/* Themes */}
          <TabsContent value="themes">
            <div className="space-y-6">
              {/* Brand Guide Assistant */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Globe className="h-5 w-5" />
                    Brand Guide Assistant
                  </CardTitle>
                  <CardDescription>
                    Analyze an existing website and extract its brand profile automatically
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <Button onClick={() => setBrandGuideOpen(true)} variant="outline">
                    <Sparkles className="h-4 w-4 mr-2" />
                    Analyze existing website
                  </Button>
                </CardContent>
              </Card>

              {/* Custom Themes */}
              {customThemes.length > 0 && (
                <Card>
                  <CardHeader>
                    <CardTitle>Custom Themes</CardTitle>
                    <CardDescription>Themes you have saved from Brand Guide Assistant</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      {customThemes.map((theme) => {
                        const colors = getThemePreviewColors(theme.settings);
                        return (
                          <div
                            key={theme.id}
                            className="relative p-4 rounded-lg border-2 hover:border-primary/50 transition-all group"
                          >
                            <button
                              onClick={() => applyCustomTheme(theme)}
                              className="text-left w-full"
                            >
                              <div className="flex items-start gap-4">
                                <div className="flex flex-col gap-1">
                                  <div
                                    className="h-8 w-8 rounded-md"
                                    style={{ backgroundColor: colors.primary }}
                                  />
                                  <div className="flex gap-1">
                                    <div
                                      className="h-3 w-3 rounded-sm"
                                      style={{ backgroundColor: colors.secondary }}
                                    />
                                    <div
                                      className="h-3 w-3 rounded-sm"
                                      style={{ backgroundColor: colors.accent }}
                                    />
                                  </div>
                                </div>
                                <div className="flex-1">
                                  <h3 className="font-semibold group-hover:text-primary transition-colors">
                                    {theme.name}
                                  </h3>
                                  <div className="flex gap-2 mt-2">
                                    {theme.settings.headingFont && (
                                      <span className="text-xs bg-muted px-2 py-0.5 rounded">
                                        {theme.settings.headingFont}
                                      </span>
                                    )}
                                  </div>
                                </div>
                              </div>
                            </button>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="absolute top-2 right-2 h-8 w-8 opacity-0 group-hover:opacity-100 transition-opacity"
                              onClick={() => handleDeleteCustomTheme(theme.id)}
                            >
                              <Trash2 className="h-4 w-4 text-muted-foreground hover:text-destructive" />
                            </Button>
                          </div>
                        );
                      })}
                    </div>
                  </CardContent>
                </Card>
              )}

            </div>
          </TabsContent>

          {/* Identity */}
          <TabsContent value="identity">
            <div className="space-y-6">
              <Card>
                <CardHeader>
                  <CardTitle>Identity</CardTitle>
                  <CardDescription>Logo and organization name displayed on the website</CardDescription>
                </CardHeader>
                <CardContent className="space-y-6">
                  <div className="space-y-2">
                    <Label>Organization name</Label>
                    <Input
                      value={settings.organizationName || ''}
                      onChange={(e) => updateField('organizationName', e.target.value)}
                      placeholder="E.g. Acme Healthcare"
                    />
                  </div>
                  
                  <div className="space-y-2">
                    <Label>Slogan / tagline</Label>
                    <Input
                      value={settings.brandTagline || ''}
                      onChange={(e) => updateField('brandTagline', e.target.value)}
                      placeholder="E.g. Quality care with the patient in focus"
                    />
                    <p className="text-xs text-muted-foreground">Displayed in the footer below the organization name</p>
                  </div>
                  
                  <div className="space-y-2">
                    <Label>Admin panel name</Label>
                    <Input
                      value={settings.adminName || 'FlowWink'}
                      onChange={(e) => updateField('adminName', e.target.value)}
                      placeholder="E.g. My CMS"
                    />
                    <p className="text-xs text-muted-foreground">Displayed in the admin sidebar header</p>
                  </div>
                  
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="space-y-2">
                      <Label>Logo (light background)</Label>
                      <ImagePickerField
                        value={settings.logo || ''}
                        onChange={(url) => updateField('logo', url)}
                        placeholder="Logo URL"
                      />
                      <p className="text-xs text-muted-foreground">Recommended size: 200x60px</p>
                    </div>
                    
                    <div className="space-y-2">
                      <Label>Logo (dark background)</Label>
                      <ImagePickerField
                        value={settings.logoDark || ''}
                        onChange={(url) => updateField('logoDark', url)}
                        placeholder="Logo URL (dark)"
                      />
                      <p className="text-xs text-muted-foreground">Used in footer and dark mode</p>
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label>Favicon</Label>
                    <ImagePickerField
                      value={settings.favicon || ''}
                      onChange={(url) => updateField('favicon', url)}
                      placeholder="Favicon URL"
                    />
                    <p className="text-xs text-muted-foreground">Small icon shown in browser tab (32x32px)</p>
                  </div>
                </CardContent>
              </Card>

              {/* Header Display Settings */}
              <Card>
                <CardHeader>
                  <CardTitle>Header Display</CardTitle>
                  <CardDescription>Control how logo and name appear in the public header</CardDescription>
                </CardHeader>
                <CardContent className="space-y-6">
                  <div className="space-y-4">
                    <div className="flex items-center justify-between">
                      <div className="space-y-0.5">
                        <Label>Show logo in header</Label>
                        <p className="text-xs text-muted-foreground">Displays the logo if one is uploaded</p>
                      </div>
                      <input
                        type="checkbox"
                        checked={settings.showLogoInHeader !== false}
                        onChange={(e) => updateField('showLogoInHeader', e.target.checked)}
                        className="h-4 w-4 rounded border-input"
                      />
                    </div>
                    
                    <div className="flex items-center justify-between">
                      <div className="space-y-0.5">
                        <Label>Show organization name next to logo</Label>
                        <p className="text-xs text-muted-foreground">Shows the name even when the logo is displayed</p>
                      </div>
                      <input
                        type="checkbox"
                        checked={settings.showNameWithLogo === true}
                        onChange={(e) => updateField('showNameWithLogo', e.target.checked)}
                        className="h-4 w-4 rounded border-input"
                      />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label>Logo size</Label>
                    <Select
                      value={settings.headerLogoSize || 'md'}
                      onValueChange={(value) => updateField('headerLogoSize', value as 'sm' | 'md' | 'lg')}
                    >
                      <SelectTrigger className="w-48">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="sm">Small</SelectItem>
                        <SelectItem value="md">Medium</SelectItem>
                        <SelectItem value="lg">Large</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  {/* Preview */}
                  <div className="space-y-2">
                    <Label className="text-muted-foreground">Preview</Label>
                    <div className="border rounded-lg p-4 bg-card">
                      <div className="flex items-center gap-3">
                        {(() => {
                          const showLogo = settings.showLogoInHeader !== false;
                          const showName = settings.showNameWithLogo === true;
                          const logoSize = settings.headerLogoSize || 'md';
                          const hasLogo = !!settings.logo;
                          const orgName = settings.organizationName || 'Organization';
                          
                          const sizeClasses = {
                            sm: 'h-8 max-w-[160px]',
                            md: 'h-10 max-w-[200px]',
                            lg: 'h-12 max-w-[240px]',
                          };
                          
                          const iconSizes = {
                            sm: 'h-8 w-8 text-lg',
                            md: 'h-10 w-10 text-xl',
                            lg: 'h-12 w-12 text-2xl',
                          };

                          if (showLogo && hasLogo) {
                            return (
                              <>
                                <img 
                                  src={settings.logo} 
                                  alt={orgName} 
                                  className={`${sizeClasses[logoSize]} object-contain`}
                                />
                                {showName && (
                                  <span className="font-serif font-bold text-xl">{orgName}</span>
                                )}
                              </>
                            );
                          }
                          
                          return (
                            <>
                              <div className={`rounded-lg bg-primary flex items-center justify-center ${iconSizes[logoSize]}`}>
                                <span className="text-primary-foreground font-serif font-bold">
                                  {orgName.charAt(0)}
                                </span>
                              </div>
                              <span className="font-serif font-bold text-xl">{orgName}</span>
                            </>
                          );
                        })()}
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>
          </TabsContent>

          {/* Colors */}
          <TabsContent value="colors">
            <Card>
              <CardHeader>
                <CardTitle>Color Palette</CardTitle>
                <CardDescription>Choose colors that represent your brand</CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                  <div className="space-y-3">
                    <Label>Primary Color</Label>
                    <div className="flex items-center gap-3">
                      <input
                        type="color"
                        value={hslToHex(settings.primaryColor || '220 100% 26%')}
                        onChange={(e) => updateField('primaryColor', hexToHsl(e.target.value))}
                        className="h-12 w-12 rounded-lg border cursor-pointer"
                      />
                      <div className="flex-1">
                        <p className="text-sm font-medium">Main color</p>
                        <p className="text-xs text-muted-foreground">Buttons, links, header</p>
                      </div>
                    </div>
                    {/* Contrast: white text on primary background */}
                    <div className="text-xs text-muted-foreground">vs white text</div>
                    <ContrastBadge ratio={getContrastRatio(settings.primaryColor || '220 100% 26%', '0 0% 100%')} />
                  </div>
                  
                  <div className="space-y-3">
                    <Label>Secondary Color</Label>
                    <div className="flex items-center gap-3">
                      <input
                        type="color"
                        value={hslToHex(settings.secondaryColor || '210 40% 96%')}
                        onChange={(e) => updateField('secondaryColor', hexToHsl(e.target.value))}
                        className="h-12 w-12 rounded-lg border cursor-pointer"
                      />
                      <div className="flex-1">
                        <p className="text-sm font-medium">Background color</p>
                        <p className="text-xs text-muted-foreground">Sections, cards</p>
                      </div>
                    </div>
                    {/* Contrast: dark text on secondary background */}
                    <div className="text-xs text-muted-foreground">vs dark text</div>
                    <ContrastBadge ratio={getContrastRatio(settings.secondaryColor || '210 40% 96%', '0 0% 10%')} />
                  </div>
                  
                  <div className="space-y-3">
                    <Label>Accent Color</Label>
                    <div className="flex items-center gap-3">
                      <input
                        type="color"
                        value={hslToHex(settings.accentColor || '199 89% 48%')}
                        onChange={(e) => updateField('accentColor', hexToHsl(e.target.value))}
                        className="h-12 w-12 rounded-lg border cursor-pointer"
                      />
                      <div className="flex-1">
                        <p className="text-sm font-medium">Highlights</p>
                        <p className="text-xs text-muted-foreground">Hover, focus states</p>
                      </div>
                    </div>
                    {/* Contrast: white text on accent background */}
                    <div className="text-xs text-muted-foreground">vs white text</div>
                    <ContrastBadge ratio={getContrastRatio(settings.accentColor || '199 89% 48%', '0 0% 100%')} />
                  </div>
                </div>

                {/* Preview */}
                <div className="mt-8 p-6 rounded-lg border bg-muted/30">
                  <p className="text-sm font-medium mb-4">Preview</p>
                  <div className="flex flex-wrap gap-3">
                    <div 
                      className="h-16 w-24 rounded-lg flex items-center justify-center text-xs font-medium text-white"
                      style={{ backgroundColor: hslToHex(settings.primaryColor || '220 100% 26%') }}
                    >
                      Primary
                    </div>
                    <div 
                      className="h-16 w-24 rounded-lg flex items-center justify-center text-xs font-medium border"
                      style={{ backgroundColor: hslToHex(settings.secondaryColor || '210 40% 96%') }}
                    >
                      Secondary
                    </div>
                    <div 
                      className="h-16 w-24 rounded-lg flex items-center justify-center text-xs font-medium text-white"
                      style={{ backgroundColor: hslToHex(settings.accentColor || '199 89% 48%') }}
                    >
                      Accent
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Typography */}
          <TabsContent value="typography">
            <Card>
              <CardHeader>
                <CardTitle>Typography</CardTitle>
                <CardDescription>Choose fonts for headings and body text</CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="space-y-2">
                    <Label>Heading font</Label>
                    <Select
                      value={settings.headingFont || 'PT Serif'}
                      onValueChange={(value) => updateField('headingFont', value)}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {AVAILABLE_HEADING_FONTS.map((font) => (
                          <SelectItem key={font} value={font}>
                            {font}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <p className="text-xs text-muted-foreground">Used for H1–H6 and logo</p>
                  </div>
                  
                  <div className="space-y-2">
                    <Label>Body font</Label>
                    <Select
                      value={settings.bodyFont || 'Inter'}
                      onValueChange={(value) => updateField('bodyFont', value)}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {AVAILABLE_BODY_FONTS.map((font) => (
                          <SelectItem key={font} value={font}>
                            {font}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <p className="text-xs text-muted-foreground">Used for body text and buttons</p>
                  </div>
                </div>

                {/* Preview */}
                <div className="mt-8 p-6 rounded-lg border bg-muted/30 space-y-4">
                  <p className="text-sm font-medium mb-4">Preview</p>
                  <h2 
                    className="text-2xl font-bold"
                    style={{ fontFamily: `'${settings.headingFont || 'PT Serif'}', serif` }}
                  >
                    Sample heading with selected font
                  </h2>
                  <p 
                    className="text-base text-muted-foreground"
                    style={{ fontFamily: `'${settings.bodyFont || 'Inter'}', sans-serif` }}
                  >
                    This is sample text that shows how body text will appear on the website. 
                    The choice of font affects readability and the feel of the entire page.
                  </p>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Appearance */}
          <TabsContent value="appearance">
            <div className="space-y-6">
              <Card>
                <CardHeader>
                  <CardTitle>Appearance</CardTitle>
                  <CardDescription>Customize the visual expression</CardDescription>
                </CardHeader>
                <CardContent className="space-y-6">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="space-y-2">
                      <Label>Corner radius</Label>
                      <Select
                        value={settings.borderRadius || 'md'}
                        onValueChange={(value) => updateField('borderRadius', value as BrandingSettings['borderRadius'])}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="none">No rounded corners</SelectItem>
                          <SelectItem value="sm">Subtly rounded</SelectItem>
                          <SelectItem value="md">Medium rounded</SelectItem>
                          <SelectItem value="lg">Heavily rounded</SelectItem>
                        </SelectContent>
                      </Select>
                      <p className="text-xs text-muted-foreground">Affects buttons, cards and images</p>
                    </div>
                    
                    <div className="space-y-2">
                      <Label>Shadows</Label>
                      <Select
                        value={settings.shadowIntensity || 'subtle'}
                        onValueChange={(value) => updateField('shadowIntensity', value as BrandingSettings['shadowIntensity'])}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="none">No shadows</SelectItem>
                          <SelectItem value="subtle">Subtle shadows</SelectItem>
                          <SelectItem value="medium">Visible shadows</SelectItem>
                        </SelectContent>
                      </Select>
                      <p className="text-xs text-muted-foreground">Adds depth and dimension to elements</p>
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label>Hero image overlay</Label>
                    <Select
                      value={settings.heroOverlayOpacity || 'medium'}
                      onValueChange={(value) => updateField('heroOverlayOpacity', value as BrandingSettings['heroOverlayOpacity'])}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="none">No dimming (full image)</SelectItem>
                        <SelectItem value="light">Light dimming</SelectItem>
                        <SelectItem value="medium">Medium dimming (default)</SelectItem>
                        <SelectItem value="strong">Strong dimming</SelectItem>
                      </SelectContent>
                    </Select>
                    <p className="text-xs text-muted-foreground">How much the background image in hero blocks is dimmed by the primary color</p>
                  </div>

                  {/* Preview */}
                  <div className="mt-8 p-6 rounded-lg border bg-muted/30">
                    <p className="text-sm font-medium mb-4">Preview</p>
                    <div className="flex flex-wrap gap-4">
                      {(['none', 'sm', 'md', 'lg'] as const).map((radius) => (
                        <div
                          key={radius}
                          className={`h-20 w-20 bg-card border flex items-center justify-center text-xs ${
                            settings.borderRadius === radius ? 'ring-2 ring-primary' : ''
                          }`}
                          style={{
                            borderRadius: radius === 'none' ? 0 : radius === 'sm' ? 4 : radius === 'md' ? 8 : 12,
                            boxShadow: settings.shadowIntensity === 'none' 
                              ? 'none' 
                              : settings.shadowIntensity === 'subtle' 
                                ? '0 1px 3px rgba(0,0,0,0.1)' 
                                : '0 4px 12px rgba(0,0,0,0.15)'
                          }}
                        >
                          {radius}
                        </div>
                      ))}
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* Theme Toggle Settings */}
              <Card>
                <CardHeader>
                  <CardTitle>Theme Toggle</CardTitle>
                  <CardDescription>Let visitors switch between light and dark themes</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex items-center justify-between">
                    <div className="space-y-0.5">
                      <Label>Show theme toggle</Label>
                      <p className="text-sm text-muted-foreground">
                        Shows a button in the navigation where visitors can switch between light, dark, and system theme
                      </p>
                    </div>
                    <div className="flex items-center gap-2">
                      <span className="text-sm text-muted-foreground">
                        {settings.allowThemeToggle !== false ? 'On' : 'Off'}
                      </span>
                      <Button
                        variant={settings.allowThemeToggle !== false ? 'default' : 'outline'}
                        size="sm"
                        onClick={() => updateField('allowThemeToggle', settings.allowThemeToggle !== false ? false : true)}
                      >
                        {settings.allowThemeToggle !== false ? 'Enabled' : 'Disabled'}
                      </Button>
                    </div>
                  </div>
                  {settings.allowThemeToggle === false && (
                    <div className="space-y-4 bg-muted p-4 rounded-md">
                      <div className="space-y-2">
                        <Label>Default Theme</Label>
                        <Select
                          value={settings.defaultTheme || 'light'}
                          onValueChange={(value) => updateField('defaultTheme', value as BrandingSettings['defaultTheme'])}
                        >
                          <SelectTrigger className="w-48">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="light">Light</SelectItem>
                            <SelectItem value="dark">Dark</SelectItem>
                            <SelectItem value="system">System (follows visitor's OS)</SelectItem>
                          </SelectContent>
                        </Select>
                        <p className="text-sm text-muted-foreground">
                          Visitors will always see this theme when the toggle is disabled.
                        </p>
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>
            </div>
          </TabsContent>
        </Tabs>

        <BrandGuideDialog
          open={brandGuideOpen}
          onOpenChange={setBrandGuideOpen}
          onApplyBranding={handleApplyBranding}
          onSaveAsTheme={handleSaveAsTheme}
        />

        <UnsavedChangesDialog blocker={blocker} />
      </div>
    );

  return embedded ? content : <AdminLayout>{content}</AdminLayout>;
}

export default function BrandingSettingsPage() {
  return <BrandingSettingsContent />;
}
