/**
 * 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';
    
    // Document ready
    $(document).ready(function() {
        initializeAdmin();
    });
    
    /**
     * Initialize admin functionality
     */
    function initializeAdmin() {
        initializeCopyButtons();
        initializeAPIEndpoints();
        initializeSetupWizard();
    initializeBrandingMediaPickers();
    }
    
    /**
     * Initialize copy-to-clipboard buttons
     */
    function initializeCopyButtons() {
        $('.copy-endpoint').on('click', function(e) {
            e.preventDefault();
            
            const url = $(this).data('url');
            const input = $(this).siblings('input');
            
            // Select and copy the text
            input.select();
            document.execCommand('copy');
            
            // Show feedback
            const originalText = $(this).text();
            $(this).text('Copied!').addClass('button-primary');
            
            setTimeout(() => {
                $(this).text(originalText).removeClass('button-primary');
            }, 1000);
        });
    }
    
    /**
     * Initialize API endpoints browser
     */
    function initializeAPIEndpoints() {
        if ($('.api-endpoints-browser').length) {
            loadAPIEndpoints();
        }
    }
    
    /**
     * Load and display API endpoints
     */
    function loadAPIEndpoints() {
        const container = $('.api-endpoints-browser');
        
        const endpoints = {
            'Core Roku Endpoints': [
                {
                    name: 'Master App Config',
                    url: castconductor_admin.api_url + 'roku/app-config',
                    description: 'Complete configuration for Roku app'
                },
                {
                    name: 'Stream Configuration',
                    url: castconductor_admin.api_url + 'roku/stream-config',
                    description: 'Stream URLs and metadata configuration'
                }
            ],
            'Content Management Endpoints': [
                {
                    name: 'Active Shoutouts',
                    url: castconductor_admin.api_url + 'content/shoutouts/active',
                    description: 'Currently active shoutout submissions'
                },
                {
                    name: 'Active Sponsors',
                    url: castconductor_admin.api_url + 'content/sponsors/active',
                    description: 'Currently active sponsor campaigns'
                },
                {
                    name: 'Active Promos',
                    url: castconductor_admin.api_url + 'content/promos/active',
                    description: 'Currently active promotional content'
                },
                {
                    name: 'Scheduled Content',
                    url: castconductor_admin.api_url + 'content/scheduled',
                    description: 'All scheduled content with status'
                }
            ],
            'Enhanced Features': [
                {
                    name: 'Album Artwork Search',
                    url: castconductor_admin.api_url + 'artwork/search',
                    description: 'Enhanced album artwork discovery'
                },
                {
                    name: 'Global Settings',
                    url: castconductor_admin.api_url + 'settings',
                    description: 'Plugin configuration settings'
                }
            ]
        };
        
        let html = '<div class="api-categories">';
        
        Object.keys(endpoints).forEach(category => {
            html += `<div class="api-category">
                <h3>${category}</h3>
                <div class="api-endpoints">`;
            
            endpoints[category].forEach(endpoint => {
                html += `
                    <div class="api-endpoint-item">
                        <div class="endpoint-header">
                            <h4>${endpoint.name}</h4>
                            <p class="endpoint-description">${endpoint.description}</p>
                        </div>
                        <div class="endpoint-actions">
                            <div class="endpoint-url-display">
                                <input type="text" value="${endpoint.url}" readonly onclick="this.select()">
                                <button class="button copy-endpoint" data-url="${endpoint.url}">📋 Copy</button>
                                <a href="${endpoint.url}" target="_blank" class="button">🔍 View JSON</a>
                                <button class="button test-endpoint" data-url="${endpoint.url}">📱 Test Live</button>
                            </div>
                        </div>
                    </div>`;
            });
            
            html += '</div></div>';
        });
        
        html += '</div>';
        
        container.html(html);
        
        // Re-initialize copy buttons for new content
        initializeCopyButtons();
        initializeTestButtons();

        // Also render a dynamic "Content Blocks (IDs & Preview)" section
        renderContentBlocksSection(container);
    }

    /**
     * Fetch and render Content Blocks section with copy/view links for IDs
     */
    function renderContentBlocksSection(container) {
        // Prefer WordPress-provided REST root/nonce to avoid subdomain/protocol cookie mismatches
        const restRoot = (window.wpApiSettings && window.wpApiSettings.root) ? window.wpApiSettings.root.replace(/\/$/, '') : castconductor_admin.api_url.replace(/\/$/, '').replace(/\/castconductor\/v5$/, '/wp-json');
        const apiBase = restRoot + '/castconductor/v5';
        const url = apiBase + '/content-blocks?per_page=100';
        const nonce = (window.wpApiSettings && window.wpApiSettings.nonce) ? window.wpApiSettings.nonce : (castconductor_admin.rest_nonce || '');

        // Wrapper
        const section = $('<div class="api-category"><h3>Content Blocks (IDs & Preview)</h3><div class="api-endpoints content-blocks-endpoints"><p>Loading content blocks…</p></div></div>');
        container.append(section);

        $.ajax({
            url,
            method: 'GET',
            beforeSend: function(xhr){
                const nonce = (window.wpApiSettings && window.wpApiSettings.nonce) ? window.wpApiSettings.nonce : (castconductor_admin.rest_nonce || '');
                if (nonce) xhr.setRequestHeader('X-WP-Nonce', nonce);
            },
        }).done(function(list){
            const wrap = section.find('.content-blocks-endpoints');
            if (!Array.isArray(list) || list.length === 0) {
                wrap.html('<div class="endpoint-item"><em>No content blocks found.</em></div>');
                return;
            }
            let inner = '';
            list.forEach(block => {
                const id = block.id;
                const type = block.type;
                const name = block.name || ('Block #' + id);
                // Append _wpnonce to allow cookie-based REST auth when opening in a new tab
                const nonceParam = nonce ? (`?_wpnonce=${encodeURIComponent(nonce)}`) : '';
                const getUrl = `${apiBase}/content-blocks/${id}${nonceParam}`;
                const previewUrl = `${apiBase}/content-blocks/${id}/preview${nonceParam}`;
                const liveDataUrl = `${apiBase}/content-blocks/${id}/live-data${nonceParam}`;

                inner += `
                    <div class="api-endpoint-item">
                        <div class="endpoint-header">
                            <h4>${escapeHtml(name)} <span style="font-weight:normal; color:#666;">(${escapeHtml(type)})</span></h4>
                            <p class="endpoint-description">ID: <code>${id}</code></p>
                        </div>
                        <div class="endpoint-actions">
                            <div class="endpoint-url-display">
                                <input type="text" value="${id}" readonly onclick="this.select()">
                                <button class="button copy-endpoint" data-url="${id}">📋 Copy ID</button>
                                <a href="${getUrl}" target="_blank" class="button">🔍 View (GET)</a>
                                <a href="${previewUrl}" target="_blank" class="button">🎨 Preview (server)</a>
                                <a href="${liveDataUrl}" target="_blank" class="button">🛰 Live Data</a>
                            </div>
                        </div>
                    </div>`;
            });
            wrap.html(inner);
            initializeCopyButtons();
        }).fail(function(xhr){
            const wrap = section.find('.content-blocks-endpoints');
            wrap.html(`<div class="endpoint-item"><strong>Failed to load content blocks</strong><br/><small>${xhr.status} ${xhr.statusText}</small></div>`);
        });
    }

    // Minimal HTML escaper for names/types
    function escapeHtml(s){
        if (s == null) return '';
        return String(s)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }
    
    /**
     * Initialize test endpoint buttons
     */
    function initializeTestButtons() {
        $('.test-endpoint').on('click', function(e) {
            e.preventDefault();
            
            const url = $(this).data('url');
            const button = $(this);
            const originalText = button.text();
            
            button.text('Testing...').prop('disabled', true);
            
            $.get(url)
                .done(function(response) {
                    button.text('✅ Success').addClass('button-primary');
                    
                    // Show response in modal or console
                    console.log('API Response:', response);
                    
                    // Could add a modal here to show JSON response
                    showAPIResponse(url, response);
                })
                .fail(function(xhr) {
                    button.text('❌ Failed').addClass('button-secondary');
                    console.error('API Error:', xhr);
                })
                .always(function() {
                    setTimeout(() => {
                        button.text(originalText)
                               .removeClass('button-primary button-secondary')
                               .prop('disabled', false);
                    }, 2000);
                });
        });
    }
    
    /**
     * Show API response in a modal
     */
    function showAPIResponse(url, response) {
        // Create modal if it doesn't exist
        let modal = $('#api-response-modal');
        if (modal.length === 0) {
            modal = $(`
                <div id="api-response-modal" class="api-modal" style="display: none;">
                    <div class="api-modal-content">
                        <div class="api-modal-header">
                            <h3>API Response</h3>
                            <button class="api-modal-close">&times;</button>
                        </div>
                        <div class="api-modal-body">
                            <p class="api-url"></p>
                            <pre class="api-response-json"></pre>
                        </div>
                    </div>
                </div>
            `);
            $('body').append(modal);
            
            // Close modal functionality
            modal.find('.api-modal-close').on('click', function() {
                modal.hide();
            });
            
            modal.on('click', function(e) {
                if (e.target === modal[0]) {
                    modal.hide();
                }
            });
        }
        
        // Populate and show modal
        modal.find('.api-url').text(url);
        modal.find('.api-response-json').text(JSON.stringify(response, null, 2));
        modal.show();
    }
    
    /**
     * Initialize setup wizard functionality
     */
    function initializeSetupWizard() {
        // Setup wizard is handled in the PHP template with inline JavaScript
        // This function can be used for additional wizard enhancements
    }
    
    /**
     * Initialize WP Media Library pickers for Branding section
     */
    function initializeBrandingMediaPickers() {
        // Use event delegation to work on dynamically loaded admin screens
        $(document).on('click', '.cc-media-control .cc-select-media', function(e) {
            e.preventDefault();
            const wrapper = $(this).closest('.cc-media-control');
            const input = wrapper.find('input[type="hidden"]');
            const preview = wrapper.find('.cc-media-preview');
            const previewImg = preview.find('img');
            const placeholder = preview.find('.cc-media-placeholder');
            const clearBtn = wrapper.find('.cc-clear-media');
            const title = $(this).data('title') || 'Select image';
            const button = $(this).data('button') || 'Use this image';

            const frame = wp.media({
                title: title,
                button: { text: button },
                multiple: false
            });

            frame.on('select', function() {
                const attachment = frame.state().get('selection').first().toJSON();
                input.val(attachment.id);
                previewImg.attr('src', attachment.url).show();
                placeholder.hide();
                clearBtn.show();
            });

            frame.open();
        });

        $(document).on('click', '.cc-media-control .cc-clear-media', function(e) {
            e.preventDefault();
            const wrapper = $(this).closest('.cc-media-control');
            wrapper.find('input[type="hidden"]').val('');
            wrapper.find('.cc-media-preview img').attr('src', '').hide();
            wrapper.find('.cc-media-preview .cc-media-placeholder').show();
            $(this).hide();
        });
    }
    
})(jQuery);
