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

export default function LivePreview() {
    const selectedTemplateId = useEditorStore((s) => s.selectedTemplateId);
    const activeTemplateId = useEditorStore((s) => s.activeTemplateId);
    const templates = useEditorStore((s) => s.templates);
    const devicePreview = useEditorStore((s) => s.devicePreview);
    const sidebarOpen = useEditorStore((s) => s.sidebarOpen);
    const setDevicePreview = useEditorStore((s) => s.setDevicePreview);
    const toggleSidebar = useEditorStore((s) => s.toggleSidebar);
    const activateTemplate = useEditorStore((s) => s.activateTemplate);
    const enterEditor = useEditorStore((s) => s.enterEditor);

    const selectedTemplate = useMemo(
        () => templates.find((t) => t.id === selectedTemplateId),
        [templates, selectedTemplateId]
    );

    const previewUrl = useMemo(() => {
        if (!selectedTemplateId) return '';
        return `${window.lpcdEditor.loginUrl}?lpcd_preview=1&template_id=${selectedTemplateId}&preview_token=${window.lpcdEditor.previewNonce}`;
    }, [selectedTemplateId]);

    const deviceWidths = {
        desktop: '100%',
        tablet: '768px',
        mobile: '375px',
    };

    return (
        <div className="lpcd-preview-panel">
            <div className="lpcd-preview-toolbar">
                <div className="lpcd-preview-left">
                    <button
                        className="lpcd-btn lpcd-btn-icon"
                        onClick={toggleSidebar}
                        title={sidebarOpen ? 'Collapse sidebar' : 'Expand sidebar'}
                    >
                        <span className={`dashicons ${sidebarOpen ? 'dashicons-arrow-left-alt2' : 'dashicons-arrow-right-alt2'}`} />
                    </button>
                    {selectedTemplate && (
                        <span className="lpcd-preview-template-name">
                            {selectedTemplate.name}
                        </span>
                    )}
                </div>

                <div className="lpcd-preview-center">
                    <div className="lpcd-device-toggle">
                        {['desktop', 'tablet', 'mobile'].map((device) => (
                            <button
                                key={device}
                                className={`lpcd-device-btn ${devicePreview === device ? 'active' : ''}`}
                                onClick={() => setDevicePreview(device)}
                                title={device.charAt(0).toUpperCase() + device.slice(1)}
                            >
                                <span className={`dashicons dashicons-${device === 'desktop' ? 'desktop' : device === 'tablet' ? 'tablet' : 'smartphone'}`} />
                            </button>
                        ))}
                    </div>
                </div>

                <div className="lpcd-preview-right">
                {selectedTemplate && (() => {
                    const FREE_NAMES = ['Light Centered', 'Dark Centered'];
                    const isProTpl = !FREE_NAMES.includes(selectedTemplate.name) && selectedTemplate.type !== 'custom';
                    const userIsPro = !!window.lpcdEditor?.isPro;
                    const locked = isProTpl && !userIsPro;

                    return (
                        <>
                            <button
                                className="lpcd-btn lpcd-btn-secondary"
                                onClick={() => !locked && enterEditor(selectedTemplateId)}
                                disabled={locked}
                                title={locked ? 'Upgrade to Pro to edit this template' : 'Edit template'}
                                style={locked ? { opacity: 0.6 } : {}}
                            >
                                {locked ? '🔒 Upgrade to Edit' : <><span className="dashicons dashicons-edit" /> Edit</>}
                            </button>
                            <button
                                className={`lpcd-btn ${activeTemplateId === selectedTemplateId ? 'lpcd-btn-success' : 'lpcd-btn-primary'}`}
                                onClick={() => !locked && activateTemplate(selectedTemplateId)}
                                disabled={locked || activeTemplateId === selectedTemplateId}
                                title={locked ? 'Upgrade to Pro to activate this template' : 'Activate template'}
                                style={locked ? { opacity: 0.6 } : {}}
                            >
                                {locked ? '🔒 Upgrade to Activate' : (activeTemplateId === selectedTemplateId ? '✓ Active' : 'Activate')}
                            </button>
                        </>
                    );
                })()}
                </div>
            </div>

            <div className="lpcd-preview-container">
                {previewUrl ? (
                    <div className="lpcd-iframe-wrap" style={{ maxWidth: deviceWidths[devicePreview] }}>
                        <iframe
                            key={selectedTemplateId}
                            src={previewUrl}
                            title="Login Preview"
                            className="lpcd-preview-iframe"
                        />
                    </div>
                ) : (
                    <div className="lpcd-preview-empty">
                        <span className="dashicons dashicons-visibility" />
                        <p>Select a template to preview</p>
                    </div>
                )}
            </div>
        </div>
    );
}
