/**
 * Shois Chat Button — Animation Picker Component
 *
 * Renders categorized animation grids with live preview on hover.
 * Used inside the Template Editor's Animations tab.
 *
 * @package ShoisChatButton
 */
import { useState, useRef, useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Animation categories with IDs matching PHP definitions.
 */
const ANIMATION_GROUPS = {
    entrance: {
        label: __('Entrance', 'shois-chat-button'),
        icon: '🎬',
        items: [
            { id: 'shcb-enter-fade', label: __('Fade In', 'shois-chat-button') },
            { id: 'shcb-enter-slideup', label: __('Slide Up', 'shois-chat-button') },
            { id: 'shcb-enter-slidedown', label: __('Slide Down', 'shois-chat-button') },
            { id: 'shcb-enter-slideright', label: __('Slide Right', 'shois-chat-button') },
            { id: 'shcb-enter-zoom', label: __('Zoom In', 'shois-chat-button') },
            { id: 'shcb-enter-bounce', label: __('Bounce In', 'shois-chat-button') },
            { id: 'shcb-enter-flip', label: __('Flip In', 'shois-chat-button') },
            { id: 'shcb-enter-roll', label: __('Roll In', 'shois-chat-button') },
            { id: 'shcb-enter-pop', label: __('Pop', 'shois-chat-button') },
            { id: 'shcb-enter-rubber', label: __('Rubber Band', 'shois-chat-button') },
        ],
    },
    idle: {
        label: __('Attention / Idle', 'shois-chat-button'),
        icon: '🔔',
        items: [
            { id: 'shcb-idle-pulse', label: __('Pulse Ring', 'shois-chat-button') },
            { id: 'shcb-idle-bounce', label: __('Bounce', 'shois-chat-button') },
            { id: 'shcb-idle-shake', label: __('Shake', 'shois-chat-button') },
            { id: 'shcb-idle-heartbeat', label: __('Heartbeat', 'shois-chat-button') },
            { id: 'shcb-idle-jello', label: __('Jello', 'shois-chat-button') },
            { id: 'shcb-idle-swing', label: __('Swing', 'shois-chat-button') },
            { id: 'shcb-idle-tada', label: __('Tada', 'shois-chat-button') },
            { id: 'shcb-idle-neon', label: __('Neon Glow', 'shois-chat-button') },
            { id: 'shcb-idle-float', label: __('Float', 'shois-chat-button') },
            { id: 'shcb-idle-wave', label: __('Wave', 'shois-chat-button') },
            { id: 'shcb-idle-ripple', label: __('Ripple', 'shois-chat-button') },
            { id: 'shcb-idle-flash', label: __('Flash', 'shois-chat-button') },
        ],
    },
    hover: {
        label: __('Hover', 'shois-chat-button'),
        icon: '👆',
        items: [
            { id: 'shcb-hover-grow', label: __('Grow', 'shois-chat-button') },
            { id: 'shcb-hover-shrink', label: __('Shrink', 'shois-chat-button') },
            { id: 'shcb-hover-glow', label: __('Glow', 'shois-chat-button') },
            { id: 'shcb-hover-rotatecw', label: __('Rotate CW', 'shois-chat-button') },
            { id: 'shcb-hover-rotateccw', label: __('Rotate CCW', 'shois-chat-button') },
            { id: 'shcb-hover-wobble', label: __('Wobble', 'shois-chat-button') },
            { id: 'shcb-hover-lift', label: __('Lift', 'shois-chat-button') },
            { id: 'shcb-hover-color', label: __('Color Shift', 'shois-chat-button') },
            { id: 'shcb-hover-ripple', label: __('Ripple', 'shois-chat-button') },
            { id: 'shcb-hover-iconspin', label: __('Icon Spin', 'shois-chat-button') },
        ],
    },
    popup: {
        label: __('Popup Transition', 'shois-chat-button'),
        icon: '💬',
        items: [
            { id: 'shcb-open-fadescale', label: __('Fade Scale', 'shois-chat-button') },
            { id: 'shcb-open-slideuppanel', label: __('Slide Up', 'shois-chat-button') },
            { id: 'shcb-open-spring', label: __('Spring Pop', 'shois-chat-button') },
            { id: 'shcb-open-flip', label: __('Flip', 'shois-chat-button') },
            { id: 'shcb-open-unfold', label: __('Unfold', 'shois-chat-button') },
            { id: 'shcb-open-door', label: __('Door Open', 'shois-chat-button') },
            { id: 'shcb-open-balloon', label: __('Balloon', 'shois-chat-button') },
            { id: 'shcb-open-blurin', label: __('Blur In', 'shois-chat-button') },
        ],
    },
};

/**
 * Small representative widget for animation preview.
 */
function MiniWidgetPreview({ animationId, playing }) {
    return (
        <div className="shcb-mini-widget-container">
            <div className={`shcb-mini-widget ${playing ? animationId : ''}`}>
                <div className="shcb-mini-widget-bubble">
                    <div className="shcb-mini-widget-line" />
                    <div className="shcb-mini-widget-line short" />
                </div>
                <div className="shcb-mini-widget-tail" />
            </div>
        </div>
    );
}

/**
 * A single animation card with live preview.
 */
function AnimationCard({ animation, selected, onSelect, group, isProUser }) {
    // Logic for PRO badge:
    // 1. Entrance: all except Fade In (shcb-enter-fade)
    // 2. Attention/Idle: all
    // 3. Hover: all
    // 4. Popup: all
    const isProAnim = (group === 'entrance' && animation.id !== 'shcb-enter-fade') || 
                  (['idle', 'hover', 'popup'].includes(group));

    const isDisabled = isProAnim && !isProUser;

    const handleClick = (e) => {
        if (isDisabled) {
            e.preventDefault();
            e.stopPropagation();
            window.dispatchEvent(new CustomEvent('shcb-pro-alert'));
        } else {
            onSelect(group, animation.id);
        }
    };

    return (
        <button
            className={`shcb-anim-v2-card ${selected ? 'shcb-anim-v2-selected' : ''} ${isDisabled ? 'shcb-pro-locked-field' : ''}`}
            onClickCapture={handleClick}
            type="button"
            style={isDisabled ? { opacity: 0.6, cursor: 'not-allowed' } : {}}
        >
            <div className="shcb-anim-v2-preview">
                <MiniWidgetPreview 
                    animationId={animation.id} 
                    playing={true} /* Always "playing" the loop in CSS */
                />
            </div>
            <div className="shcb-anim-v2-info">
                <span className="shcb-anim-v2-label">
                    {animation.label}
                    {isProAnim && <span className="shcb-pro-badge">PRO</span>}
                </span>
            </div>
            {selected && (
                <div className="shcb-anim-v2-check">
                    <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3">
                        <polyline points="20 6 9 17 4 12" />
                    </svg>
                </div>
            )}
        </button>
    );
}

/**
 * Section Header for animation groups.
 */
function AnimSectionHeader({ icon, title }) {
    return (
        <div className="shcb-behavior-section-header" style={{ marginTop: '24px' }}>
            <span style={{ fontSize: '14px', marginRight: '4px' }}>{icon}</span>
            <span>{title}</span>
        </div>
    );
}

/**
 * AnimationPicker — redesigned multi-category animation selector.
 */
export default function AnimationPicker({ values = {}, onChange, visibleGroups, isProUser = true }) {
    const groups = visibleGroups
        ? Object.keys(ANIMATION_GROUPS).filter((g) => visibleGroups.includes(g))
        : Object.keys(ANIMATION_GROUPS);

    return (
        <div className="shcb-animation-picker-v2">
            {groups.map((groupKey) => {
                const group = ANIMATION_GROUPS[groupKey];
                const selectedId = values[groupKey] || '';

                return (
                    <div key={groupKey} className="shcb-anim-v2-group">
                        <AnimSectionHeader 
                            icon={group.icon} 
                            title={group.label.toUpperCase()} 
                        />
                        
                        <div className="shcb-settings-card">
                            <div className="shcb-card-body shcb-anim-v2-grid">
                                {/* None Option */}
                                <button
                                    className={`shcb-anim-v2-card shcb-anim-v2-none ${!selectedId ? 'shcb-anim-v2-selected' : ''}`}
                                    onClick={() => onChange(groupKey, '')}
                                    type="button"
                                >
                                <div className="shcb-anim-v2-preview">
                                    <div className="shcb-anim-v2-none-icon">✕</div>
                                </div>
                                    <div className="shcb-anim-v2-info">
                                        <span className="shcb-anim-v2-label">{__('None', 'shois-chat-button')}</span>
                                    </div>
                                </button>

                                {/* Animation Items */}
                                {group.items.map((animation) => (
                                    <AnimationCard
                                        key={animation.id}
                                        animation={animation}
                                        selected={selectedId === animation.id}
                                        onSelect={onChange}
                                        group={groupKey}
                                        isProUser={isProUser}
                                    />
                                ))}
                            </div>
                        </div>
                    </div>
                );
            })}
        </div>
    );
}
