import { useState } from '@wordpress/element';
import useEditorStore from '../store/useEditorStore';

const FONT_OPTIONS = [
    'inherit', 'system-ui', 'Arial', 'Helvetica Neue', 'Segoe UI', 'Verdana',
    'Tahoma', 'Trebuchet MS', 'Georgia', 'Times New Roman', 'Courier New', 'Lucida Console',
];

function Section({ title, children, defaultOpen = false }) {
    const [open, setOpen] = useState(defaultOpen);
    return (
        <div className="lpcd-inspector-section">
            <button className={`lpcd-section-header ${open ? 'open' : ''}`} onClick={() => setOpen(!open)}>
                <span>{title}</span>
                <span className={`dashicons dashicons-arrow-${open ? 'up' : 'down'}-alt2`} />
            </button>
            {open && <div className="lpcd-section-body">{children}</div>}
        </div>
    );
}

function Field({ label, children }) {
    return (
        <div className="lpcd-field">
            <label className="lpcd-field-label">{label}</label>
            {children}
        </div>
    );
}

function ColorField({ label, value, onChange }) {
    return (
        <Field label={label}>
            <div className="lpcd-color-field">
                <input type="color" value={value || '#000000'} onChange={(e) => onChange(e.target.value)} />
                <input type="text" value={value || ''} onChange={(e) => onChange(e.target.value)} className="lpcd-color-text" />
            </div>
        </Field>
    );
}

function RangeField({ label, value, onChange, min, max, step = 1, unit = 'px' }) {
    return (
        <Field label={`${label}: ${value}${unit}`}>
            <input type="range" min={min} max={max} step={step} value={value} onChange={(e) => onChange(parseFloat(e.target.value))} className="lpcd-range" />
        </Field>
    );
}

function SelectField({ label, value, onChange, options }) {
    return (
        <Field label={label}>
            <select value={value || ''} onChange={(e) => onChange(e.target.value)} className="lpcd-select">
                {options.map((opt) => (
                    <option key={typeof opt === 'string' ? opt : opt.value} value={typeof opt === 'string' ? opt : opt.value}>
                        {typeof opt === 'string' ? opt : opt.label}
                    </option>
                ))}
            </select>
        </Field>
    );
}

function ToggleField({ label, value, onChange }) {
    return (
        <Field label={label}>
            <label className="lpcd-toggle">
                <input type="checkbox" checked={!!value} onChange={(e) => onChange(e.target.checked)} />
                <span className="lpcd-toggle-slider" />
            </label>
        </Field>
    );
}

function TextField({ label, value, onChange, placeholder = '' }) {
    return (
        <Field label={label}>
            <input type="text" value={value || ''} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} className="lpcd-input" />
        </Field>
    );
}

function TextAreaField({ label, value, onChange, placeholder = '' }) {
    return (
        <Field label={label}>
            <textarea value={value || ''} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} className="lpcd-textarea" rows="5" />
        </Field>
    );
}

function MediaUploadField({ label, value, onChange }) {
    const openMediaBrowser = () => {
        if (!window.wp || !window.wp.media) {
            alert('WordPress media library is not available.');
            return;
        }
        const frame = window.wp.media({
            title: 'Select or Upload Media',
            button: { text: 'Use this media' },
            multiple: false,
        });

        frame.on('select', () => {
            const attachment = frame.state().get('selection').first().toJSON();
            onChange(attachment.url);
        });

        frame.open();
    };

    return (
        <Field label={label}>
            <div className="lpcd-media-field" style={{ display: 'flex', gap: '8px' }}>
                <input type="text" value={value || ''} onChange={(e) => onChange(e.target.value)} placeholder="https://..." className="lpcd-input" style={{ flex: 1 }} />
                <button type="button" className="lpcd-btn lpcd-btn-secondary" onClick={openMediaBrowser} style={{ padding: '6px 12px' }}>
                    Upload
                </button>
            </div>
            {value && (
                <div style={{ marginTop: '8px', position: 'relative', display: 'inline-block' }}>
                    <img src={value} alt="Preview" style={{ maxWidth: '100%', maxHeight: '100px', borderRadius: '4px', border: '1px solid #e2e8f0', display: 'block' }} />
                    <button type="button" onClick={() => onChange('')} style={{ position: 'absolute', top: '4px', right: '4px', background: 'rgba(255,255,255,0.9)', border: 'none', borderRadius: '50%', width: '24px', height: '24px', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#dc2626', boxShadow: '0 1px 3px rgba(0,0,0,0.2)' }}>
                        <span className="dashicons dashicons-no-alt" style={{ fontSize: '16px', width: '16px', height: '16px' }} />
                    </button>
                </div>
            )}
        </Field>
    );
}

export default function InspectorPanel() {
    const inspectorTab = useEditorStore((s) => s.inspectorTab);
    const setInspectorTab = useEditorStore((s) => s.setInspectorTab);

    return (
        <div className="lpcd-inspector-panel">
            <div className="lpcd-inspector-tabs">
                <button className={`lpcd-tab ${inspectorTab === 'block' ? 'active' : ''}`} onClick={() => setInspectorTab('block')}>Block</button>
                <button className={`lpcd-tab ${inspectorTab === 'page' ? 'active' : ''}`} onClick={() => setInspectorTab('page')}>Page</button>
            </div>
            <div className="lpcd-inspector-content">
                {inspectorTab === 'block' ? <BlockSettings /> : <PageSettings />}
            </div>
        </div>
    );
}

function BlockSettings() {
    const selectedBlockId = useEditorStore((s) => s.selectedBlockId);
    const editingTemplate = useEditorStore((s) => s.editingTemplate);
    const updateBlockSettings = useEditorStore((s) => s.updateBlockSettings);

    if (!selectedBlockId || !editingTemplate) {
        return <div className="lpcd-inspector-empty"><p>Select a block to edit its settings.</p></div>;
    }

    const block = editingTemplate.jsonData.blocks.find((b) => b.id === selectedBlockId);
    if (!block) return <div className="lpcd-inspector-empty"><p>Block not found.</p></div>;

    const s = block.settings || {};
    const u = (key, val) => updateBlockSettings(selectedBlockId, key, val);

    switch (block.type) {
        case 'loginForm':
            return <LoginFormSettings s={s} u={u} />;
        case 'logo':
            return <LogoSettings s={s} u={u} />;
        case 'heading':
            return <HeadingSettings s={s} u={u} />;
        case 'text':
            return <TextSettings s={s} u={u} />;
        case 'divider':
            return <DividerSettings s={s} u={u} />;
        case 'videoBackground':
            return <VideoBackgroundSettings s={s} u={u} />;
        case 'customHtml':
            return <CustomHtmlSettings s={s} u={u} />;
        default:
            return null;
    }
}

function LoginFormSettings({ s, u }) {
    return (
        <>
            <Section title="Form Container" defaultOpen>
                <ColorField label="Background" value={s.formBackground} onChange={(v) => u('formBackground', v)} />
                <RangeField label="Width" value={s.formWidth || 360} min={300} max={480} onChange={(v) => u('formWidth', v)} />
                <RangeField label="Padding" value={s.formPadding || 26} min={16} max={60} onChange={(v) => u('formPadding', v)} />
                <RangeField label="Border Radius" value={s.formBorderRadius || 4} min={0} max={20} onChange={(v) => u('formBorderRadius', v)} />
                <SelectField label="Box Shadow" value={s.formBoxShadow} onChange={(v) => u('formBoxShadow', v)} options={[{ value: 'none', label: 'None' }, { value: 'soft', label: 'Soft' }, { value: 'medium', label: 'Medium' }, { value: 'strong', label: 'Strong' }, { value: 'custom', label: 'Custom' }]} />
                {s.formBoxShadow === 'custom' && (
                    <>
                        <RangeField label="X Offset" value={s.shadowX ?? 0} min={-50} max={50} onChange={(v) => u('shadowX', v)} />
                        <RangeField label="Y Offset" value={s.shadowY ?? 20} min={-50} max={50} onChange={(v) => u('shadowY', v)} />
                        <RangeField label="Blur" value={s.shadowBlur ?? 40} min={0} max={100} onChange={(v) => u('shadowBlur', v)} />
                        <RangeField label="Spread" value={s.shadowSpread ?? 0} min={-20} max={20} onChange={(v) => u('shadowSpread', v)} />
                        <TextField label="Shadow Color" value={s.shadowColor || 'rgba(0,0,0,0.15)'} onChange={(v) => u('shadowColor', v)} placeholder="rgba(0,0,0,0.15)" />
                        <ToggleField label="Inset" value={s.shadowInset} onChange={(v) => u('shadowInset', v)} />
                    </>
                )}
                <ToggleField label="Border" value={s.formBorderEnabled} onChange={(v) => u('formBorderEnabled', v)} />
                {s.formBorderEnabled && (
                    <>
                        <ColorField label="Border Color" value={s.formBorderColor} onChange={(v) => u('formBorderColor', v)} />
                        <RangeField label="Border Width" value={s.formBorderWidth || 1} min={1} max={4} onChange={(v) => u('formBorderWidth', v)} />
                    </>
                )}
                <RangeField label="Top Space (Margin)" value={s.marginTop ?? 0} min={0} max={100} onChange={(v) => u('marginTop', v)} />
                <RangeField label="Bottom Space (Margin)" value={s.marginBottom ?? 20} min={0} max={100} onChange={(v) => u('marginBottom', v)} />
            </Section>

            <Section title="Animation">
                <SelectField label="Type" value={s.animationType} onChange={(v) => u('animationType', v)} options={[{ value: 'none', label: 'None' }, { value: 'fadeIn', label: 'Fade In' }, { value: 'slideUp', label: 'Slide Up' }, { value: 'zoomIn', label: 'Zoom In' }]} />
                <SelectField label="Speed" value={s.animationDuration} onChange={(v) => u('animationDuration', v)} options={[{ value: 'fast', label: 'Fast' }, { value: 'normal', label: 'Normal' }, { value: 'slow', label: 'Slow' }]} />
            </Section>

            <Section title="Username Field">
                <ToggleField label="Show Label" value={s.usernameShowLabel} onChange={(v) => u('usernameShowLabel', v)} />
                <TextField label="Label" value={s.usernameLabel} onChange={(v) => u('usernameLabel', v)} />
                <TextField label="Placeholder" value={s.usernamePlaceholder} onChange={(v) => u('usernamePlaceholder', v)} />
                <ColorField label="Background" value={s.usernameBackgroundColor} onChange={(v) => u('usernameBackgroundColor', v)} />
                <ColorField label="Border Color" value={s.usernameBorderColor} onChange={(v) => u('usernameBorderColor', v)} />
                <ColorField label="Text Color" value={s.usernameTextColor} onChange={(v) => u('usernameTextColor', v)} />
                <ColorField label="Label Color" value={s.labelColor} onChange={(v) => u('labelColor', v)} />
                <RangeField label="Font Size" value={s.usernameFontSize || 15} min={12} max={20} onChange={(v) => u('usernameFontSize', v)} />
                <RangeField label="Height" value={s.usernameHeight || 44} min={36} max={56} onChange={(v) => u('usernameHeight', v)} />
                <RangeField label="Border Radius" value={s.usernameBorderRadius || 4} min={0} max={12} onChange={(v) => u('usernameBorderRadius', v)} />
            </Section>

            <Section title="Password Field">
                <ToggleField label="Show Label" value={s.passwordShowLabel} onChange={(v) => u('passwordShowLabel', v)} />
                <TextField label="Label" value={s.passwordLabel} onChange={(v) => u('passwordLabel', v)} />
                <TextField label="Placeholder" value={s.passwordPlaceholder} onChange={(v) => u('passwordPlaceholder', v)} />
                <ToggleField label="Show/Hide Toggle" value={s.showPasswordToggle} onChange={(v) => u('showPasswordToggle', v)} />
                <ColorField label="Background" value={s.passwordBackgroundColor} onChange={(v) => u('passwordBackgroundColor', v)} />
                <ColorField label="Border Color" value={s.passwordBorderColor} onChange={(v) => u('passwordBorderColor', v)} />
                <ColorField label="Text Color" value={s.passwordTextColor} onChange={(v) => u('passwordTextColor', v)} />
                <RangeField label="Height" value={s.passwordHeight || 44} min={36} max={56} onChange={(v) => u('passwordHeight', v)} />
            </Section>

            <Section title="Submit Button">
                <TextField label="Text" value={s.submitText} onChange={(v) => u('submitText', v)} placeholder="Log In" />
                <ColorField label="Background" value={s.submitBackgroundColor} onChange={(v) => u('submitBackgroundColor', v)} />
                <ColorField label="Text Color" value={s.submitTextColor} onChange={(v) => u('submitTextColor', v)} />
                <ColorField label="Hover Background" value={s.submitHoverBackgroundColor} onChange={(v) => u('submitHoverBackgroundColor', v)} />
                <RangeField label="Height" value={s.submitHeight || 44} min={36} max={56} onChange={(v) => u('submitHeight', v)} />
                <RangeField label="Font Size" value={s.submitFontSize || 16} min={12} max={22} onChange={(v) => u('submitFontSize', v)} />
                <RangeField label="Border Radius" value={s.submitBorderRadius || 4} min={0} max={30} onChange={(v) => u('submitBorderRadius', v)} />
                <SelectField label="Font Weight" value={s.submitFontWeight} onChange={(v) => u('submitFontWeight', v)} options={['400', '500', '600', '700']} />
                <ToggleField label="Full Width" value={s.submitFullWidth} onChange={(v) => u('submitFullWidth', v)} />
                <SelectField label="Hover Effect" value={s.hoverEffect || 'none'} onChange={(v) => u('hoverEffect', v)} options={[{ value: 'none', label: 'None' }, { value: 'lift', label: 'Lift' }, { value: 'glow', label: 'Glow' }, { value: 'scale', label: 'Scale' }, { value: 'pulse', label: 'Pulse' }, { value: 'bgSlide', label: 'Background Slide' }]} />
                <ToggleField label="Loading Spinner" value={s.showLoadingSpinner} onChange={(v) => u('showLoadingSpinner', v)} />
            </Section>

            <Section title="Links & Extras">
                <ToggleField label="Remember Me" value={s.showRememberMe} onChange={(v) => u('showRememberMe', v)} />
                {s.showRememberMe && (
                    <>
                        <TextField label="Remember Me Text" value={s.rememberMeText} onChange={(v) => u('rememberMeText', v)} />
                        <ColorField label="Remember Me Color" value={s.rememberMeColor} onChange={(v) => u('rememberMeColor', v)} />
                    </>
                )}
                <ToggleField label="Lost Password" value={s.showLostPassword} onChange={(v) => u('showLostPassword', v)} />
                {s.showLostPassword && (
                    <>
                        <TextField label="Lost Password Text" value={s.lostPasswordText} onChange={(v) => u('lostPasswordText', v)} />
                        <ColorField label="Link Color" value={s.lostPasswordColor} onChange={(v) => u('lostPasswordColor', v)} />
                    </>
                )}
                <ToggleField label="Back to Blog" value={s.showBackLink} onChange={(v) => u('showBackLink', v)} />
                <ToggleField label="Register Link" value={s.showRegisterLink} onChange={(v) => u('showRegisterLink', v)} />
            </Section>
        </>
    );
}

function LogoSettings({ s, u }) {
    return (
        <>
            <Section title="Logo Settings" defaultOpen>
                <SelectField label="Source" value={s.source} onChange={(v) => u('source', v)} options={[{ value: 'site', label: 'Site Logo' }, { value: 'upload', label: 'Upload' }, { value: 'url', label: 'URL' }]} />
                {(s.source === 'upload' || s.source === 'url') && (
                    <MediaUploadField label="Image URL" value={s.imageUrl} onChange={(v) => u('imageUrl', v)} />
                )}
                <RangeField label="Width" value={s.width || 80} min={20} max={300} onChange={(v) => u('width', v)} />
                <SelectField label="Alignment" value={s.alignment} onChange={(v) => u('alignment', v)} options={['left', 'center', 'right']} />
                <TextField label="Link URL" value={s.linkUrl} onChange={(v) => u('linkUrl', v)} placeholder="Leave empty for home URL" />
            </Section>
            <Section title="Spacing">
                <RangeField label="Margin Top" value={s.marginTop || 0} min={0} max={80} onChange={(v) => u('marginTop', v)} />
                <RangeField label="Margin Bottom" value={s.marginBottom || 20} min={0} max={80} onChange={(v) => u('marginBottom', v)} />
                <RangeField label="Padding Left" value={s.paddingLeft || 0} min={0} max={60} onChange={(v) => u('paddingLeft', v)} />
                <RangeField label="Padding Right" value={s.paddingRight || 0} min={0} max={60} onChange={(v) => u('paddingRight', v)} />
            </Section>
        </>
    );
}

function HeadingSettings({ s, u }) {
    return (
        <>
            <Section title="Heading Settings" defaultOpen>
                <TextField label="Text" value={s.text} onChange={(v) => u('text', v)} />
                <SelectField label="Tag" value={s.tag} onChange={(v) => u('tag', v)} options={['h1', 'h2', 'h3', 'h4', 'p']} />
                <SelectField label="Font" value={s.fontFamily} onChange={(v) => u('fontFamily', v)} options={FONT_OPTIONS} />
                <RangeField label="Size" value={s.fontSize || 24} min={12} max={60} onChange={(v) => u('fontSize', v)} />
                <SelectField label="Weight" value={s.fontWeight} onChange={(v) => u('fontWeight', v)} options={['300', '400', '500', '600', '700', '800']} />
                <ColorField label="Color" value={s.textColor} onChange={(v) => u('textColor', v)} />
                <SelectField label="Alignment" value={s.alignment} onChange={(v) => u('alignment', v)} options={['left', 'center', 'right']} />
                <RangeField label="Letter Spacing" value={s.letterSpacing || 0} min={-2} max={8} step={0.5} unit="px" onChange={(v) => u('letterSpacing', v)} />
            </Section>
            <Section title="Spacing">
                <RangeField label="Margin Top" value={s.marginTop || 0} min={0} max={80} onChange={(v) => u('marginTop', v)} />
                <RangeField label="Margin Bottom" value={s.marginBottom || 12} min={0} max={80} onChange={(v) => u('marginBottom', v)} />
                <RangeField label="Padding Left" value={s.paddingLeft || 0} min={0} max={60} onChange={(v) => u('paddingLeft', v)} />
                <RangeField label="Padding Right" value={s.paddingRight || 0} min={0} max={60} onChange={(v) => u('paddingRight', v)} />
            </Section>
        </>
    );
}

function TextSettings({ s, u }) {
    return (
        <>
            <Section title="Text Settings" defaultOpen>
                <TextField label="Text" value={s.text} onChange={(v) => u('text', v)} />
                <SelectField label="Font" value={s.fontFamily} onChange={(v) => u('fontFamily', v)} options={FONT_OPTIONS} />
                <RangeField label="Size" value={s.fontSize || 14} min={12} max={24} onChange={(v) => u('fontSize', v)} />
                <SelectField label="Weight" value={s.fontWeight} onChange={(v) => u('fontWeight', v)} options={['300', '400', '500', '600']} />
                <ColorField label="Color" value={s.textColor} onChange={(v) => u('textColor', v)} />
                <SelectField label="Alignment" value={s.alignment} onChange={(v) => u('alignment', v)} options={['left', 'center', 'right']} />
                <RangeField label="Line Height" value={s.lineHeight || 1.6} min={1.0} max={3.0} step={0.1} unit="" onChange={(v) => u('lineHeight', v)} />
            </Section>
            <Section title="Spacing">
                <RangeField label="Margin Top" value={s.marginTop || 0} min={0} max={80} onChange={(v) => u('marginTop', v)} />
                <RangeField label="Margin Bottom" value={s.marginBottom || 16} min={0} max={80} onChange={(v) => u('marginBottom', v)} />
                <RangeField label="Padding Left" value={s.paddingLeft || 0} min={0} max={60} onChange={(v) => u('paddingLeft', v)} />
                <RangeField label="Padding Right" value={s.paddingRight || 0} min={0} max={60} onChange={(v) => u('paddingRight', v)} />
            </Section>
        </>
    );
}

function DividerSettings({ s, u }) {
    return (
        <Section title="Divider Settings" defaultOpen>
            <SelectField label="Style" value={s.style} onChange={(v) => u('style', v)} options={[{ value: 'solid', label: 'Solid' }, { value: 'dashed', label: 'Dashed' }, { value: 'dotted', label: 'Dotted' }, { value: 'invisible', label: 'Invisible (Spacer)' }]} />
            <ColorField label="Color" value={s.color} onChange={(v) => u('color', v)} />
            <RangeField label="Width" value={s.width || 100} min={10} max={100} unit="%" onChange={(v) => u('width', v)} />
            <RangeField label="Thickness" value={s.thickness || 1} min={1} max={8} onChange={(v) => u('thickness', v)} />
            <SelectField label="Alignment" value={s.alignment} onChange={(v) => u('alignment', v)} options={['left', 'center', 'right']} />
            <RangeField label="Top Spacing" value={s.marginTop || 12} min={0} max={60} onChange={(v) => u('marginTop', v)} />
            <RangeField label="Bottom Spacing" value={s.marginBottom || 12} min={0} max={60} onChange={(v) => u('marginBottom', v)} />
        </Section>
    );
}

function VideoBackgroundSettings({ s, u }) {
    return (
        <>
            <Section title="Source" defaultOpen>
                <SelectField label="Source Type" value={s.source || 'youtube'} onChange={(v) => u('source', v)} options={[{ value: 'youtube', label: 'YouTube URL' }, { value: 'selfhosted', label: 'Self-hosted URL' }, { value: 'upload', label: 'Upload MP4' }]} />
                {(s.source || 'youtube') === 'youtube' && (
                    <TextField label="YouTube URL" value={s.youtubeUrl || ''} onChange={(v) => u('youtubeUrl', v)} placeholder="https://www.youtube.com/watch?v=..." />
                )}
                {s.source === 'selfhosted' && (
                    <TextField label="Video URL" value={s.videoUrl || ''} onChange={(v) => u('videoUrl', v)} placeholder="https://example.com/video.mp4" />
                )}
                {s.source === 'upload' && (
                    <MediaUploadField label="Upload MP4" value={s.videoUpload || ''} onChange={(v) => u('videoUpload', v)} />
                )}
            </Section>
            <Section title="Playback">
                <ToggleField label="Autoplay" value={s.autoplay !== false} onChange={(v) => u('autoplay', v)} />
                <ToggleField label="Mute" value={s.mute !== false} onChange={(v) => u('mute', v)} />
                {s.mute === false && (
                    <div style={{ padding: '8px 12px', background: '#fef3c7', borderRadius: '4px', fontSize: '12px', color: '#92400e', marginBottom: '8px' }}>Mute is required for autoplay to work in most browsers.</div>
                )}
                <ToggleField label="Loop" value={s.loop !== false} onChange={(v) => u('loop', v)} />
            </Section>
            <Section title="Overlay">
                <ToggleField label="Show Overlay" value={s.overlayEnabled} onChange={(v) => u('overlayEnabled', v)} />
                {s.overlayEnabled && (
                    <>
                        <ColorField label="Overlay Color" value={s.overlayColor || '#000000'} onChange={(v) => u('overlayColor', v)} />
                        <RangeField label="Overlay Opacity" value={s.overlayOpacity ?? 0.4} min={0} max={1} step={0.05} unit="" onChange={(v) => u('overlayOpacity', v)} />
                    </>
                )}
            </Section>
            <Section title="Fallback">
                <MediaUploadField label="Fallback Image (Mobile)" value={s.fallbackImage || ''} onChange={(v) => u('fallbackImage', v)} />
                <p style={{ fontSize: '12px', color: '#64748b', margin: '4px 0 0' }}>Shown on mobile devices where video autoplay is blocked.</p>
            </Section>
            <Section title="Spacing">
                <RangeField label="Margin Top" value={s.marginTop || 0} min={0} max={80} onChange={(v) => u('marginTop', v)} />
                <RangeField label="Margin Bottom" value={s.marginBottom || 0} min={0} max={80} onChange={(v) => u('marginBottom', v)} />
            </Section>
        </>
    );
}

function CustomHtmlSettings({ s, u }) {
    return (
        <>
            <Section title="Custom HTML" defaultOpen>
                <div style={{ padding: '8px 12px', background: '#dbeafe', borderRadius: '4px', fontSize: '12px', color: '#1e40af', marginBottom: '8px' }}>Script tags are not allowed here. To add JavaScript, use Settings → Advanced → Custom JavaScript.</div>
                <TextAreaField
                    label="HTML Content"
                    value={s.htmlContent || ''}
                    onChange={(v) => u('htmlContent', v)}
                    placeholder="<div class='my-widget'>Your HTML here</div>"
                />
                <p style={{ fontSize: '12px', color: '#64748b', margin: '4px 0 0' }}>Shortcodes are supported. Content is sanitized before output.</p>
            </Section>
            <Section title="Spacing">
                <RangeField label="Margin Top" value={s.marginTop || 0} min={0} max={80} onChange={(v) => u('marginTop', v)} />
                <RangeField label="Margin Bottom" value={s.marginBottom || 16} min={0} max={80} onChange={(v) => u('marginBottom', v)} />
                <RangeField label="Padding Left" value={s.paddingLeft || 0} min={0} max={60} onChange={(v) => u('paddingLeft', v)} />
                <RangeField label="Padding Right" value={s.paddingRight || 0} min={0} max={60} onChange={(v) => u('paddingRight', v)} />
            </Section>
        </>
    );
}

function PageSettings() {
    const editingTemplate = useEditorStore((s) => s.editingTemplate);
    const updatePageSettings = useEditorStore((s) => s.updatePageSettings);
    const updateNestedPageSetting = useEditorStore((s) => s.updateNestedPageSetting);

    if (!editingTemplate) return null;
    const ps = editingTemplate.jsonData.pageSettings || {};

    return (
        <>
            <Section title="Layout" defaultOpen>
                <SelectField
                    label="Layout Type"
                    value={ps.layoutType || 'centered'}
                    onChange={(v) => updatePageSettings('layoutType', v)}
                    options={[
                        { value: 'centered', label: 'Centered (Default)' },
                        { value: 'split_left', label: 'Split/Side-by-Side (Image Left)' },
                        { value: 'split_right', label: 'Split/Side-by-Side (Image Right)' }
                    ]}
                />
                {ps.layoutType !== 'centered' && (
                    <>
                        <RangeField label="Form Panel Width" value={ps.splitFormWidth || 40} min={20} max={80} unit="%" onChange={(v) => updatePageSettings('splitFormWidth', v)} />
                        <SelectField
                            label="Form Vertical Alignment"
                            value={ps.splitAlignment || 'center'}
                            onChange={(v) => updatePageSettings('splitAlignment', v)}
                            options={[
                                { value: 'center', label: 'Center' },
                                { value: 'flex-start', label: 'Top' },
                                { value: 'flex-end', label: 'Bottom' },
                                { value: 'stretch', label: 'Stretch' }
                            ]}
                        />
                    </>
                )}
            </Section>

            {(ps.layoutType === 'split_left' || ps.layoutType === 'split_right') && (
                <Section title="Branding Panel" defaultOpen>
                    <SelectField
                        label="Background Type"
                        value={ps.brandingPanel?.backgroundType || 'color'}
                        onChange={(v) => updateNestedPageSetting('brandingPanel', 'backgroundType', v)}
                        options={[
                            { value: 'color', label: 'Solid Color' },
                            { value: 'gradient', label: 'Gradient' },
                            { value: 'image', label: 'Image' }
                        ]}
                    />
                    {(!ps.brandingPanel?.backgroundType || ps.brandingPanel?.backgroundType === 'color') && (
                        <ColorField label="Background Color" value={ps.brandingPanel?.backgroundColor || '#1a1a2e'} onChange={(v) => updateNestedPageSetting('brandingPanel', 'backgroundColor', v)} />
                    )}
                    {ps.brandingPanel?.backgroundType === 'gradient' && (
                        <>
                            <ColorField label="Gradient Color 1" value={ps.brandingPanel?.gradientColor1 || '#1a1a2e'} onChange={(v) => updateNestedPageSetting('brandingPanel', 'gradientColor1', v)} />
                            <ColorField label="Gradient Color 2" value={ps.brandingPanel?.gradientColor2 || '#16213e'} onChange={(v) => updateNestedPageSetting('brandingPanel', 'gradientColor2', v)} />
                            <RangeField label="Gradient Angle" value={ps.brandingPanel?.gradientAngle || 135} min={0} max={360} unit="°" onChange={(v) => updateNestedPageSetting('brandingPanel', 'gradientAngle', v)} />
                        </>
                    )}
                    {ps.brandingPanel?.backgroundType === 'image' && (
                        <>
                            <MediaUploadField label="Background Image" value={ps.brandingPanel?.backgroundImage} onChange={(v) => updateNestedPageSetting('brandingPanel', 'backgroundImage', v)} />
                            <SelectField label="Position" value={ps.brandingPanel?.backgroundPosition || 'center'} onChange={(v) => updateNestedPageSetting('brandingPanel', 'backgroundPosition', v)} options={['center', 'top', 'bottom', 'left', 'right']} />
                            <SelectField label="Size" value={ps.brandingPanel?.backgroundSize || 'cover'} onChange={(v) => updateNestedPageSetting('brandingPanel', 'backgroundSize', v)} options={['cover', 'contain', 'auto']} />
                        </>
                    )}
                    <ColorField label="Text Color" value={ps.brandingPanel?.textColor || '#ffffff'} onChange={(v) => updateNestedPageSetting('brandingPanel', 'textColor', v)} />
                    <SelectField
                        label="Vertical Alignment"
                        value={ps.brandingPanel?.verticalAlign || 'center'}
                        onChange={(v) => updateNestedPageSetting('brandingPanel', 'verticalAlign', v)}
                        options={[
                            { value: 'center', label: 'Center' },
                            { value: 'flex-start', label: 'Top' },
                            { value: 'flex-end', label: 'Bottom' }
                        ]}
                    />
                </Section>
            )}

            <Section title="Background">
                {(() => {
                    const isPro = !!window.lpcdEditor?.isPro;
                    const bgOptions = [
                        { value: 'color', label: 'Solid Color' },
                        { value: 'gradient', label: 'Gradient' },
                        { value: 'image', label: 'Image' },
                        { value: 'animated-gradient', label: 'Animated Gradient', pro: true },
                        { value: 'video', label: 'Video', pro: true },
                    ];
                    return (
                        <>
                            <Field label="Type">
                                <select
                                    value={ps.backgroundType}
                                    onChange={(e) => {
                                        const v = e.target.value;
                                        const opt = bgOptions.find(o => o.value === v);
                                        if (opt?.pro && !isPro) {
                                            e.target.value = ps.backgroundType;
                                            return;
                                        }
                                        updatePageSettings('backgroundType', v);
                                    }}
                                    className="lpcd-select"
                                >
                                    {bgOptions.map(opt => (
                                        <option key={opt.value} value={opt.value} disabled={opt.pro && !isPro}>
                                            {opt.label}{opt.pro ? ' ⭐ PRO' : ''}
                                        </option>
                                    ))}
                                </select>
                            </Field>
                            {(!isPro && (ps.backgroundType === 'animated-gradient' || ps.backgroundType === 'video')) && (
                                <div className="lpcd-pro-notice-inline" style={{ marginBottom: '12px' }}>
                                    <span className="dashicons dashicons-lock" /> This background type requires a Pro license. <a href="#">Upgrade Now</a>
                                </div>
                            )}
                        </>
                    );
                })()}
                {ps.backgroundType === 'color' && (
                    <ColorField label="Color" value={ps.backgroundColor} onChange={(v) => updatePageSettings('backgroundColor', v)} />
                )}
                {ps.backgroundType === 'gradient' && (
                    <>
                        <ColorField label="Color 1" value={ps.backgroundGradient?.color1} onChange={(v) => updateNestedPageSetting('backgroundGradient', 'color1', v)} />
                        <ColorField label="Color 2" value={ps.backgroundGradient?.color2} onChange={(v) => updateNestedPageSetting('backgroundGradient', 'color2', v)} />
                        <RangeField label="Angle" value={ps.backgroundGradient?.angle || 135} min={0} max={360} unit="°" onChange={(v) => updateNestedPageSetting('backgroundGradient', 'angle', v)} />
                    </>
                )}
                {ps.backgroundType === 'image' && (
                    <>
                        <MediaUploadField label="Image URL" value={ps.backgroundImage} onChange={(v) => updatePageSettings('backgroundImage', v)} />
                        <SelectField label="Position" value={ps.backgroundPosition} onChange={(v) => updatePageSettings('backgroundPosition', v)} options={['center', 'top', 'bottom', 'left', 'right']} />
                        <SelectField label="Size" value={ps.backgroundSize} onChange={(v) => updatePageSettings('backgroundSize', v)} options={['cover', 'contain', 'auto']} />
                        <ToggleField label="Overlay" value={ps.overlayEnabled} onChange={(v) => updatePageSettings('overlayEnabled', v)} />
                        {ps.overlayEnabled && (
                            <>
                                <ColorField label="Overlay Color" value={ps.overlayColor} onChange={(v) => updatePageSettings('overlayColor', v)} />
                                <RangeField label="Overlay Opacity" value={ps.overlayOpacity || 0.4} min={0} max={1} step={0.05} unit="" onChange={(v) => updatePageSettings('overlayOpacity', v)} />
                            </>
                        )}
                    </>
                )}
                {ps.backgroundType === 'animated-gradient' && (
                    <div className={!window.lpcdEditor?.isPro ? 'lpcd-pro-locked' : ''}>
                        <div style={{ marginBottom: '8px' }}>
                            <label className="lpcd-field-label">Gradient Colors</label>
                            {(ps.animatedGradient?.colors || ['#667eea', '#764ba2']).map((color, idx) => (
                                <div key={idx} style={{ display: 'flex', gap: '6px', alignItems: 'center', marginBottom: '6px' }}>
                                    <input type="color" value={color} onChange={(e) => {
                                        const colors = [...(ps.animatedGradient?.colors || ['#667eea', '#764ba2'])];
                                        colors[idx] = e.target.value;
                                        updateNestedPageSetting('animatedGradient', 'colors', colors);
                                    }} style={{ width: 36, height: 28, border: 'none', cursor: 'pointer' }} />
                                    <span style={{ flex: 1, fontSize: '12px', color: '#64748b' }}>{color}</span>
                                    {(ps.animatedGradient?.colors || []).length > 2 && (
                                        <button className="lpcd-btn-reset" onClick={() => {
                                            const colors = [...(ps.animatedGradient?.colors || [])];
                                            colors.splice(idx, 1);
                                            updateNestedPageSetting('animatedGradient', 'colors', colors);
                                        }} title="Remove">✕</button>
                                    )}
                                </div>
                            ))}
                            {(ps.animatedGradient?.colors || []).length < 5 && (
                                <button className="lpcd-btn lpcd-btn-secondary" style={{ fontSize: '12px', padding: '4px 10px' }} onClick={() => {
                                    const colors = [...(ps.animatedGradient?.colors || ['#667eea', '#764ba2']), '#f64f59'];
                                    updateNestedPageSetting('animatedGradient', 'colors', colors);
                                }}>+ Add Color</button>
                            )}
                        </div>
                        <RangeField label="Angle" value={ps.animatedGradient?.angle || 135} min={0} max={360} unit="°" onChange={(v) => updateNestedPageSetting('animatedGradient', 'angle', v)} />
                        <RangeField label="Speed" value={ps.animatedGradient?.speed || 8} min={2} max={20} unit="s" onChange={(v) => updateNestedPageSetting('animatedGradient', 'speed', v)} />
                    </div>
                )}
                {ps.backgroundType === 'video' && (
                    <div className={!window.lpcdEditor?.isPro ? 'lpcd-pro-locked' : ''}>
                        <SelectField
                            label="Video Source"
                            value={ps.videoSource || 'youtube'}
                            onChange={(v) => updatePageSettings('videoSource', v)}
                            options={[{ value: 'youtube', label: 'YouTube URL' }, { value: 'upload', label: 'Upload MP4' }]}
                        />
                        {(ps.videoSource || 'youtube') === 'youtube' && (
                            <TextField label="YouTube URL" value={ps.videoYoutubeUrl || ''} onChange={(v) => updatePageSettings('videoYoutubeUrl', v)} placeholder="https://www.youtube.com/watch?v=..." />
                        )}
                        {ps.videoSource === 'upload' && (
                            <MediaUploadField label="Upload Video" value={ps.videoUploadUrl || ''} onChange={(v) => updatePageSettings('videoUploadUrl', v)} />
                        )}
                        <ToggleField label="Overlay" value={ps.overlayEnabled} onChange={(v) => updatePageSettings('overlayEnabled', v)} />
                        {ps.overlayEnabled && (
                            <>
                                <ColorField label="Overlay Color" value={ps.overlayColor || '#000000'} onChange={(v) => updatePageSettings('overlayColor', v)} />
                                <RangeField label="Overlay Opacity" value={ps.overlayOpacity || 0.4} min={0} max={1} step={0.05} unit="" onChange={(v) => updatePageSettings('overlayOpacity', v)} />
                            </>
                        )}
                        <MediaUploadField label="Fallback Image (Mobile)" value={ps.videoFallbackImage || ''} onChange={(v) => updatePageSettings('videoFallbackImage', v)} />
                        <p style={{ fontSize: '12px', color: '#64748b', margin: '4px 0 0' }}>Shown on mobile devices or as placeholder while loading.</p>
                        <ToggleField label="Play on Mobile" value={ps.videoPlayOnMobile} onChange={(v) => updatePageSettings('videoPlayOnMobile', v)} />
                        {ps.videoPlayOnMobile && (
                            <p style={{ fontSize: '12px', color: '#64748b', margin: '4px 0 8px' }}>Note: Autoplay on mobile requires the video to be muted.</p>
                        )}
                        <SelectField
                            label="Video Fit"
                            value={ps.videoObjectFit || 'cover'}
                            onChange={(v) => updatePageSettings('videoObjectFit', v)}
                            options={[{ value: 'cover', label: 'Cover (Fill Area)' }, { value: 'contain', label: 'Contain (Show Full Video)' }, { value: 'fill', label: 'Fill (Stretch to Area)' }]}
                        />
                    </div>
                )}
            </Section>

            <Section title="Page Animation">
                <SelectField
                    label="Type"
                    value={ps.pageAnimation?.type}
                    onChange={(v) => updateNestedPageSetting('pageAnimation', 'type', v)}
                    options={[{ value: 'none', label: 'None' }, { value: 'fadeIn', label: 'Fade In' }, { value: 'slideUp', label: 'Slide Up' }, { value: 'zoomIn', label: 'Zoom In' }]}
                />
                {ps.pageAnimation?.type !== 'none' && (
                    <RangeField label="Duration" value={ps.pageAnimation?.duration || 600} min={200} max={1500} unit="ms" onChange={(v) => updateNestedPageSetting('pageAnimation', 'duration', v)} />
                )}
            </Section>

            <Section title="Custom CSS">
                <TextAreaField
                    label="CSS"
                    value={ps.customCss}
                    onChange={(v) => updatePageSettings('customCss', v)}
                    placeholder="/* Applies to login page only */"
                />
            </Section>
        </>
    );
}
