/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 * 
 * Copyright (c) 2025 CastConductor.com. All Rights Reserved.
 * 
 * This file is part of Cast Conductor ("Software"). The Software and its source
 * code constitute proprietary, confidential, and trade secret information of
 * CastConductor.com ("Company"). Any access or use is governed strictly by the
 * Cast Conductor Proprietary License v5 ("License"). By installing, copying,
 * accessing, compiling, or otherwise using the Software you agree to be bound by
 * all terms of the License. If you do not agree, you must cease use immediately.
 * 
 * Key Terms (Summary – see full License for binding terms):
 *  1. No Redistribution: You may not publish, distribute, sublicense, rent,
 *     lease, transfer, sell, or otherwise make the Software (or any derivative)
 *     available to any third party without prior written consent of Company.
 *  2. No Modification: Modification, reverse engineering, decompilation, or
 *     disassembly is prohibited except to the limited extent expressly permitted
 *     by applicable law that cannot be contractually waived.
 *  3. Confidentiality: Treat all source code and related artifacts as Company
 *     Confidential Information. Maintain at least the same degree of care as for
 *     your own confidential materials, and not less than reasonable care.
 *  4. No Patent License: No express or implied patent rights are granted. Future
 *     patents (if any) are fully reserved.
 *  5. No Trademark License: Company names, marks, and logos may not be used
 *     without prior written permission.
 *  6. Limited Internal Use: Use is limited solely to internal evaluation and
 *     operation of licensed Cast Conductor deployments. Commercial hosting or
 *     resale as a service requires a separate written agreement.
 *  7. Telemetry & License Validation: The Software may periodically transmit a
 *     hashed installation identifier, domain (or site ID), plugin/app version,
 *     and a truncated (non-reversible) fragment of the license key solely to
 *     validate activation status and enforce licensing. This minimal "phone home"
 *     check contains no personal or content data. If optional telemetry is later
 *     introduced it will be limited to aggregate operational metrics (no PII),
 *     fully documented, and optionally disableable per published instructions.
 *  8. Third-Party Components: The Software may include open source components
 *     covered by their own licenses. See THIRD-PARTY-NOTICES.md. Those licenses
 *     govern their respective components; this License governs all remaining code.
 *  9. Export Compliance: You are responsible for compliance with all applicable
 *     export control and sanctions laws.
 * 10. Warranty Disclaimer: THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF
 *     ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO MERCHANTABILITY,
 *     FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.
 * 11. Limitation of Liability: IN NO EVENT WILL COMPANY OR AUTHORS BE LIABLE FOR
 *     ANY INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE
 *     DAMAGES, OR LOST PROFITS, EVEN IF ADVISED OF THE POSSIBILITY.
 * 12. Acceptance: Use of the Software constitutes acceptance of the License.
 * 13. Enforcement: Unauthorized reproduction or distribution may result in civil
 *     and criminal penalties and will be prosecuted to the maximum extent allowed
 *     by law.
 * 
 * Authoritative EULA: EULA-v5.1.md (repository root – private) and https://castconductor.com/eula
 * Precedence: If this summary conflicts with the EULA, the EULA governs.
 * Revision: Current EULA revision v5.1 (subject to update; check EULA for current enterprise thresholds).
 * 
 * Full License text available from: licensing@castconductor.com
 * Security reports: security@castconductor.com
 * Commercial inquiries: licensing@castconductor.com
 * 
 * END OF HEADER
 */
(function($) {
    'use strict';
    
    var ContentBlocks = {
        
        /**
         * Initialize the content blocks interface
         */
        init: function() {
            this.loadContentBlocks();
            this.loadContentBlockTypes();
            this.bindEvents();
        },
        
        /**
         * Bind event handlers
         */
        bindEvents: function() {
            // Add new content block
            $('#add-content-block').on('click', function(e) {
                e.preventDefault();
                ContentBlocks.showModal('add');
            });
            
            // Close modal
            $('.close, #cancel-content-block').on('click', function() {
                ContentBlocks.hideModal();
            });
            
            // Save content block
            $('#save-content-block').on('click', function(e) {
                e.preventDefault();
                ContentBlocks.saveContentBlock();
            });
            
            // Content block type change
            $('#block-type').on('change', function() {
                ContentBlocks.loadTypeSpecificConfig($(this).val());
            });
            
            // Dynamic event binding for edit/delete buttons
            $(document).on('click', '.edit-content-block', function(e) {
                e.preventDefault();
                var blockId = $(this).data('id');
                ContentBlocks.editContentBlock(blockId);
            });
            
            $(document).on('click', '.delete-content-block', function(e) {
                e.preventDefault();
                var blockId = $(this).data('id');
                ContentBlocks.deleteContentBlock(blockId);
            });
            
            $(document).on('click', '.preview-content-block', function(e) {
                e.preventDefault();
                var blockId = $(this).data('id');
                ContentBlocks.previewContentBlock(blockId);
            });
        },
        
        /**
         * Load content blocks from API
         */
        loadContentBlocks: function() {
            $('#content-blocks-list').html('<div class="loading">Loading content blocks...</div>');
            
            $.ajax({
                url: castconductor_content_blocks.api_url,
                method: 'GET',
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', castconductor_content_blocks.nonce);
                },
                success: function(response) {
                    ContentBlocks.renderContentBlocks(response);
                },
                error: function(xhr, status, error) {
                    $('#content-blocks-list').html('<div class="error">Failed to load content blocks: ' + error + '</div>');
                }
            });
        },
        
        /**
         * Load content block types from API
         */
        loadContentBlockTypes: function() {
            $.ajax({
                url: castconductor_content_blocks.types_url,
                method: 'GET',
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', castconductor_content_blocks.nonce);
                },
                success: function(response) {
                    if (response.success && response.data) {
                        ContentBlocks.populateTypeDropdown(response.data);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Failed to load content block types:', error);
                }
            });
        },
        
        /**
         * Populate the type dropdown
         */
        populateTypeDropdown: function(types) {
            var $select = $('#block-type');
            $select.find('option[value!=""]').remove();
            
            $.each(types, function(type, config) {
                $select.append('<option value="' + type + '">' + config.name + ' - ' + config.description + '</option>');
            });
        },
        
        /**
         * Render content blocks grid
         */
        renderContentBlocks: function(contentBlocks) {
            var html = '';
            
            if (contentBlocks.length === 0) {
                html = '<div class="no-content-blocks">No content blocks found. <a href="#" id="add-first-block">Create your first content block</a></div>';
            } else {
                $.each(contentBlocks, function(index, block) {
                    html += ContentBlocks.renderContentBlockCard(block);
                });
            }
            
            $('#content-blocks-list').html(html);
            
            // Bind event for "add first block" link
            $('#add-first-block').on('click', function(e) {
                e.preventDefault();
                ContentBlocks.showModal('add');
            });
        },
        
        /**
         * Render individual content block card
         */
        renderContentBlockCard: function(block) {
            var typeClass = 'type-' + block.type.replace('_', '-');
            var statusBadge = block.enabled ? '<span class="status enabled">Enabled</span>' : '<span class="status disabled">Disabled</span>';
            
            return `
                <div class="content-block-card ${typeClass}" data-id="${block.id}">
                    <h3>${block.name}</h3>
                    <div class="content-block-meta">
                        <span class="content-block-type">${block.type}</span>
                        ${statusBadge}
                    </div>
                    <div class="content-block-info">
                        <p>Created: ${ContentBlocks.formatDate(block.created_at)}</p>
                        <p>Updated: ${ContentBlocks.formatDate(block.updated_at)}</p>
                    </div>
                    <div class="content-block-actions">
                        <button type="button" class="button button-small edit-content-block" data-id="${block.id}">Edit</button>
                        <button type="button" class="button button-small preview-content-block" data-id="${block.id}">Preview</button>
                        <button type="button" class="button button-small delete-content-block" data-id="${block.id}">Delete</button>
                    </div>
                </div>
            `;
        },
        
        /**
         * Show modal for add/edit
         */
        showModal: function(mode, blockData) {
            var title = mode === 'add' ? 'Add Content Block' : 'Edit Content Block';
            $('#modal-title').text(title);
            
            // Reset form
            $('#content-block-form')[0].reset();
            
            if (mode === 'edit' && blockData) {
                $('#block-name').val(blockData.name);
                $('#block-type').val(blockData.type).trigger('change');
                $('#block-enabled').prop('checked', blockData.enabled);
                
                // Store block ID for updating
                $('#content-block-form').data('block-id', blockData.id);
            } else {
                $('#content-block-form').removeData('block-id');
            }
            
            $('#content-block-modal').show();
        },
        
        /**
         * Hide modal
         */
        hideModal: function() {
            $('#content-block-modal').hide();
            $('#type-specific-config').empty();
            $('#visual-config-preview').hide();
        },
        
        /**
         * Load type-specific configuration
         */
        loadTypeSpecificConfig: function(type) {
            if (!type) {
                $('#type-specific-config').empty();
                return;
            }
            
            // For now, show basic configuration
            // In Phase 3, this will load the Canvas Editor
            var html = `
                <h3>Configuration</h3>
                <p>Configuration options for ${type} content blocks will be available in the Canvas Editor.</p>
                <div class="notice notice-info inline">
                    <p><strong>Coming in Phase 3:</strong> Full visual configuration with the Canvas Editor interface.</p>
                </div>
            `;
            
            $('#type-specific-config').html(html);
        },
        
        /**
         * Save content block
         */
        saveContentBlock: function() {
            var blockId = $('#content-block-form').data('block-id');
            var isEdit = !!blockId;
            var url = isEdit ? castconductor_content_blocks.api_url + blockId : castconductor_content_blocks.api_url;
            var method = isEdit ? 'PUT' : 'POST';
            
            var data = {
                name: $('#block-name').val(),
                type: $('#block-type').val(),
                enabled: $('#block-enabled').is(':checked'),
                visual_config: {} // Will be populated by Canvas Editor in Phase 3
            };
            
            // Basic validation
            if (!data.name || !data.type) {
                alert('Please fill in all required fields.');
                return;
            }
            
            // Disable save button
            $('#save-content-block').prop('disabled', true).text('Saving...');
            
            $.ajax({
                url: url,
                method: method,
                data: JSON.stringify(data),
                contentType: 'application/json',
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', castconductor_content_blocks.nonce);
                },
                success: function(response) {
                    ContentBlocks.hideModal();
                    ContentBlocks.loadContentBlocks();
                    
                    // Show success message
                    ContentBlocks.showNotice(isEdit ? 'Content block updated successfully!' : 'Content block created successfully!', 'success');
                },
                error: function(xhr, status, error) {
                    var message = 'Failed to save content block';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        message += ': ' + xhr.responseJSON.message;
                    }
                    ContentBlocks.showNotice(message, 'error');
                },
                complete: function() {
                    $('#save-content-block').prop('disabled', false).text('Save Content Block');
                }
            });
        },
        
        /**
         * Edit content block
         */
        editContentBlock: function(blockId) {
            $.ajax({
                url: castconductor_content_blocks.api_url + blockId,
                method: 'GET',
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', castconductor_content_blocks.nonce);
                },
                success: function(response) {
                    ContentBlocks.showModal('edit', response);
                },
                error: function(xhr, status, error) {
                    ContentBlocks.showNotice('Failed to load content block for editing', 'error');
                }
            });
        },
        
        /**
         * Delete content block
         */
        deleteContentBlock: function(blockId) {
            if (!confirm('Are you sure you want to delete this content block? This action cannot be undone.')) {
                return;
            }
            
            $.ajax({
                url: castconductor_content_blocks.api_url + blockId,
                method: 'DELETE',
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', castconductor_content_blocks.nonce);
                },
                success: function(response) {
                    ContentBlocks.loadContentBlocks();
                    ContentBlocks.showNotice('Content block deleted successfully!', 'success');
                },
                error: function(xhr, status, error) {
                    var message = 'Failed to delete content block';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        message += ': ' + xhr.responseJSON.message;
                    }
                    ContentBlocks.showNotice(message, 'error');
                }
            });
        },
        
        /**
         * Preview content block
         */
        previewContentBlock: function(blockId) {
            $.ajax({
                url: castconductor_content_blocks.api_url + blockId + '/preview',
                method: 'GET',
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', castconductor_content_blocks.nonce);
                },
                success: function(response) {
                    if (response.success && response.data) {
                        ContentBlocks.showPreviewModal(response.data);
                    }
                },
                error: function(xhr, status, error) {
                    ContentBlocks.showNotice('Failed to generate preview', 'error');
                }
            });
        },
        
        /**
         * Show preview modal
         */
        showPreviewModal: function(data) {
            var modal = `
                <div id="preview-modal" class="castconductor-modal">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h2>Content Block Preview: ${data.content_block.name}</h2>
                            <span class="close-preview">&times;</span>
                        </div>
                        <div class="modal-body">
                            <div class="preview-container">
                                ${data.preview_html}
                            </div>
                            <div class="preview-info">
                                <h4>Sample Data:</h4>
                                <pre>${JSON.stringify(data.sample_data, null, 2)}</pre>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="button close-preview">Close Preview</button>
                        </div>
                    </div>
                </div>
            `;
            
            $('body').append(modal);
            
            // Bind close events
            $('.close-preview').on('click', function() {
                $('#preview-modal').remove();
            });
            
            // Close on outside click
            $('#preview-modal').on('click', function(e) {
                if (e.target === this) {
                    $('#preview-modal').remove();
                }
            });
        },
        
        /**
         * Show notice message
         */
        showNotice: function(message, type) {
            var notice = `
                <div class="notice notice-${type} is-dismissible">
                    <p>${message}</p>
                    <button type="button" class="notice-dismiss">
                        <span class="screen-reader-text">Dismiss this notice.</span>
                    </button>
                </div>
            `;
            
            $('.wrap h1').after(notice);
            
            // Auto-dismiss after 5 seconds
            setTimeout(function() {
                $('.notice').fadeOut();
            }, 5000);
            
            // Bind dismiss button
            $('.notice-dismiss').on('click', function() {
                $(this).closest('.notice').fadeOut();
            });
        },
        
        /**
         * Format date for display
         */
        formatDate: function(dateString) {
            var date = new Date(dateString);
            return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
        }
    };
    
    // Initialize when document is ready
    $(document).ready(function() {
        // Only initialize on content blocks page
        if (window.location.href.indexOf('castconductor-content-blocks') !== -1) {
            ContentBlocks.init();
        }
    });
    
})(jQuery);
