import { useState } from '@wordpress/element';
import useEditorStore from '../store/useEditorStore';
export default function TemplateSidebar() {
    const templates = useEditorStore((s) => s.templates);
    const selectedTemplateId = useEditorStore((s) => s.selectedTemplateId);
    const activeTemplateId = useEditorStore((s) => s.activeTemplateId);
    const selectTemplate = useEditorStore((s) => s.selectTemplate);
    const createBlankTemplate = useEditorStore((s) => s.createBlankTemplate);
    const deleteTemplate = useEditorStore((s) => s.deleteTemplate);
    const sidebarOpen = useEditorStore((s) => s.sidebarOpen);

    const [search, setSearch] = useState('');
    const [hoveredId, setHoveredId] = useState(null);
    const [showCustomModal, setShowCustomModal] = useState(false);

    // Only these two templates are free — everything else gets a Pro badge.
    const FREE_NAMES = ['Light Centered', 'Dark Centered'];
    const isFreeTemplate = (t) => FREE_NAMES.includes(t.name) || t.type === 'custom';

    const filtered = templates
        .filter((t) => t.name.toLowerCase().includes(search.toLowerCase()))
        .sort((a, b) => {
            const aFree = isFreeTemplate(a) ? 0 : 1;
            const bFree = isFreeTemplate(b) ? 0 : 1;
            return aFree - bFree;
        });

    if (!sidebarOpen) return null;

    return (
        <div className="lpcd-sidebar">
            <div className="lpcd-sidebar-header">
                <h2>Templates</h2>
                <button
                    className="lpcd-create-blank-btn"
                    onClick={createBlankTemplate}
                >
                    <span className="dashicons dashicons-plus-alt2" />
                    Create Your Own
                </button>
            </div>

            <div className="lpcd-sidebar-filters">
                <input
                    type="text"
                    className="lpcd-search-input"
                    placeholder="Search templates..."
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                />
            </div>

            <div className="lpcd-template-grid">
                {filtered.map((template) => {
                    const isPro = !isFreeTemplate(template);
                    return (
                        <div
                            key={template.id}
                            className={`lpcd-template-card ${selectedTemplateId === template.id ? 'selected' : ''}`}
                            onMouseEnter={() => setHoveredId(template.id)}
                            onMouseLeave={() => setHoveredId(null)}
                            onClick={() => selectTemplate(template.id)}
                        >
                            <div className="lpcd-template-thumb">
                                <img src={`${window.lpcdEditor.pluginUrl}img/previews/${template.name.replace(/\s+/g, '-')}.webp`} alt={template.name} className="lpcd-template-img" />
                                {activeTemplateId === template.id && (
                                    <span className="lpcd-badge-active">Active</span>
                                )}
                                {isPro && (
                                    <span className="lpcd-badge-pro">
                                        <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M12 1l3.09 4.26L20 6.27l-2.18 4.32L18.18 16 12 14.14 5.82 16l.36-5.41L4 6.27l4.91-1.01L12 1z" /><path d="M10 14.2l-3.5-3.5 1.41-1.41L10 11.38l5.09-5.09 1.41 1.41L10 14.2z" fill="rgba(255,255,255,0.9)" /></svg>
                                        PRO
                                    </span>
                                )}
                                {template.type === 'advanced' && (
                                    <span className="lpcd-badge-type" style={{ position: 'absolute', top: '6px', left: '6px', background: '#7c3aed', color: '#fff', fontSize: '9px', fontWeight: '700', padding: '2px 6px', borderRadius: '8px', zIndex: 2 }}>✦</span>
                                )}
                                {hoveredId === template.id && (
                                    <div className="lpcd-template-overlay">
                                        <button
                                            className="lpcd-btn lpcd-btn-light lpcd-btn-sm"
                                            onClick={(e) => {
                                                e.stopPropagation();
                                                selectTemplate(template.id);
                                            }}
                                        >
                                            Preview
                                        </button>
                                    </div>
                                )}
                            </div>
                            <div className="lpcd-template-info">
                                <span className="lpcd-template-name">{template.name}</span>
                                {template.type === 'custom' && (
                                    <button
                                        className="lpcd-template-delete"
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            if (window.confirm('Delete this template?')) {
                                                deleteTemplate(template.id);
                                            }
                                        }}
                                        title="Delete"
                                    >
                                        <span className="dashicons dashicons-trash" />
                                    </button>
                                )}
                            </div>
                        </div>
                    );
                })}

                <div className="lpcd-sidebar-footer">
                    <button
                        className="lpcd-custom-design-btn"
                        onClick={() => setShowCustomModal(true)}
                    >
                        <span className="dashicons dashicons-art" />
                        Customized Login Page
                    </button>
                </div>
            </div>

            {showCustomModal && (
                <div className="lpcd-modal-overlay">
                    <div className="lpcd-modal">
                        <button className="lpcd-modal-close" onClick={() => setShowCustomModal(false)}>
                            <span className="dashicons dashicons-no-alt" />
                        </button>
                        <div className="lpcd-modal-content lpcd-custom-design-modal">
                            <div className="lpcd-custom-design-icon">
                                <span className="dashicons dashicons-art" />
                            </div>
                            <h3>Need a Custom Design?</h3>
                            <p>
                                If you are a <strong>PRO</strong> user, you can easily contact us and we will create a completely custom login page design tailored exactly to your brand and website!
                            </p>
                            <div className="lpcd-modal-actions">
                                <a href="https://wordpress.org/plugins/login-page-customizer-and-designer/" target="_blank" rel="noopener noreferrer" className="lpcd-btn lpcd-btn-primary lpcd-btn-large">
                                    Upgrade Now
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
