/**
 * Shois Chat Button — Templates Library Page
 *
 * Grid of template cards with preview thumbnails, active indicator,
 * and duplicate/edit/delete actions.
 *
 * @package ShoisChatButton
 */
import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { TEMPLATE_DEFAULTS } from './TemplateEditor';

/**
 * Template definitions with metadata.
 */
const BUILT_IN_TEMPLATES = [
    { slug: 'classic-green', name: __('Classic Green', 'shois-chat-button'), color: '#5170ff', type: 'bubble', image: 'Classic-Green.webp' },
    { slug: 'gradient-sunset', name: __('Gradient Sunset', 'shois-chat-button'), color: '#f97316', type: 'bubble', image: 'Gradient-Sunset.webp' },
    { slug: 'minimal-white', name: __('Minimal White', 'shois-chat-button'), color: '#0f172a', type: 'bubble', image: 'Minimal-White.webp' },
    { slug: 'ivory-prism', name: __('Ivory Prism', 'shois-chat-button'), color: '#FF5C3A', type: 'bubble', image: 'Ivory-Prism.webp' },
    { slug: 'soft', name: __('Soft Minimal', 'shois-chat-button'), color: '#111111', type: 'bubble', image: 'Soft-Minimal.webp' },
    { slug: 'sticker-board', name: __('Sticker Board', 'shois-chat-button'), color: '#FFE566', type: 'bubble', image: 'Sticker-Board.webp' },
    { slug: 'bubblegum', name: __('Bubblegum Morphic', 'shois-chat-button'), color: '#FF6B9D', type: 'bubble', image: 'Bubblegum-Morphic.webp' },
    { slug: 'dark-elegance', name: __('Dark Elegance', 'shois-chat-button'), color: '#8b5cf6', type: 'bubble', image: 'Dark-Elegance.webp' },
    { slug: 'ink', name: __('Ink Drop', 'shois-chat-button'), color: '#111111', type: 'bubble', image: 'Ink-Drop.webp' },
    { slug: 'fold', name: __('Paper Fold', 'shois-chat-button'), color: '#D97706', type: 'bubble', image: 'Paper-Fold.webp' },
    { slug: 'vinyl', name: __('Vinyl Record', 'shois-chat-button'), color: '#E8C547', type: 'bubble', image: 'Vinyl-Record.webp' },
];

/**
 * Single template card.
 *
 * @param {Object}   props          Component props.
 * @param {Object}   props.template Template object.
 * @param {boolean}  props.isActive Whether this is the active template.
 * @param {Function} props.onSelect Select handler.
 * @param {Function} props.onEdit   Edit handler.
 * @return {JSX.Element} Template card element.
 */
function TemplateCard({ template, isActive, onSelect, onEdit }) {
    const isProTemplate = !['classic-green', 'gradient-sunset', 'minimal-white', 'ivory-prism', 'soft'].includes(template.slug);
    const isProUser = window.shcbAdmin?.isPro || false;
    const isLocked = isProTemplate && !isProUser;

    const handleActionClick = (e, actionFn) => {
        if (isLocked) {
            e.preventDefault();
            e.stopPropagation();
            window.dispatchEvent(new CustomEvent('shcb-pro-alert'));
        } else {
            actionFn();
        }
    };

    return (
        <div className={`shcb-tpl-card ${isLocked ? 'shcb-pro-locked' : ''}`} data-slug={template.slug} style={isLocked ? { opacity: 0.8 } : {}}>
            <div
                className="shcb-tpl-card-preview"
                style={{ '--tpl-color': template.color }}
            >
                <div className="shcb-tpl-preview-image">
                    {template.image ? (
                        <img 
                            src={`${window.shcbAdmin?.pluginUrl || '/'}assets/thumbnails/${template.image}`} 
                            alt={template.name}
                            className="shcb-tpl-thumbnail-img"
                        />
                    ) : (
                        <div className="shcb-tpl-preview-mock">
                            <div className="shcb-tpl-mock-avatar" />
                            <div className="shcb-tpl-mock-line-1" />
                            <div className="shcb-tpl-mock-btn">
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="white">
                                    <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
                                </svg>
                            </div>
                        </div>
                    )}
                </div>
            </div>
            <div className="shcb-tpl-card-info">
                <h4 className="shcb-tpl-card-name">
                    {template.name}
                    {isProTemplate && (
                        <span className="shcb-pro-badge">PRO</span>
                    )}
                </h4>
            </div>
            <div className="shcb-tpl-card-actions">
                <button
                    className="shcb-tpl-btn-customize"
                    onClick={(e) => handleActionClick(e, () => onEdit(template))}
                    type="button"
                >
                    {__('Customize', 'shois-chat-button')}
                </button>
                {isActive ? (
                    <span className="shcb-tpl-active-status">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                            <polyline points="20 6 9 17 4 12"></polyline>
                        </svg>
                        {__('Currently Active', 'shois-chat-button')}
                    </span>
                ) : (
                    <button
                        className="shcb-tpl-btn-activate"
                        onClick={(e) => handleActionClick(e, () => onSelect(template.slug))}
                        type="button"
                    >
                        {__('Activate', 'shois-chat-button')}
                    </button>
                )}
            </div>
        </div>
    );
}

/**
 * TemplatesPage — template library with grid layout.
 *
 * @param {Object}   props            Component props.
 * @param {Function} props.onEditTemplate Handler to open the template editor.
 * @return {JSX.Element} Templates page.
 */
export default function TemplatesPage({ onEditTemplate }) {
    const [activeSlug, setActiveSlug] = useState('classic-green');
    const [saving, setSaving] = useState(false);

    useEffect(() => {
        apiFetch({ path: '/shois-chat/v1/settings' })
            .then((data) => {
                if (data && data.active_template_slug) {
                    setActiveSlug(data.active_template_slug);
                }
            })
            .catch(() => { });
    }, []);

    const handleActivate = (slug) => {
        setSaving(true);

        // Build a fresh template_config from the new template's defaults
        // so the frontend immediately picks up the correct design tokens.
        const defaults = TEMPLATE_DEFAULTS[slug] || {};
        const freshConfig = {
            template_slug: slug,
            primary_color: defaults.primary_color || '#5170ff',
            header_bg_color: defaults.header_bg_color || defaults.primary_color || '#5170ff',
            header_text_color: defaults.header_text_color || '#ffffff',
            text_color: defaults.text_color || '#1e293b',
            bg_color: defaults.bg_color || '#ffffff',
            agent_bg_color: defaults.agent_bg_color || '#f8faf9',
            agent_text_color: defaults.agent_text_color || '#1e293b',
        };

        apiFetch({
            path: '/shois-chat/v1/settings',
            method: 'POST',
            data: {
                active_template_slug: slug,
                template_config: freshConfig,
            },
        })
            .then(() => {
                setActiveSlug(slug);
            })
            .catch(() => { })
            .finally(() => setSaving(false));
    };

    const handleEdit = (template) => {
        if (onEditTemplate) {
            onEditTemplate(template);
        }
    };

    return (
        <div className="shcb-templates-page">
            <div className="shcb-modern-card">
                <div className="shcb-modern-card-header">
                    <span>🎨</span>
                    <h3>{__('Template Library', 'shois-chat-button')}</h3>
                    <span className="shcb-tpl-count">
                        {BUILT_IN_TEMPLATES.length} {__('templates', 'shois-chat-button')}
                    </span>
                </div>
                <p className="shcb-tab-description">
                    {__('Choose a template and customize it to match your brand. Each template can be fully customized with different colors, content, and animations.', 'shois-chat-button')}
                </p>
            </div>

            <div className="shcb-tpl-grid">
                {BUILT_IN_TEMPLATES.map((tpl) => (
                    <TemplateCard
                        key={tpl.slug}
                        template={tpl}
                        isActive={activeSlug === tpl.slug}
                        onSelect={handleActivate}
                        onEdit={handleEdit}
                    />
                ))}
            </div>

            {saving && (
                <div className="shcb-saving-toast">
                    {__('Saving...', 'shois-chat-button')}
                </div>
            )}
        </div>
    );
}
