/**
 * 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';
    
    const AlbumArtworkAdmin = {
        
        /**
         * Initialize the album artwork admin interface
         */
        init: function() {
            this.bindEvents();
            this.loadStats();
        },
        
        /**
         * Bind DOM events
         */
        bindEvents: function() {
            // Test artwork search
            $('#test-artwork-search').on('click', this.testArtworkSearch.bind(this));
            
            // Clear cache
            $('#clear-artwork-cache').on('click', this.clearCache.bind(this));
            
            // Test APIs
            $('#test-apis').on('click', this.testAPIs.bind(this));
            
            // Search form submission
            $('#artwork-search-form').on('submit', this.performSearch.bind(this));
        },
        
        /**
         * Test artwork search with predefined data
         */
        testArtworkSearch: function(e) {
            e.preventDefault();
            
            const testCases = [
                { artist: 'Pink Floyd', album: 'Dark Side of the Moon', title: '' },
                { artist: 'The Beatles', album: 'Abbey Road', title: '' },
                { artist: 'Radiohead', album: 'OK Computer', title: '' },
                { artist: 'Miles Davis', album: 'Kind of Blue', title: '' }
            ];
            
            $('#test-results').html('<div class="notice notice-info"><p>Running test searches...</p></div>');
            
            this.runTestCases(testCases, 0);
        },
        
        /**
         * Run test cases sequentially
         */
        runTestCases: function(testCases, index) {
            if (index >= testCases.length) {
                $('#test-results').append('<div class="notice notice-success"><p>All test cases completed!</p></div>');
                return;
            }
            
            const testCase = testCases[index];
            const self = this;
            
            $.ajax({
                url: castconductorAjax.restUrl + 'castconductor/v5/album-artwork/search',
                method: 'POST',
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', castconductorAjax.restNonce);
                },
                data: testCase,
                success: function(response) {
                    self.displayTestResult(testCase, response, true);
                    // Continue with next test case after a small delay
                    setTimeout(() => self.runTestCases(testCases, index + 1), 1000);
                },
                error: function(xhr) {
                    self.displayTestResult(testCase, xhr.responseJSON, false);
                    setTimeout(() => self.runTestCases(testCases, index + 1), 1000);
                }
            });
        },
        
        /**
         * Display test result
         */
        displayTestResult: function(testCase, response, success) {
            const resultHtml = `
                <div class="test-result ${success ? 'success' : 'error'}">
                    <h4>Test: ${testCase.artist} - ${testCase.album}</h4>
                    <div class="test-details">
                        <strong>Status:</strong> ${success ? 'Success' : 'Failed'}<br>
                        ${success && response.artwork_url ? 
                            `<strong>Artwork URL:</strong> <a href="${response.artwork_url}" target="_blank">View Image</a><br>
                             <strong>Source:</strong> ${response.source}<br>
                             <img src="${response.artwork_url}" style="max-width: 100px; height: auto; margin-top: 5px;" />` 
                            : '<strong>Result:</strong> No artwork found'
                        }
                    </div>
                </div>
            `;
            
            $('#test-results').append(resultHtml);
        },
        
        /**
         * Perform custom artwork search
         */
        performSearch: function(e) {
            e.preventDefault();
            
            const artist = $('#search-artist').val().trim();
            const album = $('#search-album').val().trim();
            const title = $('#search-title').val().trim();
            const forceRefresh = $('#force-refresh').is(':checked');
            
            if (!artist && !album && !title) {
                alert('Please enter at least one search term.');
                return;
            }
            
            $('#search-results').html('<div class="notice notice-info"><p>Searching for artwork...</p></div>');
            
            $.ajax({
                url: castconductorAjax.restUrl + 'castconductor/v5/album-artwork/search',
                method: 'POST',
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', castconductorAjax.restNonce);
                },
                data: {
                    artist: artist,
                    album: album,
                    title: title,
                    force_refresh: forceRefresh
                },
                success: function(response) {
                    this.displaySearchResult(response, true);
                }.bind(this),
                error: function(xhr) {
                    this.displaySearchResult(xhr.responseJSON, false);
                }.bind(this)
            });
        },
        
        /**
         * Display search result
         */
        displaySearchResult: function(response, success) {
            let resultHtml = '';
            
            if (success && response.artwork_url) {
                resultHtml = `
                    <div class="notice notice-success">
                        <p><strong>Artwork found!</strong></p>
                        <p><strong>Source:</strong> ${response.source}</p>
                        <p><strong>Cache Key:</strong> ${response.cache_key}</p>
                        <p><a href="${response.artwork_url}" target="_blank">View Full Size</a></p>
                        <img src="${response.artwork_url}" style="max-width: 300px; height: auto; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.3);" />
                    </div>
                `;
                
                // Show API responses if available
                if (response.api_responses) {
                    resultHtml += '<h4>API Responses:</h4>';
                    Object.keys(response.api_responses).forEach(api => {
                        const apiResponse = response.api_responses[api];
                        resultHtml += `
                            <div class="api-response">
                                <strong>${api.charAt(0).toUpperCase() + api.slice(1)}:</strong>
                                ${apiResponse.error ? 
                                    `<span style="color: #d63638;">${apiResponse.error}</span>` :
                                    `<span style="color: #00a32a;">Success (Score: ${apiResponse.match_score?.toFixed(2) || 'N/A'})</span>`
                                }
                            </div>
                        `;
                    });
                }
            } else {
                resultHtml = `
                    <div class="notice notice-warning">
                        <p><strong>No artwork found</strong></p>
                        <p>Try adjusting your search terms or check if the artist/album exists in the music databases.</p>
                    </div>
                `;
            }
            
            $('#search-results').html(resultHtml);
        },
        
        /**
         * Clear artwork cache
         */
        clearCache: function(e) {
            e.preventDefault();
            
            if (!confirm('Are you sure you want to clear the artwork cache? This will remove all cached artwork URLs.')) {
                return;
            }
            
            $.ajax({
                url: castconductorAjax.restUrl + 'castconductor/v5/album-artwork/cache',
                method: 'DELETE',
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', castconductorAjax.restNonce);
                },
                success: function(response) {
                    $('#cache-status').html(`
                        <div class="notice notice-success">
                            <p>${response.message}</p>
                        </div>
                    `);
                    this.loadStats(); // Refresh stats
                }.bind(this),
                error: function(xhr) {
                    $('#cache-status').html(`
                        <div class="notice notice-error">
                            <p>Error clearing cache: ${xhr.responseJSON?.message || 'Unknown error'}</p>
                        </div>
                    `);
                }
            });
        },
        
        /**
         * Test API connectivity
         */
        testAPIs: function(e) {
            e.preventDefault();
            
            $('#api-test-results').html('<div class="notice notice-info"><p>Testing API connectivity...</p></div>');
            
            $.ajax({
                url: castconductorAjax.restUrl + 'castconductor/v5/album-artwork/test',
                method: 'POST',
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', castconductorAjax.restNonce);
                },
                success: function(response) {
                    this.displayAPITestResults(response.test_results);
                }.bind(this),
                error: function(xhr) {
                    $('#api-test-results').html(`
                        <div class="notice notice-error">
                            <p>Error testing APIs: ${xhr.responseJSON?.message || 'Unknown error'}</p>
                        </div>
                    `);
                }
            });
        },
        
        /**
         * Display API test results
         */
        displayAPITestResults: function(results) {
            let resultHtml = '<h4>API Test Results:</h4>';
            
            Object.keys(results).forEach(api => {
                const result = results[api];
                const statusColor = result.status === 'success' ? '#00a32a' : '#d63638';
                
                resultHtml += `
                    <div class="api-test-result" style="margin-bottom: 15px; padding: 10px; border-left: 4px solid ${statusColor};">
                        <strong>${api.charAt(0).toUpperCase() + api.slice(1)} API:</strong>
                        <span style="color: ${statusColor};">${result.status.toUpperCase()}</span><br>
                        ${result.response.error ? 
                            `<em>Error: ${result.response.error}</em>` :
                            `<em>Found artwork: ${result.response.artwork_url ? 'Yes' : 'No'}</em>`
                        }
                    </div>
                `;
            });
            
            $('#api-test-results').html(resultHtml);
        },
        
        /**
         * Load artwork discovery statistics
         */
        loadStats: function() {
            $.ajax({
                url: castconductorAjax.restUrl + 'castconductor/v5/album-artwork/stats',
                method: 'GET',
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', castconductorAjax.restNonce);
                },
                success: function(response) {
                    this.displayStats(response.stats);
                }.bind(this),
                error: function() {
                    $('#stats-display').html('<p>Unable to load statistics.</p>');
                }
            });
        },
        
        /**
         * Display statistics
         */
        displayStats: function(stats) {
            const statsHtml = `
                <div class="stats-grid">
                    <div class="stat-item">
                        <h4>Total Searches</h4>
                        <span class="stat-value">${stats.total_searches}</span>
                    </div>
                    <div class="stat-item">
                        <h4>Success Rate</h4>
                        <span class="stat-value">${stats.success_rate}%</span>
                    </div>
                    <div class="stat-item">
                        <h4>Cache Hits</h4>
                        <span class="stat-value">${stats.cache_hits}</span>
                    </div>
                    <div class="stat-item">
                        <h4>iTunes API</h4>
                        <span class="stat-value">${stats.api_usage.itunes}</span>
                    </div>
                    <div class="stat-item">
                        <h4>MusicBrainz API</h4>
                        <span class="stat-value">${stats.api_usage.musicbrainz}</span>
                    </div>
                    <div class="stat-item">
                        <h4>Deezer API</h4>
                        <span class="stat-value">${stats.api_usage.deezer}</span>
                    </div>
                </div>
            `;
            
            $('#stats-display').html(statsHtml);
        }
    };
    
    // Initialize when DOM is ready
    $(document).ready(function() {
        if ($('#album-artwork-admin').length) {
            AlbumArtworkAdmin.init();
        }
    });
    
})(jQuery);
