import { useState, useEffect, useCallback, useRef } from '@wordpress/element';

function CustomSelect({ value, onChange, options }) {
    const [open, setOpen] = useState(false);
    const [flipUp, setFlipUp] = useState(false);
    const ref = useRef(null);

    useEffect(() => {
        const handleClick = (e) => {
            if (ref.current && !ref.current.contains(e.target)) setOpen(false);
        };
        document.addEventListener('mousedown', handleClick);
        return () => document.removeEventListener('mousedown', handleClick);
    }, []);

    const handleToggle = () => {
        if (!open && ref.current) {
            const rect = ref.current.getBoundingClientRect();
            const spaceBelow = window.innerHeight - rect.bottom;
            setFlipUp(spaceBelow < 260);
        }
        setOpen(!open);
    };

    const selected = options.find((o) => o.value === value) || options[0];

    return (
        <div className="lpcd-custom-select" ref={ref}>
            <button type="button" className={`lpcd-custom-select-trigger${open ? ' open' : ''}`} onClick={handleToggle}>
                <span>{selected?.label}{selected?.pro && <> <span className="lpcd-pro-pill">PRO</span></>}</span>
                <svg className={`lpcd-custom-select-chevron${open ? ' open' : ''}`} width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9" /></svg>
            </button>
            {open && (
                <div className={`lpcd-custom-select-dropdown${flipUp ? ' flip-up' : ''}`}>
                    {options.map((o) => (
                        <button type="button" key={o.value} className={`lpcd-custom-select-option${o.value === value ? ' selected' : ''}${o.pro && !window.lpcdSettings?.isPro ? ' lpcd-pro-locked' : ''}`} onClick={() => { if (o.pro && !window.lpcdSettings?.isPro) return; onChange(o.value); setOpen(false); }} disabled={o.pro && !window.lpcdSettings?.isPro}>
                            <span>{o.label}{o.pro && <> <span className="lpcd-pro-pill">PRO</span></>}</span>
                            {o.value === value && <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg>}
                        </button>
                    ))}
                </div>
            )}
        </div>
    );
}

const TAB_LABELS = {
    general: 'General Settings',
    security: 'Security Settings',
    messages: 'Messages',
    loginurl: 'Custom Login URL',
    redirects: 'Redirects',
    advanced: 'Advanced',
    importexport: 'Import / Export',
};

const TABS = [
    { key: 'general', label: 'General', icon: 'dashicons-admin-generic' },
    { key: 'security', label: 'Security', icon: 'dashicons-shield' },
    { key: 'messages', label: 'Messages', icon: 'dashicons-format-chat' },
    { key: 'loginurl', label: 'Custom Login URL', icon: 'dashicons-lock' },
    { key: 'redirects', label: 'Redirects', icon: 'dashicons-admin-links' },
    { key: 'advanced', label: 'Advanced', icon: 'dashicons-admin-tools' },
    { key: 'importexport', label: 'Import / Export', icon: 'dashicons-upload' },
];

export default function SettingsApp() {
    const [tab, setTab] = useState('general');
    const [settings, setSettings] = useState({});
    const [isSaving, setIsSaving] = useState(false);
    const [isLoading, setIsLoading] = useState(true);
    const [notice, setNotice] = useState(null);
    const isPro = !!window.lpcdSettings?.isPro;

    const showNotice = useCallback((msg, type = 'success') => {
        setNotice({ msg, type });
        setTimeout(() => setNotice(null), 4000);
    }, []);

    useEffect(() => {
        fetch(`${window.lpcdSettings.restUrl}settings`, {
            headers: { 'X-WP-Nonce': window.lpcdSettings.nonce },
        })
            .then((r) => r.json())
            .then((data) => { setSettings(data); setIsLoading(false); })
            .catch(() => { showNotice('Failed to load settings.', 'error'); setIsLoading(false); });
    }, [showNotice]);

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

    const save = async () => {
        setIsSaving(true);
        try {
            const res = await fetch(`${window.lpcdSettings.restUrl}settings`, {
                method: 'PUT',
                headers: { 'X-WP-Nonce': window.lpcdSettings.nonce, 'Content-Type': 'application/json' },
                body: JSON.stringify(settings),
            });
            const data = await res.json();
            if (res.ok) {
                setSettings(data.settings);
                if (!data.settings.pluginEnabled && tab !== 'general') {
                    showNotice('Settings saved, but they won\u2019t take effect because the plugin is disabled. Go to the General tab and enable the plugin first.', 'warning');
                } else {
                    showNotice('Settings saved!');
                }
            } else {
                throw new Error(data.message || 'Save failed.');
            }
        } catch (err) {
            showNotice(err.message, 'error');
        }
        setIsSaving(false);
    };

    const verifyRecaptcha = async () => {
        try {
            const res = await fetch(`${window.lpcdSettings.restUrl}verify-recaptcha`, {
                method: 'POST',
                headers: { 'X-WP-Nonce': window.lpcdSettings.nonce, 'Content-Type': 'application/json' },
                body: JSON.stringify({ siteKey: settings.recaptchaSiteKey, secretKey: settings.recaptchaSecretKey }),
            });
            const data = await res.json();
            showNotice(data.message, data.success ? 'success' : 'error');
        } catch {
            showNotice('Verification failed.', 'error');
        }
    };

    if (isLoading) {
        return <div className="lpcd-settings-loading"><div className="lpcd-loading-spinner" /><p>Loading settings...</p></div>;
    }

    return (
        <div className="lpcd-settings-app">
            {/* Sidebar */}
            <div className="lpcd-settings-nav">
                <div className="lpcd-settings-nav-brand">
                    <div className="lpcd-settings-nav-brand-icon">
                        <span className="dashicons dashicons-shield" />
                    </div>
                    <div className="lpcd-settings-nav-brand-text">
                        <h1>LoginCraft</h1>
                        <span>v{window.lpcdSettings?.version || '1.0.0'}</span>
                    </div>
                </div>
                <div className="lpcd-settings-nav-tabs">
                    {TABS.map((t) => (
                        <button key={t.key} className={`lpcd-settings-tab ${tab === t.key ? 'active' : ''}`} onClick={() => setTab(t.key)}>
                            <span className={`dashicons ${t.icon}`} /> {t.label}
                        </button>
                    ))}
                </div>
            </div>

            {/* Main */}
            <div className="lpcd-settings-main">
                <div className="lpcd-settings-header">
                    <h2>{TAB_LABELS[tab] || 'Settings'}</h2>
                    <button className="lpcd-btn lpcd-btn-primary" onClick={save} disabled={isSaving}>
                        {isSaving ? 'Saving...' : 'Save Changes'}
                    </button>
                </div>

                <div className="lpcd-settings-content">
                    {notice && (
                        <div className={`lpcd-notice lpcd-notice-${notice.type}`}>{notice.msg}</div>
                    )}
                    {tab === 'general' && <GeneralTab s={settings} u={update} />}
                    {tab === 'security' && <SecurityTab s={settings} u={update} onVerify={verifyRecaptcha} />}
                    {tab === 'messages' && <MessagesTab s={settings} u={update} />}
                    {tab === 'loginurl' && <LoginUrlTab s={settings} u={update} isPro={isPro} />}
                    {tab === 'redirects' && <RedirectsTab s={settings} u={update} isPro={isPro} />}
                    {tab === 'advanced' && <AdvancedTab s={settings} u={update} isPro={isPro} />}
                    {tab === 'importexport' && <ImportExportTab setSettings={setSettings} />}
                </div>
            </div>
        </div>
    );
}

function Card({ title, children }) {
    return (
        <div className="lpcd-section">
            <h3 className="lpcd-section-title">{title}</h3>
            <div className="lpcd-card">{children}</div>
        </div>
    );
}

function FormField({ label, children, desc }) {
    return (
        <div className="lpcd-form-field">
            <div>
                <label>{label}</label>
                {desc && <p className="lpcd-field-desc">{desc}</p>}
            </div>
            <div className="lpcd-field-input-wrap">
                {children}
            </div>
        </div>
    );
}

function Toggle({ label, checked, onChange, desc, disabled }) {
    return (
        <div className={`lpcd-form-field${disabled ? ' lpcd-pro-locked' : ''}`}>
            <div>
                <label>{label}</label>
                {desc && <p className="lpcd-field-desc">{desc}</p>}
            </div>
            <label className="lpcd-toggle">
                <input type="checkbox" checked={!!checked} onChange={(e) => !disabled && onChange(e.target.checked)} disabled={disabled} />
                <span className="lpcd-toggle-slider" />
            </label>
        </div>
    );
}

function MediaUploadField({ 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 (
        <div className="lpcd-media-upload">
            {value ? (
                <div className="lpcd-media-preview">
                    <img src={value} alt="Preview" />
                    <button type="button" className="lpcd-media-remove" onClick={() => onChange('')} title="Remove">
                        <span className="dashicons dashicons-no-alt" />
                    </button>
                </div>
            ) : (
                <div className="lpcd-media-placeholder" onClick={openMediaBrowser}>
                    <span className="dashicons dashicons-format-image" />
                </div>
            )}
            <button type="button" className="lpcd-btn lpcd-btn-secondary" onClick={openMediaBrowser}>
                Upload Icon
            </button>
        </div>
    );
}

function GeneralTab({ s, u }) {
    return (
        <>
            <Card title="Plugin Status">
                <Toggle label="Enable Plugin" checked={s.pluginEnabled} onChange={(v) => u('pluginEnabled', v)} desc="When disabled, the login page renders with default WordPress styles." />
            </Card>
            <Card title="Login Page">
                <FormField label="Page Title">
                    <input className="lpcd-input" value={s.loginPageTitle || ''} onChange={(e) => u('loginPageTitle', e.target.value)} placeholder="Custom browser tab title" />
                </FormField>
                <FormField label="Custom Favicon URL">
                    <MediaUploadField value={s.customFavicon} onChange={(v) => u('customFavicon', v)} />
                </FormField>
            </Card>
            <Card title="Back to Blog Link">
                <Toggle label="Show Link" checked={s.showBackToBlogLink} onChange={(v) => u('showBackToBlogLink', v)} />
                {s.showBackToBlogLink && (
                    <>
                        <FormField label="Custom Text">
                            <input className="lpcd-input" value={s.backToBlogText || ''} onChange={(e) => u('backToBlogText', e.target.value)} placeholder="← Back to site" />
                        </FormField>
                        <FormField label="Custom URL">
                            <input className="lpcd-input" value={s.backToBlogUrl || ''} onChange={(e) => u('backToBlogUrl', e.target.value)} placeholder="https://..." />
                        </FormField>
                    </>
                )}
            </Card>
        </>
    );
}

function SecurityTab({ s, u, onVerify }) {
    return (
        <>
            <Card title="CAPTCHA">
                <FormField label="Provider">
                    <CustomSelect value={s.captchaProvider || 'none'} onChange={(v) => u('captchaProvider', v)} options={[
                        { value: 'none', label: 'None' },
                        { value: 'recaptcha_v2', label: 'Google reCAPTCHA v2', pro: true },
                        { value: 'recaptcha_v3', label: 'Google reCAPTCHA v3', pro: true },
                        { value: 'hcaptcha', label: 'hCaptcha', pro: true },
                        { value: 'turnstile', label: 'Cloudflare Turnstile', pro: true },
                    ]} />
                </FormField>
                {s.captchaProvider === 'recaptcha_v2' && (
                    <>
                        <FormField label="Site Key">
                            <input className="lpcd-input" value={s.recaptchaSiteKey || ''} onChange={(e) => u('recaptchaSiteKey', e.target.value)} />
                        </FormField>
                        <FormField label="Secret Key">
                            <input className="lpcd-input" type="password" value={s.recaptchaSecretKey || ''} onChange={(e) => u('recaptchaSecretKey', e.target.value)} />
                        </FormField>
                        <FormField label="Theme">
                            <CustomSelect value={s.recaptchaTheme || 'light'} onChange={(v) => u('recaptchaTheme', v)} options={[
                                { value: 'light', label: 'Light' },
                                { value: 'dark', label: 'Dark' },
                            ]} />
                        </FormField>
                        <FormField label="Size">
                            <CustomSelect value={s.recaptchaSize || 'normal'} onChange={(v) => u('recaptchaSize', v)} options={[
                                { value: 'normal', label: 'Normal' },
                                { value: 'compact', label: 'Compact' },
                            ]} />
                        </FormField>
                        <Toggle label="Show on Login" checked={s.recaptchaOnLogin} onChange={(v) => u('recaptchaOnLogin', v)} />
                        <Toggle label="Show on Lost Password" checked={s.recaptchaOnLostPw} onChange={(v) => u('recaptchaOnLostPw', v)} />
                        <button className="lpcd-btn lpcd-btn-secondary" onClick={onVerify} style={{ marginTop: '8px' }}>Verify Keys</button>
                    </>
                )}
                {s.captchaProvider === 'recaptcha_v3' && (
                    <>
                        <FormField label="Site Key">
                            <input className="lpcd-input" value={s.recaptchaV3SiteKey || ''} onChange={(e) => u('recaptchaV3SiteKey', e.target.value)} />
                        </FormField>
                        <FormField label="Secret Key">
                            <input className="lpcd-input" type="password" value={s.recaptchaV3SecretKey || ''} onChange={(e) => u('recaptchaV3SecretKey', e.target.value)} />
                        </FormField>
                        <FormField label="Score Threshold" desc="Score between 0.0 (bot) and 1.0 (human). Default: 0.5">
                            <input className="lpcd-input" value={s.recaptchaV3Threshold || '0.5'} onChange={(e) => u('recaptchaV3Threshold', e.target.value)} placeholder="0.5" />
                        </FormField>
                        <Toggle label="Show on Login" checked={s.recaptchaV3OnLogin} onChange={(v) => u('recaptchaV3OnLogin', v)} />
                        <Toggle label="Show on Lost Password" checked={s.recaptchaV3OnLostPw} onChange={(v) => u('recaptchaV3OnLostPw', v)} />
                    </>
                )}
                {s.captchaProvider === 'hcaptcha' && (
                    <>
                        <FormField label="Site Key">
                            <input className="lpcd-input" value={s.hcaptchaSiteKey || ''} onChange={(e) => u('hcaptchaSiteKey', e.target.value)} />
                        </FormField>
                        <FormField label="Secret Key">
                            <input className="lpcd-input" type="password" value={s.hcaptchaSecretKey || ''} onChange={(e) => u('hcaptchaSecretKey', e.target.value)} />
                        </FormField>
                        <FormField label="Theme">
                            <CustomSelect value={s.hcaptchaTheme || 'light'} onChange={(v) => u('hcaptchaTheme', v)} options={[
                                { value: 'light', label: 'Light' },
                                { value: 'dark', label: 'Dark' },
                            ]} />
                        </FormField>
                        <Toggle label="Show on Login" checked={s.hcaptchaOnLogin} onChange={(v) => u('hcaptchaOnLogin', v)} />
                        <Toggle label="Show on Lost Password" checked={s.hcaptchaOnLostPw} onChange={(v) => u('hcaptchaOnLostPw', v)} />
                    </>
                )}
                {s.captchaProvider === 'turnstile' && (
                    <>
                        <FormField label="Site Key">
                            <input className="lpcd-input" value={s.turnstileSiteKey || ''} onChange={(e) => u('turnstileSiteKey', e.target.value)} />
                        </FormField>
                        <FormField label="Secret Key">
                            <input className="lpcd-input" type="password" value={s.turnstileSecretKey || ''} onChange={(e) => u('turnstileSecretKey', e.target.value)} />
                        </FormField>
                        <FormField label="Theme">
                            <CustomSelect value={s.turnstileTheme || 'auto'} onChange={(v) => u('turnstileTheme', v)} options={[
                                { value: 'auto', label: 'Auto' },
                                { value: 'light', label: 'Light' },
                                { value: 'dark', label: 'Dark' },
                            ]} />
                        </FormField>
                        <Toggle label="Show on Login" checked={s.turnstileOnLogin} onChange={(v) => u('turnstileOnLogin', v)} />
                        <Toggle label="Show on Lost Password" checked={s.turnstileOnLostPw} onChange={(v) => u('turnstileOnLostPw', v)} />
                    </>
                )}
            </Card>
            <Card title="Error Messages">
                <Toggle label="Generic Error Messages" checked={s.genericErrorMessages} onChange={(v) => u('genericErrorMessages', v)} desc='When enabled, all login errors show "Invalid username or password." for security.' />
            </Card>
        </>
    );
}

function MessagesTab({ s, u }) {
    const fields = [
        { key: 'wrongPasswordMessage', label: 'Wrong Password', def: 'The password you entered for that username is incorrect.' },
        { key: 'invalidUsernameMessage', label: 'Invalid Username', def: 'No account found with that username.' },
        { key: 'invalidEmailMessage', label: 'Invalid Email', def: 'No account found with that email address.' },
        { key: 'emptyUsernameMessage', label: 'Empty Username', def: 'Please enter your username or email address.' },
        { key: 'emptyPasswordMessage', label: 'Empty Password', def: 'Please enter your password.' },
        { key: 'captchaFailedMessage', label: 'CAPTCHA Failed', def: 'CAPTCHA verification failed. Please try again.' },
        { key: 'logoutSuccessMessage', label: 'Logout Success', def: 'You have been logged out.' },
        { key: 'passwordResetSentMessage', label: 'Password Reset Sent', def: 'A password reset link has been sent to your email.' },
    ];

    return (
        <Card title="Custom Login Messages">
            {fields.map((f) => (
                <FormField key={f.key} label={f.label}>
                    <div className="lpcd-message-field">
                        <input className="lpcd-input" value={s[f.key] || ''} onChange={(e) => u(f.key, e.target.value)} placeholder={f.def} />
                        <button className="lpcd-btn-reset" onClick={() => u(f.key, f.def)} title="Reset to default">↺</button>
                    </div>
                </FormField>
            ))}
        </Card>
    );
}

function LoginUrlTab({ s, u, isPro }) {
    return (
        <Card title={<>Custom Login URL <span className="lpcd-pro-pill">PRO</span></>}>
            {!isPro && <div className="lpcd-pro-notice-inline"><span className="dashicons dashicons-lock" /> This feature requires a Pro license. <a href="#">Upgrade Now</a></div>}
            <Toggle label="Enable Custom Login URL" checked={s.enableCustomLogin} onChange={(v) => isPro && u('enableCustomLogin', v)} desc="Turn on to hide default wp-login.php and use a custom link." disabled={!isPro} />

            {s.enableCustomLogin && (
                <>
                    <FormField label="Custom Login Slug" desc="Example: my-login. Use only lowercase letters, numbers, and hyphens.">
                        <input className="lpcd-input" value={s.customLoginSlug || ''} onChange={(e) => u('customLoginSlug', e.target.value)} placeholder="my-login" />
                    </FormField>

                    <FormField label="Default Login URL Redirect" desc="Where should visitors be sent if they try to access wp-login.php?">
                        <CustomSelect value={s.defaultLoginRedirectType || '404'} onChange={(v) => u('defaultLoginRedirectType', v)} options={[
                            { value: '404', label: 'Show 404 Error (Recommended)' },
                            { value: 'homepage', label: 'Homepage' },
                            { value: 'custom', label: 'Custom URL' },
                        ]} />
                    </FormField>

                    {s.defaultLoginRedirectType === 'custom' && (
                        <FormField label="Custom Redirect URL">
                            <input className="lpcd-input" value={s.defaultLoginRedirectUrl || ''} onChange={(e) => u('defaultLoginRedirectUrl', e.target.value)} placeholder="https://..." />
                        </FormField>
                    )}

                    {s.customLoginSlug && (
                        <div style={{ padding: '8px 12px', background: '#fef3c7', borderRadius: '4px', fontSize: '12px', color: '#92400e', marginBottom: '8px', marginTop: '12px' }}>
                            Your new login page will be at: <strong>{window.location.origin}/{s.customLoginSlug}</strong>
                        </div>
                    )}
                </>
            )}
        </Card>
    );
}

function RedirectsTab({ s, u, isPro }) {
    return (
        <>
            <Card title="After Login Redirect">
                <FormField label="Redirect To">
                    <CustomSelect value={s.loginRedirectType || 'default'} onChange={(v) => u('loginRedirectType', v)} options={[
                        { value: 'default', label: 'WordPress Default' },
                        { value: 'homepage', label: 'Homepage', pro: true },
                        { value: 'custom', label: 'Custom URL', pro: true },
                    ]} />
                </FormField>
                {s.loginRedirectType === 'custom' && (
                    <FormField label="Custom URL">
                        <input className="lpcd-input" value={s.loginRedirectUrl || ''} onChange={(e) => u('loginRedirectUrl', e.target.value)} placeholder="https://..." />
                    </FormField>
                )}
            </Card>
            <Card title="After Registration Redirect">
                <FormField label="Redirect To">
                    <CustomSelect value={s.registrationRedirectType || 'default'} onChange={(v) => u('registrationRedirectType', v)} options={[
                        { value: 'default', label: 'WordPress Default' },
                        { value: 'homepage', label: 'Homepage', pro: true },
                        { value: 'custom', label: 'Custom URL', pro: true },
                    ]} />
                </FormField>
                {s.registrationRedirectType === 'custom' && (
                    <FormField label="Custom URL">
                        <input className="lpcd-input" value={s.registrationRedirectUrl || ''} onChange={(e) => u('registrationRedirectUrl', e.target.value)} placeholder="https://..." />
                    </FormField>
                )}
            </Card>
        </>
    );
}

function AdvancedTab({ s, u, isPro }) {
    return (
        <>
            <Card title="Global Custom CSS">
                <FormField label="CSS Code" desc="This CSS is applied on the login page in addition to your template styles.">
                    <textarea className="lpcd-textarea" rows={8} value={s.globalCustomCss || ''} onChange={(e) => u('globalCustomCss', e.target.value)} placeholder="/* Your custom CSS here */" style={{ fontFamily: 'monospace', fontSize: '13px' }} />
                </FormField>
            </Card>
            <Card title={<>Custom JavaScript <span className="lpcd-pro-pill">PRO</span></>}>
                {!isPro && <div className="lpcd-pro-notice-inline"><span className="dashicons dashicons-lock" /> This feature requires a Pro license. <a href="#">Upgrade Now</a></div>}
                <FormField label="Head JS" desc="JavaScript injected into the login page <head>. Use with caution.">
                    <textarea className="lpcd-textarea" rows={5} value={s.customJsHead || ''} onChange={(e) => isPro && u('customJsHead', e.target.value)} placeholder="// JS for <head>" style={{ fontFamily: 'monospace', fontSize: '13px' }} disabled={!isPro} />
                </FormField>
                <FormField label="Footer JS" desc="JavaScript injected before the closing </body> tag on the login page.">
                    <textarea className="lpcd-textarea" rows={5} value={s.customJsFooter || ''} onChange={(e) => isPro && u('customJsFooter', e.target.value)} placeholder="// JS for footer" style={{ fontFamily: 'monospace', fontSize: '13px' }} disabled={!isPro} />
                </FormField>
            </Card>
            <Card title={<>WooCommerce <span className="lpcd-pro-pill">PRO</span></>}>
                {!isPro && <div className="lpcd-pro-notice-inline"><span className="dashicons dashicons-lock" /> This feature requires a Pro license. <a href="#">Upgrade Now</a></div>}
                <Toggle label={<>Enable WooCommerce Support <span className="lpcd-pro-pill">PRO</span></>} checked={s.woocommerceEnabled} onChange={(v) => isPro && u('woocommerceEnabled', v)} desc="When enabled, WooCommerce My Account login/registration will use your custom login page design." disabled={!isPro} />
            </Card>
        </>
    );
}

function ImportExportTab({ setSettings }) {
    const apiBase = `${window.lpcdSettings?.restUrl || '/wp-json/lpcd/v1'}`;
    const nonce = window.lpcdSettings?.nonce || '';

    const headers = { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce };

    const doExport = async (type) => {
        try {
            const resp = await fetch(`${apiBase}/export/${type}`, { headers: { 'X-WP-Nonce': nonce } });
            const data = await resp.json();
            const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `lpcd-${type}-export.json`;
            a.click();
            URL.revokeObjectURL(url);
        } catch (e) {
            alert('Export failed: ' + e.message);
        }
    };

    const doImport = async (type, file) => {
        try {
            const text = await file.text();
            const json = JSON.parse(text);
            const resp = await fetch(`${apiBase}/import/${type}`, { method: 'POST', headers, body: JSON.stringify(json) });
            const data = await resp.json();
            alert(data.message || 'Import complete.');
        } catch (e) {
            alert('Import failed: ' + e.message);
        }
    };

    const doReset = async () => {
        if (!window.confirm('Are you sure you want to reset ALL settings to defaults? This cannot be undone.')) return;
        try {
            const resp = await fetch(`${apiBase}/reset-settings`, { method: 'POST', headers });
            const data = await resp.json();
            if (data.settings) setSettings(data.settings);
            alert(data.message || 'Reset complete.');
        } catch (e) {
            alert('Reset failed: ' + e.message);
        }
    };

    return (
        <>
            <Card title="Export">
                <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
                    <button className="lpcd-btn lpcd-btn-secondary" onClick={() => doExport('template')}>
                        <span className="dashicons dashicons-download" style={{ marginRight: '4px' }} /> Export Active Template
                    </button>
                    <button className="lpcd-btn lpcd-btn-secondary" onClick={() => doExport('settings')}>
                        <span className="dashicons dashicons-download" style={{ marginRight: '4px' }} /> Export Settings
                    </button>
                </div>
            </Card>
            <Card title="Import">
                <FormField label="Import Template" desc="Upload a previously exported template JSON file.">
                    <input type="file" accept=".json" onChange={(e) => { if (e.target.files[0]) doImport('template', e.target.files[0]); }} />
                </FormField>
                <FormField label="Import Settings" desc="Upload a previously exported settings JSON file.">
                    <input type="file" accept=".json" onChange={(e) => { if (e.target.files[0]) doImport('settings', e.target.files[0]); }} />
                </FormField>
            </Card>
            <Card title="Reset">
                <p style={{ marginBottom: '12px', color: '#64748b' }}>Reset all plugin settings to their default values. Templates are not affected.</p>
                <button className="lpcd-btn" style={{ background: '#dc2626', color: '#fff', border: 'none' }} onClick={doReset}>
                    Reset All Settings
                </button>
            </Card>
        </>
    );
}
