import React from 'react';
import { cn } from '@/lib/utils';
import { __ } from '@/lib/i18n';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import {
    Accordion,
    AccordionContent,
    AccordionItem,
    AccordionTrigger,
} from '@/components/ui/accordion';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Slider } from '@/components/ui/slider';
import {
    Settings,
    PanelRightClose,
    PanelRight,
    Trash2,
    ExternalLink,
    Palette,
    Type,
    Home
} from 'lucide-react';
import { InspectorField, SectionProp } from './InspectorField';
import { InspectorRepeater } from './InspectorRepeater';
import { MediaUploader } from '@/components/MediaUploader';
import { SectionStyles, ElementStyle, PageItem } from '../store/usePageEditorStore';
import { SECTION_SCHEMAS } from '../schema/sectionSchema';

interface Section {
    id: string;
    type: string;
    layoutVariant?: string;
    colorScheme?: string;
    styles?: SectionStyles;
    elementStyles?: Record<string, ElementStyle>;
    props: Record<string, SectionProp>;
}

interface InspectorPanelProps {
    page: PageItem | null;
    selectedSection: Section | null;
    isCollapsed: boolean;
    isTemplate: boolean;
    availableSources: { value: string; label: string }[];
    onToggleCollapse: () => void;
    onSectionPropChange: (propName: string, value: SectionProp) => void;
    onLayoutChange: (layout: string) => void;
    onColorSchemeChange: (scheme: string) => void;
    onSectionStylesChange: (styles: Partial<SectionStyles>) => void;
    onElementStylesChange: (fieldName: string, styles: Partial<ElementStyle>) => void;
    onDeleteSection: () => void;
    onSetAsSpaLanding?: () => void;
    onUnsetSpaLanding?: () => void;
    onDeletePage?: () => void;
    onDeleteTemplate?: () => void;
    onContainerWidthChange?: (width: 'boxed' | 'fullwidth') => void;
}

const SECTION_FIELDS = Object.fromEntries(
    Object.entries(SECTION_SCHEMAS).map(([type, schema]) => [type, schema.fields])
);

const LAYOUT_OPTIONS = Object.fromEntries(
    Object.entries(SECTION_SCHEMAS)
        .filter(([, schema]) => !!schema.layouts)
        .map(([type, schema]) => [type, schema.layouts || []])
);

const COLOR_SCHEMES = [
    { value: 'default', label: 'Default' },
    { value: 'primary', label: 'Primary' },
    { value: 'secondary', label: 'Secondary' },
    { value: 'muted', label: 'Muted' },
];

const STYLABLE_ELEMENTS = Object.fromEntries(
    Object.entries(SECTION_SCHEMAS).map(([type, schema]) => [type, schema.stylableElements || []])
);

export function InspectorPanel({
    page,
    selectedSection,
    isCollapsed,
    isTemplate,
    availableSources,
    onToggleCollapse,
    onSectionPropChange,
    onLayoutChange,
    onColorSchemeChange,
    onSectionStylesChange,
    onElementStylesChange,
    onDeleteSection,
    onSetAsSpaLanding,
    onUnsetSpaLanding,
    onDeletePage,
    onDeleteTemplate,
    onContainerWidthChange,
}: InspectorPanelProps) {
    if (isCollapsed) {
        return (
            <div className="w-10 border-l bg-white flex flex-col items-center py-4">
                <Button variant="ghost" size="icon" onClick={onToggleCollapse} className="mb-4">
                    <PanelRight className="w-4 h-4" />
                </Button>
            </div>
        );
    }

    if (!selectedSection) {
        return (
            <div className="w-80 border-l bg-white flex flex-col h-full">
                <div className="flex items-center justify-between p-4 border-b shrink-0">
                    <h3 className="font-semibold text-sm">{__('Page Settings')}</h3>
                    <Button variant="ghost" size="icon" onClick={onToggleCollapse} className="h-8 w-8">
                        <PanelRightClose className="w-4 h-4" />
                    </Button>
                </div>
                <div className="p-4 space-y-4 overflow-y-auto">
                    <div className="flex items-center gap-2 text-sm font-medium text-gray-700">
                        <Settings className="w-4 h-4" />
                        {isTemplate ? __('Template Info') : __('Page Info')}
                    </div>
                    <div className="space-y-4 bg-gray-50 p-3 rounded-lg border">
                        <div>
                            <Label className="text-xs text-gray-500 uppercase tracking-wider">{__('Type')}</Label>
                            <p className="text-sm font-medium">
                                {isTemplate ? __('Template (Dynamic)') : __('Page (Structural)')}
                            </p>
                        </div>
                        {page?.title && (
                            <div>
                                <Label className="text-xs text-gray-500 uppercase tracking-wider">{__('Title')}</Label>
                                <p className="text-sm font-medium">{page.title}</p>
                            </div>
                        )}
                        {page?.url && (
                            <div>
                                <Label className="text-xs text-gray-500 uppercase tracking-wider">{__('URL')}</Label>
                                <a href={page.url} target="_blank" rel="noopener noreferrer" className="text-sm text-blue-600 hover:underline flex items-center gap-1 mt-1">
                                    {__('View Page')}
                                    <ExternalLink className="w-3 h-3" />
                                </a>
                            </div>
                        )}

                        {/* SPA Landing Settings - Only for Pages */}
                        {!isTemplate && page && (
                            <div className="pt-2 border-t mt-2">
                                <Label className="text-xs text-gray-500 uppercase tracking-wider block mb-2">{__('SPA Landing Page')}</Label>
                                {page.isSpaLanding ? (
                                    <div className="space-y-2">
                                        <div className="bg-green-50 text-green-700 px-3 py-2 rounded-md text-sm flex items-center gap-2 border border-green-100">
                                            <Home className="w-4 h-4" />
                                            <span className="font-medium">{__('This is your SPA Landing')}</span>
                                        </div>
                                        <Button
                                            variant="outline"
                                            size="sm"
                                            className="w-full text-red-600 hover:text-red-700 hover:bg-red-50 border-red-200"
                                            onClick={onUnsetSpaLanding}
                                        >
                                            <Trash2 className="w-4 h-4 mr-2" />
                                            {__('Unset Landing Page')}
                                        </Button>
                                    </div>
                                ) : (
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        className="w-full justify-start"
                                        onClick={onSetAsSpaLanding}
                                    >
                                        <Home className="w-4 h-4 mr-2" />
                                        {__('Set as SPA Landing')}
                                    </Button>
                                )}
                            </div>
                        )}

                        {/* Container Width */}
                        {!isTemplate && page && onContainerWidthChange && (
                            <div className="pt-2 border-t mt-2">
                                <Label className="text-xs text-gray-500 uppercase tracking-wider block mb-2">{__('Container Width')}</Label>
                                <RadioGroup
                                    value={page.containerWidth || 'boxed'}
                                    onValueChange={(val: any) => onContainerWidthChange(val)}
                                    className="gap-2"
                                >
                                    <div className="flex items-center space-x-2">
                                        <RadioGroupItem value="boxed" id="cw-boxed" />
                                        <Label htmlFor="cw-boxed" className="text-sm font-normal cursor-pointer">{__('Boxed')}</Label>
                                    </div>
                                    <div className="flex items-center space-x-2">
                                        <RadioGroupItem value="fullwidth" id="cw-full" />
                                        <Label htmlFor="cw-full" className="text-sm font-normal cursor-pointer">{__('Full Width')}</Label>
                                    </div>
                                    <div className="flex items-center space-x-2">
                                        <RadioGroupItem value="default" id="cw-default" />
                                        <Label htmlFor="cw-default" className="text-sm font-normal cursor-pointer text-gray-500">{__('Default (SPA Settings)')}</Label>
                                    </div>
                                </RadioGroup>
                            </div>
                        )}

                        {/* Danger Zone */}
                        {!isTemplate && page && onDeletePage && (
                            <div className="pt-2 border-t mt-2">
                                <Label className="text-xs text-red-600 uppercase tracking-wider block mb-2">{__('Danger Zone')}</Label>
                                <Button
                                    variant="outline"
                                    size="sm"
                                    className="w-full justify-start text-red-600 hover:text-red-700 hover:bg-red-50 border-red-200"
                                    onClick={onDeletePage}
                                >
                                    <Trash2 className="w-4 h-4 mr-2" />
                                    {__('Delete This Page')}
                                </Button>
                            </div>
                        )}

                        {/* Danger Zone - Templates */}
                        {isTemplate && page && onDeleteTemplate && (
                            <div className="pt-2 border-t mt-2">
                                <Label className="text-xs text-red-600 uppercase tracking-wider block mb-2">{__('Danger Zone')}</Label>
                                <p className="text-xs text-gray-500 mb-3">
                                    {__('Deleting this template will disable SPA rendering for this post type. WordPress will handle it natively.')}
                                </p>
                                <Button
                                    variant="outline"
                                    size="sm"
                                    className="w-full justify-start text-red-600 hover:text-red-700 hover:bg-red-50 border-red-200"
                                    onClick={onDeleteTemplate}
                                >
                                    <Trash2 className="w-4 h-4 mr-2" />
                                    {__('Abort SPA Template')}
                                </Button>
                            </div>
                        )}
                    </div>
                    <div className="bg-blue-50 text-blue-800 p-3 rounded text-xs leading-relaxed">
                        {__('Select any section on the canvas to edit its content and design.')}
                    </div>
                </div>
            </div >
        );
    }

    return (
        <div
            className={cn(
                "w-80 border-l bg-white flex flex-col transition-all duration-300 shadow-xl z-30",
                isCollapsed && "w-0 overflow-hidden border-none"
            )}
        >
            {/* Header */}
            <div className="h-14 border-b flex items-center justify-between px-4 shrink-0 bg-white">
                <span className="font-semibold text-sm truncate">
                    {SECTION_FIELDS[selectedSection.type]
                        ? (selectedSection.type.charAt(0).toUpperCase() + selectedSection.type.slice(1)).replace('-', ' ')
                        : 'Settings'}
                </span>
                <Button variant="ghost" size="icon" onClick={onToggleCollapse} className="h-8 w-8 hover:bg-gray-100">
                    <PanelRightClose className="h-4 w-4" />
                </Button>
            </div>

            {/* Content Tabs (Content vs Design) */}
            <Tabs defaultValue="content" className="flex-1 flex flex-col overflow-hidden">
                <div className="px-4 pt-4 shrink-0 bg-white">
                    <TabsList className="w-full grid grid-cols-2">
                        <TabsTrigger value="content">{__('Content')}</TabsTrigger>
                        <TabsTrigger value="design">{__('Design')}</TabsTrigger>
                    </TabsList>
                </div>

                <div className="flex-1 overflow-y-auto">
                    {/* Content Tab */}
                    <TabsContent value="content" className="p-4 space-y-6 m-0">
                        {/* Structure & Presets */}
                        <div className="space-y-4">
                            <h4 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3">{__('Structure')}</h4>
                            {LAYOUT_OPTIONS[selectedSection.type] && (
                                <div className="space-y-2">
                                    <Label className="text-xs">{__('Layout Variant')}</Label>
                                    <Select
                                        value={selectedSection.layoutVariant || 'default'}
                                        onValueChange={onLayoutChange}
                                    >
                                        <SelectTrigger><SelectValue /></SelectTrigger>
                                        <SelectContent>
                                            {LAYOUT_OPTIONS[selectedSection.type].map((opt) => (
                                                <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                </div>
                            )}

                            <div className="space-y-2">
                                <Label className="text-xs">{__('Preset Scheme')}</Label>
                                <Select
                                    value={selectedSection.colorScheme || 'default'}
                                    onValueChange={onColorSchemeChange}
                                >
                                    <SelectTrigger><SelectValue /></SelectTrigger>
                                    <SelectContent>
                                        {COLOR_SCHEMES.map((opt) => (
                                            <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>
                        </div>

                        <div className="w-full h-px bg-gray-100" />

                        {/* Fields */}
                        <div className="space-y-4">
                            <h4 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3">{__('Fields')}</h4>
                            {SECTION_FIELDS[selectedSection.type]?.map((field) => (
                                <React.Fragment key={field.name}>
                                    <InspectorField
                                        fieldName={field.name}
                                        fieldLabel={field.label}
                                        fieldType={field.type}
                                        value={selectedSection.props[field.name] || { type: 'static', value: '' }}
                                        onChange={(val) => onSectionPropChange(field.name, val)}
                                        supportsDynamic={field.dynamic && isTemplate}
                                        availableSources={availableSources}
                                    />
                                    {selectedSection.type === 'contact-form' && field.name === 'redirect_url' && (
                                        <p className="text-[10px] text-gray-500 mt-1 pl-1">
                                            Available shortcodes: {'{name}'}, {'{email}'}, {'{date}'}
                                        </p>
                                    )}
                                    {selectedSection.type === 'contact-form' && field.name === 'webhook_url' && (
                                        <Accordion type="single" collapsible className="w-full mt-1 border rounded-md">
                                            <AccordionItem value="payload" className="border-0">
                                                <AccordionTrigger className="text-[10px] py-1 px-2 hover:no-underline text-gray-500">
                                                    View Payload Example
                                                </AccordionTrigger>
                                                <AccordionContent className="px-2 pb-2">
                                                    <pre className="text-[10px] bg-gray-50 p-2 rounded overflow-x-auto">
                                                        {JSON.stringify({
                                                            "form_id": "contact_form_123",
                                                            "fields": {
                                                                "name": "John Doe",
                                                                "email": "john@example.com",
                                                                "message": "Hello world"
                                                            },
                                                            "meta": {
                                                                "url": "https://site.com/contact",
                                                                "timestamp": 1710000000
                                                            }
                                                        }, null, 2)}
                                                    </pre>
                                                </AccordionContent>
                                            </AccordionItem>
                                        </Accordion>
                                    )}
                                </React.Fragment>
                            ))}
                        </div>

                        {/* Feature Grid Repeater */}
                        {selectedSection.type === 'feature-grid' && (() => {
                            const itemsProp = selectedSection.props.items || selectedSection.props.features;
                            const isDynamicItems = itemsProp?.type === 'dynamic' && !!itemsProp?.source;
                            const items = Array.isArray(itemsProp?.value) ? itemsProp.value : [];
                            return (
                                <div className="pt-4 border-t">
                                    <InspectorRepeater
                                        label={__('Features')}
                                        items={items}
                                        onChange={(newItems) => onSectionPropChange('items', { type: 'static', value: newItems })}
                                        fields={[
                                            { name: 'title', label: 'Title', type: 'text' },
                                            { name: 'description', label: 'Description', type: 'textarea' },
                                            { name: 'icon', label: 'Icon', type: 'icon' },
                                        ]}
                                        itemLabelKey="title"
                                        isDynamic={isDynamicItems}
                                        dynamicLabel={
                                            isDynamicItems
                                                ? `Auto-populated from "${itemsProp.source}" at runtime`
                                                : undefined
                                        }
                                    />
                                </div>
                            );
                        })()}

                        {/* Bento Category Grid Repeater */}
                        {selectedSection.type === 'bento-category-grid' && (() => {
                            const itemsProp = selectedSection.props.items;
                            const items = Array.isArray(itemsProp?.value) ? itemsProp.value : [];
                            return (
                                <div className="pt-4 border-t">
                                    <InspectorRepeater
                                        label={__('Grid Items')}
                                        items={items}
                                        onChange={(newItems) => onSectionPropChange('items', { type: 'static', value: newItems })}
                                        fields={[
                                            { name: 'label', label: 'Label', type: 'text' },
                                            { name: 'image', label: 'Image', type: 'image' },
                                            { name: 'url', label: 'Link URL', type: 'text' },
                                            { name: 'size', label: 'Size (small/medium/large/tall)', type: 'text' },
                                        ]}
                                        itemLabelKey="label"
                                    />
                                </div>
                            );
                        })()}

                        {/* Shoppable Image Hotspots Repeater */}
                        {selectedSection.type === 'shoppable-image' && (() => {
                            const hotspotsProp = selectedSection.props.hotspots;
                            const hotspots = Array.isArray(hotspotsProp?.value) ? hotspotsProp.value : [];
                            return (
                                <div className="pt-4 border-t">
                                    <InspectorRepeater
                                        label={__('Hotspots')}
                                        items={hotspots}
                                        onChange={(newItems) => onSectionPropChange('hotspots', { type: 'static', value: newItems })}
                                        fields={[
                                            { name: 'product_slug', label: 'Product', type: 'product' },
                                            // Allow advanced override/editing of asset/data if needed
                                            { name: 'product_name', label: 'Product Name', type: 'text' },
                                            { name: 'product_price', label: 'Price', type: 'text' },
                                            { name: 'product_image', label: 'Product Image URL', type: 'text' },
                                            { name: 'x', label: 'X Position (%)', type: 'text' },
                                            { name: 'y', label: 'Y Position (%)', type: 'text' },
                                        ]}
                                        itemLabelKey="product_name"
                                    />
                                    <p className="text-xs text-muted-foreground mt-2">
                                        X and Y are percentages (0-100) from the top-left of the image.
                                    </p>
                                </div>
                            );
                        })()}
                    </TabsContent>

                    {/* Design Tab */}
                    <TabsContent value="design" className="p-4 space-y-6 m-0">
                        {/* Background */}
                        <div className="space-y-4">
                            <h4 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3">{__('Background')}</h4>

                            {/* Background Type Selector */}
                            <div className="space-y-2">
                                <Label className="text-xs">{__('Type')}</Label>
                                <div className="flex gap-1">
                                    {(['solid', 'gradient', 'image'] as const).map((t) => (
                                        <button
                                            key={t}
                                            onClick={() => onSectionStylesChange({ backgroundType: t })}
                                            className={cn(
                                                'flex-1 text-xs py-1.5 px-2 rounded-md border transition-colors capitalize',
                                                (selectedSection.styles?.backgroundType || 'solid') === t
                                                    ? 'bg-blue-50 border-blue-300 text-blue-700 font-medium'
                                                    : 'bg-white border-gray-200 text-gray-600 hover:bg-gray-50'
                                            )}
                                        >
                                            {t}
                                        </button>
                                    ))}
                                </div>
                            </div>

                            {/* Solid Color */}
                            {(!selectedSection.styles?.backgroundType || selectedSection.styles?.backgroundType === 'solid') && (
                                <div className="space-y-2">
                                    <Label className="text-xs">{__('Background Color')}</Label>
                                    <div className="flex gap-2">
                                        <div className="relative w-8 h-8 rounded border shadow-sm shrink-0 overflow-hidden">
                                            <div className="absolute inset-0" style={{ backgroundColor: selectedSection.styles?.backgroundColor || 'transparent' }} />
                                            <input
                                                type="color"
                                                className="absolute inset-0 opacity-0 cursor-pointer w-full h-full p-0 border-0"
                                                value={selectedSection.styles?.backgroundColor || '#ffffff'}
                                                onChange={(e) => onSectionStylesChange({ backgroundColor: e.target.value })}
                                            />
                                        </div>
                                        <input
                                            type="text"
                                            placeholder="#FFFFFF"
                                            className="flex-1 h-8 rounded-md border border-input bg-background px-3 py-1 text-sm"
                                            value={selectedSection.styles?.backgroundColor || ''}
                                            onChange={(e) => onSectionStylesChange({ backgroundColor: e.target.value })}
                                        />
                                    </div>
                                </div>
                            )}

                            {/* Gradient Controls */}
                            {selectedSection.styles?.backgroundType === 'gradient' && (
                                <div className="space-y-3">
                                    {/* Live Preview Swatch */}
                                    <div
                                        className="w-full h-12 rounded-lg border shadow-inner"
                                        style={{
                                            background: `linear-gradient(${selectedSection.styles?.gradientAngle ?? 135}deg, ${selectedSection.styles?.gradientFrom || '#9333ea'}, ${selectedSection.styles?.gradientTo || '#3b82f6'})`
                                        }}
                                    />
                                    <div className="grid grid-cols-2 gap-3">
                                        <div className="space-y-1">
                                            <Label className="text-xs">{__('From')}</Label>
                                            <div className="flex gap-1.5">
                                                <div className="relative w-8 h-8 rounded border shadow-sm shrink-0 overflow-hidden">
                                                    <div className="absolute inset-0" style={{ backgroundColor: selectedSection.styles?.gradientFrom || '#9333ea' }} />
                                                    <input
                                                        type="color"
                                                        className="absolute inset-0 opacity-0 cursor-pointer w-full h-full p-0 border-0"
                                                        value={selectedSection.styles?.gradientFrom || '#9333ea'}
                                                        onChange={(e) => onSectionStylesChange({ gradientFrom: e.target.value })}
                                                    />
                                                </div>
                                                <input
                                                    type="text"
                                                    className="flex-1 h-8 rounded-md border border-input bg-background px-2 py-1 text-xs"
                                                    value={selectedSection.styles?.gradientFrom || '#9333ea'}
                                                    onChange={(e) => onSectionStylesChange({ gradientFrom: e.target.value })}
                                                />
                                            </div>
                                        </div>
                                        <div className="space-y-1">
                                            <Label className="text-xs">{__('To')}</Label>
                                            <div className="flex gap-1.5">
                                                <div className="relative w-8 h-8 rounded border shadow-sm shrink-0 overflow-hidden">
                                                    <div className="absolute inset-0" style={{ backgroundColor: selectedSection.styles?.gradientTo || '#3b82f6' }} />
                                                    <input
                                                        type="color"
                                                        className="absolute inset-0 opacity-0 cursor-pointer w-full h-full p-0 border-0"
                                                        value={selectedSection.styles?.gradientTo || '#3b82f6'}
                                                        onChange={(e) => onSectionStylesChange({ gradientTo: e.target.value })}
                                                    />
                                                </div>
                                                <input
                                                    type="text"
                                                    className="flex-1 h-8 rounded-md border border-input bg-background px-2 py-1 text-xs"
                                                    value={selectedSection.styles?.gradientTo || '#3b82f6'}
                                                    onChange={(e) => onSectionStylesChange({ gradientTo: e.target.value })}
                                                />
                                            </div>
                                        </div>
                                    </div>
                                    <div className="space-y-1">
                                        <div className="flex items-center justify-between">
                                            <Label className="text-xs">{__('Angle')}</Label>
                                            <span className="text-xs text-gray-500">{selectedSection.styles?.gradientAngle ?? 135}°</span>
                                        </div>
                                        <Slider
                                            value={[selectedSection.styles?.gradientAngle ?? 135]}
                                            min={0}
                                            max={360}
                                            step={15}
                                            onValueChange={(vals) => onSectionStylesChange({ gradientAngle: vals[0] })}
                                        />
                                    </div>
                                </div>
                            )}

                            {/* Image Background */}
                            {selectedSection.styles?.backgroundType === 'image' && (() => {
                                const isDynamicBg = selectedSection.styles?.dynamicBackground === 'post_featured_image';
                                return (
                                    <>
                                        {/* Source toggle: Upload vs Featured Image */}
                                        <div className="space-y-2">
                                            <Label className="text-xs">{__('Background Image')}</Label>
                                            <div className="flex gap-1 p-0.5 bg-gray-100 rounded-md">
                                                <button
                                                    onClick={() => onSectionStylesChange({ dynamicBackground: undefined })}
                                                    className={cn(
                                                        'flex-1 text-xs py-1.5 px-2 rounded transition-colors',
                                                        !isDynamicBg
                                                            ? 'bg-white shadow-sm font-medium text-gray-900'
                                                            : 'text-gray-500 hover:text-gray-700'
                                                    )}
                                                >
                                                    Upload Image
                                                </button>
                                                <button
                                                    onClick={() => onSectionStylesChange({ dynamicBackground: 'post_featured_image', backgroundImage: '' })}
                                                    className={cn(
                                                        'flex-1 text-xs py-1.5 px-2 rounded transition-colors',
                                                        isDynamicBg
                                                            ? 'bg-white shadow-sm font-medium text-gray-900'
                                                            : 'text-gray-500 hover:text-gray-700'
                                                    )}
                                                >
                                                    Featured Image
                                                </button>
                                            </div>
                                        </div>

                                        {/* Static upload */}
                                        {!isDynamicBg && (
                                            <div className="space-y-2">
                                                <MediaUploader type="image" onSelect={(url) => onSectionStylesChange({ backgroundImage: url })}>
                                                    {selectedSection.styles?.backgroundImage ? (
                                                        <div className="relative group cursor-pointer border rounded overflow-hidden h-24 bg-gray-50">
                                                            <img src={selectedSection.styles.backgroundImage} alt="Background" className="w-full h-full object-cover" />
                                                            <div className="absolute inset-0 bg-black/40 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                                                                <span className="text-white text-xs font-medium">{__('Change')}</span>
                                                            </div>
                                                            <button
                                                                onClick={(e) => { e.stopPropagation(); onSectionStylesChange({ backgroundImage: '' }); }}
                                                                className="absolute top-1 right-1 bg-white/90 p-1 rounded-full text-gray-600 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity"
                                                            >
                                                                <Trash2 className="w-3 h-3" />
                                                            </button>
                                                        </div>
                                                    ) : (
                                                        <Button variant="outline" className="w-full h-24 border-dashed flex flex-row gap-2 text-gray-400 font-normal">
                                                            <Palette className="w-6 h-6" />
                                                            {__('Select Image')}
                                                        </Button>
                                                    )}
                                                </MediaUploader>
                                            </div>
                                        )}

                                        {/* Dynamic source info */}
                                        {isDynamicBg && (
                                            <div className="flex items-start gap-2 text-xs bg-blue-50 border border-blue-200 rounded-md p-2.5 text-blue-700">
                                                <span className="mt-0.5">⚡</span>
                                                <span>At runtime, the background will use this post's featured image. Falls back to no background if no featured image is set.</span>
                                            </div>
                                        )}

                                        <div className="space-y-1 pt-2">
                                            <div className="flex items-center justify-between">
                                                <Label className="text-xs">{__('Overlay Opacity')}</Label>
                                                <span className="text-xs text-gray-500">{selectedSection.styles?.backgroundOverlay ?? 0}%</span>
                                            </div>
                                            <Slider
                                                value={[selectedSection.styles?.backgroundOverlay ?? 0]}
                                                min={0}
                                                max={100}
                                                step={5}
                                                onValueChange={(vals) => onSectionStylesChange({ backgroundOverlay: vals[0] })}
                                            />
                                        </div>
                                    </>
                                );
                            })()}

                            {/* Spacing Controls */}
                            <div className="grid grid-cols-2 gap-2 pt-2 border-t mt-4">
                                <div className="space-y-1">
                                    <Label className="text-xs text-gray-500">{__('Padding Top')}</Label>
                                    <input
                                        type="text"
                                        placeholder="e.g. 40px, 4rem"
                                        className="w-full h-8 text-xs rounded border px-2"
                                        value={selectedSection.styles?.paddingTop || ''}
                                        onChange={(e) => onSectionStylesChange({ paddingTop: e.target.value })}
                                    />
                                </div>
                                <div className="space-y-1">
                                    <Label className="text-xs text-gray-500">{__('Padding Bottom')}</Label>
                                    <input
                                        type="text"
                                        placeholder="e.g. 40px, 4rem"
                                        className="w-full h-8 text-xs rounded border px-2"
                                        value={selectedSection.styles?.paddingBottom || ''}
                                        onChange={(e) => onSectionStylesChange({ paddingBottom: e.target.value })}
                                    />
                                </div>
                            </div>

                            <div className="space-y-2 pt-2 border-t mt-4">
                                <Label className="text-xs">{__('Content Width')}</Label>
                                <RadioGroup
                                    value={selectedSection.styles?.contentWidth || 'full'}
                                    onValueChange={(val: any) => onSectionStylesChange({ contentWidth: val })}
                                    className="flex flex-wrap gap-4"
                                >
                                    <div className="flex items-center space-x-2">
                                        <RadioGroupItem value="full" id="width-full" />
                                        <Label htmlFor="width-full" className="text-sm font-normal cursor-pointer">{__('Full Width')}</Label>
                                    </div>
                                    <div className="flex items-center space-x-2">
                                        <RadioGroupItem value="contained" id="width-contained" />
                                        <Label htmlFor="width-contained" className="text-sm font-normal cursor-pointer">{__('Contained')}</Label>
                                    </div>
                                    <div className="flex items-center space-x-2">
                                        <RadioGroupItem value="boxed" id="width-boxed" />
                                        <Label htmlFor="width-boxed" className="text-sm font-normal cursor-pointer">{__('Boxed (Card)')}</Label>
                                    </div>
                                </RadioGroup>
                            </div>

                            <div className="space-y-2 pt-2 border-t mt-4">
                                <Label className="text-xs">{__('Section Height')}</Label>
                                <Select
                                    value={selectedSection.styles?.heightPreset || 'default'}
                                    onValueChange={(val) => {
                                        onSectionStylesChange({ heightPreset: val });
                                    }}
                                >
                                    <SelectTrigger><SelectValue placeholder="Height" /></SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="default">Default</SelectItem>
                                        <SelectItem value="small">Small (Compact)</SelectItem>
                                        <SelectItem value="medium">Medium</SelectItem>
                                        <SelectItem value="large">Large (Spacious)</SelectItem>
                                        <SelectItem value="screen">Full Screen</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>
                        </div>


                        <div className="w-full h-px bg-gray-100" />

                        {/* Element Styles */}
                        <div className="space-y-4">
                            <h4 className="text-xs font-semibold text-gray-500 uppercase tracking-wider">{__('Element Styles')}</h4>

                            <Accordion type="single" collapsible className="w-full">
                                {(STYLABLE_ELEMENTS[selectedSection.type] || []).map((field) => {
                                    const styles = selectedSection.elementStyles?.[field.name] || {};
                                    const isImage = field.type === 'image';

                                    return (
                                        <AccordionItem key={field.name} value={field.name}>
                                            <AccordionTrigger className="text-xs hover:no-underline py-2">{field.label}</AccordionTrigger>
                                            <AccordionContent className="space-y-4 pt-2">
                                                {/* Common: Background Wrapper */}
                                                <div className="space-y-2">
                                                    <Label className="text-xs text-gray-500">{__('Background (Wrapper)')}</Label>
                                                    <div className="flex items-center gap-2">
                                                        <div className="relative w-6 h-6 rounded border shadow-sm shrink-0 overflow-hidden">
                                                            <div className="absolute inset-0" style={{ backgroundColor: styles.backgroundColor || 'transparent' }} />
                                                            <input
                                                                type="color"
                                                                className="absolute inset-0 opacity-0 cursor-pointer w-full h-full p-0 border-0"
                                                                value={styles.backgroundColor || '#ffffff'}
                                                                onChange={(e) => onElementStylesChange(field.name, { backgroundColor: e.target.value })}
                                                            />
                                                        </div>
                                                        <input
                                                            type="text"
                                                            placeholder="Color (#fff)"
                                                            className="flex-1 h-7 text-xs rounded border px-2"
                                                            value={styles.backgroundColor || ''}
                                                            onChange={(e) => onElementStylesChange(field.name, { backgroundColor: e.target.value })}
                                                        />
                                                    </div>
                                                </div>

                                                {!isImage ? (
                                                    <>
                                                        {/* Text Color */}
                                                        <div className="space-y-2">
                                                            <Label className="text-xs text-gray-500">{__('Text Color')}</Label>
                                                            <div className="flex items-center gap-2">
                                                                <div className="relative w-6 h-6 rounded border shadow-sm shrink-0 overflow-hidden">
                                                                    <div className="absolute inset-0" style={{ backgroundColor: styles.color || '#000000' }} />
                                                                    <input
                                                                        type="color"
                                                                        className="absolute inset-0 opacity-0 cursor-pointer w-full h-full p-0 border-0"
                                                                        value={styles.color || '#000000'}
                                                                        onChange={(e) => onElementStylesChange(field.name, { color: e.target.value })}
                                                                    />
                                                                </div>
                                                                <input
                                                                    type="text"
                                                                    placeholder="Color (#000)"
                                                                    className="flex-1 h-7 text-xs rounded border px-2"
                                                                    value={styles.color || ''}
                                                                    onChange={(e) => onElementStylesChange(field.name, { color: e.target.value })}
                                                                />
                                                            </div>
                                                        </div>

                                                        {/* Typography Group */}
                                                        <div className="space-y-2">
                                                            <Label className="text-xs text-gray-500">{__('Typography')}</Label>

                                                            <Select value={styles.fontFamily || 'default'} onValueChange={(val) => onElementStylesChange(field.name, { fontFamily: val === 'default' ? undefined : val as any })}>
                                                                <SelectTrigger className="h-7 text-xs"><SelectValue placeholder="Font Family" /></SelectTrigger>
                                                                <SelectContent>
                                                                    <SelectItem value="default">Default</SelectItem>
                                                                    <SelectItem value="primary">Primary (Headings)</SelectItem>
                                                                    <SelectItem value="secondary">Secondary (Body)</SelectItem>
                                                                </SelectContent>
                                                            </Select>

                                                            <div className="grid grid-cols-2 gap-2">
                                                                <Select value={styles.fontSize || 'default'} onValueChange={(val) => onElementStylesChange(field.name, { fontSize: val === 'default' ? undefined : val })}>
                                                                    <SelectTrigger className="h-7 text-xs"><SelectValue placeholder="Size" /></SelectTrigger>
                                                                    <SelectContent>
                                                                        <SelectItem value="default">Default Size</SelectItem>
                                                                        <SelectItem value="text-sm">Small</SelectItem>
                                                                        <SelectItem value="text-base">Base</SelectItem>
                                                                        <SelectItem value="text-lg">Large</SelectItem>
                                                                        <SelectItem value="text-xl">XL</SelectItem>
                                                                        <SelectItem value="text-2xl">2XL</SelectItem>
                                                                        <SelectItem value="text-3xl">3XL</SelectItem>
                                                                        <SelectItem value="text-4xl">4XL</SelectItem>
                                                                        <SelectItem value="text-5xl">5XL</SelectItem>
                                                                        <SelectItem value="text-6xl">6XL</SelectItem>
                                                                    </SelectContent>
                                                                </Select>

                                                                <Select value={styles.fontWeight || 'default'} onValueChange={(val) => onElementStylesChange(field.name, { fontWeight: val === 'default' ? undefined : val })}>
                                                                    <SelectTrigger className="h-7 text-xs"><SelectValue placeholder="Weight" /></SelectTrigger>
                                                                    <SelectContent>
                                                                        <SelectItem value="default">Default Weight</SelectItem>
                                                                        <SelectItem value="font-light">Light</SelectItem>
                                                                        <SelectItem value="font-normal">Normal</SelectItem>
                                                                        <SelectItem value="font-medium">Medium</SelectItem>
                                                                        <SelectItem value="font-semibold">Semibold</SelectItem>
                                                                        <SelectItem value="font-bold">Bold</SelectItem>
                                                                        <SelectItem value="font-extrabold">Extra Bold</SelectItem>
                                                                    </SelectContent>
                                                                </Select>
                                                            </div>

                                                            <Select value={styles.textAlign || 'default'} onValueChange={(val) => onElementStylesChange(field.name, { textAlign: val === 'default' ? undefined : val as any })}>
                                                                <SelectTrigger className="h-7 text-xs"><SelectValue placeholder="Alignment" /></SelectTrigger>
                                                                <SelectContent>
                                                                    <SelectItem value="default">Default Align</SelectItem>
                                                                    <SelectItem value="left">Left</SelectItem>
                                                                    <SelectItem value="center">Center</SelectItem>
                                                                    <SelectItem value="right">Right</SelectItem>
                                                                </SelectContent>
                                                            </Select>
                                                        </div>

                                                        {/* Link Specific Styles */}
                                                        {field.name === 'link' && (
                                                            <div className="space-y-2">
                                                                <Label className="text-xs text-gray-500">{__('Link Styles')}</Label>
                                                                <Select value={styles.textDecoration || 'default'} onValueChange={(val) => onElementStylesChange(field.name, { textDecoration: val === 'default' ? undefined : val as any })}>
                                                                    <SelectTrigger className="h-7 text-xs"><SelectValue placeholder="Decoration" /></SelectTrigger>
                                                                    <SelectContent>
                                                                        <SelectItem value="default">Default</SelectItem>
                                                                        <SelectItem value="none">None</SelectItem>
                                                                        <SelectItem value="underline">Underline</SelectItem>
                                                                    </SelectContent>
                                                                </Select>
                                                                <div className="space-y-1">
                                                                    <Label className="text-xs text-gray-400">{__('Hover Color')}</Label>
                                                                    <div className="flex items-center gap-2">
                                                                        <div className="relative w-6 h-6 rounded border shadow-sm shrink-0 overflow-hidden">
                                                                            <div className="absolute inset-0" style={{ backgroundColor: styles.hoverColor || 'transparent' }} />
                                                                            <input
                                                                                type="color"
                                                                                className="absolute inset-0 opacity-0 cursor-pointer w-full h-full p-0 border-0"
                                                                                value={styles.hoverColor || '#000000'}
                                                                                onChange={(e) => onElementStylesChange(field.name, { hoverColor: e.target.value })}
                                                                            />
                                                                        </div>
                                                                        <input
                                                                            type="text"
                                                                            placeholder="Hover Color"
                                                                            className="flex-1 h-7 text-xs rounded border px-2"
                                                                            value={styles.hoverColor || ''}
                                                                            onChange={(e) => onElementStylesChange(field.name, { hoverColor: e.target.value })}
                                                                        />
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        )}

                                                        {/* Button/Box Specific Styles */}
                                                        {field.name === 'button' && (
                                                            <div className="space-y-2">
                                                                <Label className="text-xs text-gray-500">{__('Box Styles')}</Label>
                                                                <div className="grid grid-cols-2 gap-2">
                                                                    <div className="space-y-1">
                                                                        <Label className="text-xs text-gray-400">{__('Border Color')}</Label>
                                                                        <div className="flex items-center gap-2 h-7">
                                                                            <div className="relative w-6 h-6 rounded border shadow-sm shrink-0 overflow-hidden">
                                                                                <div className="absolute inset-0" style={{ backgroundColor: styles.borderColor || 'transparent' }} />
                                                                                <input
                                                                                    type="color"
                                                                                    className="absolute inset-0 opacity-0 cursor-pointer w-full h-full p-0 border-0"
                                                                                    value={styles.borderColor || '#000000'}
                                                                                    onChange={(e) => onElementStylesChange(field.name, { borderColor: e.target.value })}
                                                                                />
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div className="space-y-1">
                                                                        <Label className="text-xs text-gray-400">{__('Border Width')}</Label>
                                                                        <input type="text" placeholder="e.g. 1px" className="w-full h-7 text-xs rounded border px-2" value={styles.borderWidth || ''} onChange={(e) => onElementStylesChange(field.name, { borderWidth: e.target.value })} />
                                                                    </div>
                                                                    <div className="space-y-1">
                                                                        <Label className="text-xs text-gray-400">{__('Radius')}</Label>
                                                                        <input type="text" placeholder="e.g. 4px" className="w-full h-7 text-xs rounded border px-2" value={styles.borderRadius || ''} onChange={(e) => onElementStylesChange(field.name, { borderRadius: e.target.value })} />
                                                                    </div>
                                                                    <div className="space-y-1">
                                                                        <Label className="text-xs text-gray-400">{__('Padding')}</Label>
                                                                        <input type="text" placeholder="e.g. 8px 16px" className="w-full h-7 text-xs rounded border px-2" value={styles.padding || ''} onChange={(e) => onElementStylesChange(field.name, { padding: e.target.value })} />
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        )}
                                                    </>
                                                ) : (
                                                    <>
                                                        {/* Image Settings */}
                                                        <div className="space-y-2">
                                                            <Label className="text-xs text-gray-500">{__('Image Fit')}</Label>
                                                            <Select value={styles.objectFit || 'default'} onValueChange={(val) => onElementStylesChange(field.name, { objectFit: val === 'default' ? undefined : val as any })}>
                                                                <SelectTrigger className="h-7 text-xs"><SelectValue placeholder="Object Fit" /></SelectTrigger>
                                                                <SelectContent>
                                                                    <SelectItem value="default">Default</SelectItem>
                                                                    <SelectItem value="cover">Cover</SelectItem>
                                                                    <SelectItem value="contain">Contain</SelectItem>
                                                                    <SelectItem value="fill">Fill</SelectItem>
                                                                </SelectContent>
                                                            </Select>
                                                        </div>

                                                        <div className="grid grid-cols-2 gap-2">
                                                            <div className="space-y-1">
                                                                <Label className="text-xs text-gray-500">{__('Width')}</Label>
                                                                <input type="text" placeholder="e.g. 100%" className="w-full h-7 text-xs rounded border px-2" value={styles.width || ''} onChange={(e) => onElementStylesChange(field.name, { width: e.target.value })} />
                                                            </div>
                                                            <div className="space-y-1">
                                                                <Label className="text-xs text-gray-500">{__('Height')}</Label>
                                                                <input type="text" placeholder="e.g. auto" className="w-full h-7 text-xs rounded border px-2" value={styles.height || ''} onChange={(e) => onElementStylesChange(field.name, { height: e.target.value })} />
                                                            </div>
                                                        </div>
                                                    </>
                                                )}
                                            </AccordionContent>
                                        </AccordionItem>
                                    );
                                })}
                            </Accordion>
                        </div>
                    </TabsContent>
                </div>

                {/* Footer - Delete Button */}
                {
                    selectedSection && (
                        <div className="p-4 border-t mt-auto shrink-0 bg-gray-50/50">
                            <Button variant="destructive" className="w-full" onClick={onDeleteSection}>
                                <Trash2 className="w-4 h-4 mr-2" />
                                {__('Delete Section')}
                            </Button>
                        </div>
                    )
                }
            </Tabs >
        </div >
    );
}
