/**
 * URL Management Module
 * Handles: URL detail views, URL-based schema management
 */
(function($) {
    'use strict';

    window.SchemafyUrlManager = {
        // Store current URL for refresh after operations
        currentDetailUrl: null,

        /**
         * Open URL schemas view
         */
        openUrlSchemas: function(url) {
            const $bulkTab = $('.schemafy-tab-btn-v2[data-tab="bulk"]');
            if ($bulkTab.length) {
                $bulkTab.trigger('click');
                setTimeout(() => {
                    this.loadUrlDetailViewInBulk(url);
                }, 100);
            } else {
                this.loadUrlDetailView(url);
            }
        },

        /**
         * Load URL detail view in bulk tab
         */
        loadUrlDetailViewInBulk: function(url) {
            // Store current URL for refresh after operations
            this.currentDetailUrl = url;

            const $container = $('#schemafy-url-detail-container-bulk');
            const $bulkContent = $('#schemafy-tab-bulk');

            if (!$container.length) {
                $bulkContent.prepend('<div id="schemafy-url-detail-container-bulk" style="display: none;"></div>');
            }

            const $detailContainer = $('#schemafy-url-detail-container-bulk');

            $detailContainer.html(`
                <div class="schemafy-card-v2">
                    <div class="schemafy-loading-v2">
                        <div class="schemafy-spinner-v2"></div>
                        <p>Loading schemas for this URL...</p>
                    </div>
                </div>
            `).show();

            $('#schemafy-bulk-manager-main-card').hide();

            $.ajax({
                url: schemafy_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'schemafy_get_schemas_by_url',
                    nonce: schemafy_ajax.nonce,
                    url: url
                },
                success: (response) => {
                    if (response.success) {
                        this.renderUrlDetailViewInBulk(response.data);
                    } else {
                        $detailContainer.html(`
                            <div class="schemafy-card-v2">
                                <div class="schemafy-empty-state-v2">
                                    <div class="schemafy-empty-icon"><span class="dashicons dashicons-warning"></span></div>
                                    <h3>Error loading schemas</h3>
                                    <p>${response.data || 'Unknown error'}</p>
                                </div>
                            </div>
                        `);
                    }
                },
                error: () => {
                    $detailContainer.html(`
                        <div class="schemafy-card-v2">
                            <div class="schemafy-empty-state-v2">
                                <div class="schemafy-empty-icon"><span class="dashicons dashicons-warning"></span></div>
                                <h3>Connection Error</h3>
                                <p>Failed to load schemas for this URL.</p>
                            </div>
                        </div>
                    `);
                }
            });
        },

        /**
         * Render URL detail view
         */
        renderUrlDetailViewInBulk: function(data) {
            const $container = $('#schemafy-url-detail-container-bulk');
            const schemas = data.schemas || [];
            const url = data.url;

            let html = `
                <div class="schemafy-card-v2">
                    <div class="schemafy-url-detail-header">
                        <div class="schemafy-detail-header-left">
                            <button class="schemafy-btn-icon" onclick="SchemafyUrlManager.closeUrlDetailViewInBulk()" title="Go Back">
                                <span class="dashicons dashicons-arrow-left-alt"></span>
                            </button>
                            <div class="schemafy-detail-header-info">
                                <h2>
                                    <span class="dashicons dashicons-admin-links"></span>
                                    Rich Snippets for URL
                                </h2>
                                <div class="schemafy-url-display">
                                    <span class="dashicons dashicons-admin-site"></span>
                                    <a href="${url}" target="_blank" class="schemafy-url-link">${url}</a>
                                </div>
                            </div>
                        </div>
                        <div class="schemafy-detail-header-right">
                            <div class="schemafy-schema-count-badge">
                                <span class="dashicons dashicons-code-standards"></span>
                                <span>${schemas.length} Schema${schemas.length !== 1 ? 's' : ''}</span>
                            </div>
                        </div>
                    </div>
            `;

            if (schemas.length === 0) {
                html += `
                    <div class="schemafy-empty-state-v2">
                        <div class="schemafy-empty-icon"><span class="dashicons dashicons-info"></span></div>
                        <h3>No schemas found</h3>
                        <p>This URL doesn't have any schemas yet.</p>
                    </div>
                `;
            } else {
                html += '<div class="schemafy-url-schemas-list">';
                schemas.forEach(schema => {
                    html += this.renderSchemaCard(schema, url);
                });
                html += '</div>';
            }

            html += '</div>';
            $container.html(html);

            this.bindUrlDetailEvents($container);
        },

        /**
         * Map schema @type to category (same system as URL map chips).
         */
        _getSchemaCategory: function(type) {
            const map = {
                article:    ['Article','BlogPosting','NewsArticle'],
                business:   ['LocalBusiness','Service','Restaurant','CafeOrCoffeeShop','Dentist','Physician',
                             'LegalService','AutoDealer','AutoRepair','AutoWash','Plumber','Electrician',
                             'HVACBusiness','GeneralContractor','RoofingContractor','HousePainter',
                             'BeautySalon','ExerciseGym','LodgingBusiness','RealEstateAgent','InsuranceAgency',
                             'AccountingService','MovingCompany','Florist','VeterinaryCare','Locksmith',
                             'TravelAgency','Optician','ChildCare','ProfessionalService','Physiotherapist',
                             'Pharmacy','FinancialService','HomeAndConstructionBusiness','EventVenue'],
                content:    ['FAQPage','HowTo','Recipe','VideoObject','Review'],
                commerce:   ['Product','Event','Offer'],
                education:  ['JobPosting','Course','Person'],
            };
            for (const [cat, types] of Object.entries(map)) {
                if (types.includes(type)) return cat;
            }
            return 'structural';
        },

        /**
         * Lightweight JSON syntax highlighter.
         * Returns HTML with colour-coded tokens.
         */
        _highlightJson: function(jsonStr) {
            return jsonStr.replace(
                /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?|[{}[\],:])/g,
                function(match) {
                    let cls = 'schemafy-json-num';
                    if (/^"/.test(match)) {
                        cls = /:$/.test(match) ? 'schemafy-json-key' : 'schemafy-json-str';
                    } else if (/true|false/.test(match)) {
                        cls = 'schemafy-json-bool';
                    } else if (/null/.test(match)) {
                        cls = 'schemafy-json-null';
                    } else if (/[{}[\],:]/.test(match)) {
                        cls = 'schemafy-json-punct';
                    }
                    return `<span class="${cls}">${window.SchemafyUtilities.escapeHtml(match)}</span>`;
                }
            );
        },

        /**
         * Render individual schema card
         */
        renderSchemaCard: function(schema, _url) {
            const type     = schema.schema_type || 'Unknown';
            const safeType = window.SchemafyUtilities.escapeHtml(type);
            const safeName = window.SchemafyUtilities.escapeHtml(schema.schema_name || type);
            const icon     = window.SchemafyUtilities ? window.SchemafyUtilities.getSchemaTypeIcon(type) : '📄';
            const cat      = this._getSchemaCategory(type);

            const statusClass = schema.is_active ? 'active' : 'inactive';
            const statusText  = schema.is_active ? 'Active' : 'Inactive';

            const safeId = parseInt(schema.id, 10);

            return `
                <div class="schemafy-schema-card-v2" data-id="${safeId}" data-category="${cat}">
                    <div class="schemafy-schema-card-header">
                        <div class="schemafy-schema-type-icon-box">${icon}</div>
                        <div class="schemafy-schema-card-info">
                            <h4>${safeName}</h4>
                            <div class="schemafy-schema-card-info-row">
                                <span class="schemafy-schema-type-badge">${safeType}</span>
                                <span class="schemafy-schema-status schemafy-status-${statusClass}">${statusText}</span>
                            </div>
                        </div>
                    </div>
                    <div class="schemafy-schema-card-actions">
                        <button class="schemafy-schema-action-btn schemafy-edit-url-schema" data-id="${safeId}">
                            <span class="dashicons dashicons-edit"></span>Edit
                        </button>
                        <button class="schemafy-schema-action-btn schemafy-toggle-url-schema" data-id="${safeId}">
                            <span class="dashicons dashicons-image-rotate"></span>Toggle
                        </button>
                        <button class="schemafy-schema-action-btn schemafy-duplicate-url-schema" data-id="${safeId}">
                            <span class="dashicons dashicons-admin-page"></span>Duplicate
                        </button>
                        <div class="schemafy-action-separator"></div>
                        <button class="schemafy-schema-action-btn schemafy-action-delete schemafy-delete-url-schema" data-id="${safeId}" title="Delete schema">
                            <span class="dashicons dashicons-trash"></span>
                        </button>
                    </div>
                </div>
            `;
        },

        /**
         * Bind URL detail view events
         */
        bindUrlDetailEvents: function($container) {
            const self = this;

            // Copy JSON to clipboard
            $container.off('click', '.schemafy-preview-copy-btn').on('click', '.schemafy-preview-copy-btn', function(e) {
                e.stopPropagation();
                const id  = $(this).data('id');
                const $card = $container.find(`.schemafy-schema-card-v2[data-id="${id}"]`);
                const text = $card.find('pre code').text();
                navigator.clipboard.writeText(text).then(() => {
                    const $btn = $(this);
                    $btn.html('<span class="dashicons dashicons-yes"></span>Copied!');
                    setTimeout(() => $btn.html('<span class="dashicons dashicons-admin-page"></span>Copy'), 1800);
                }).catch(() => {
                    window.SchemafyUtilities && window.SchemafyUtilities.showNotification('Copy failed', 'error');
                });
            });

            $container.off('click', '.schemafy-edit-url-schema').on('click', '.schemafy-edit-url-schema', function(e) {
                e.stopPropagation();
                if (window.SchemafyOperations) {
                    window.SchemafyOperations.editSchema($(this).data('id'));
                }
            });

            $container.off('click', '.schemafy-toggle-url-schema').on('click', '.schemafy-toggle-url-schema', function(e) {
                e.stopPropagation();
                const id = $(this).data('id');
                self.toggleSchemaInUrlView(id);
            });

            $container.off('click', '.schemafy-duplicate-url-schema').on('click', '.schemafy-duplicate-url-schema', function(e) {
                e.stopPropagation();
                const id = $(this).data('id');
                self.duplicateSchemaInUrlView(id);
            });

            $container.off('click', '.schemafy-delete-url-schema').on('click', '.schemafy-delete-url-schema', function(e) {
                e.stopPropagation();
                const id = $(this).data('id');
                self.deleteSchemaInUrlView(id);
            });
        },

        /**
         * Toggle schema and refresh view
         */
        toggleSchemaInUrlView: function(id) {
            const self = this;
            $.ajax({
                url: schemafy_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'schemafy_toggle_schema',
                    nonce: schemafy_ajax.nonce,
                    id: id
                },
                success: function(response) {
                    if (response.success) {
                        window.SchemafyUtilities.showNotification('Schema toggled successfully', 'success');
                        // Refresh the URL detail view
                        if (self.currentDetailUrl) {
                            self.loadUrlDetailViewInBulk(self.currentDetailUrl);
                        }
                    } else {
                        window.SchemafyUtilities.showNotification(response.data || 'Error toggling schema', 'error');
                    }
                },
                error: function() {
                    window.SchemafyUtilities.showNotification('Network error', 'error');
                }
            });
        },

        /**
         * Duplicate schema and refresh view
         */
        duplicateSchemaInUrlView: function(id) {
            const self = this;
            window.SchemafyUtilities.confirm(
                'Duplicate this schema?',
                function() {
                    $.ajax({
                        url: schemafy_ajax.ajax_url,
                        type: 'POST',
                        data: {
                            action: 'schemafy_duplicate_schema',
                            nonce: schemafy_ajax.nonce,
                            id: id
                        },
                        success: function(response) {
                            if (response.success) {
                                window.SchemafyUtilities.showNotification('Schema duplicated successfully', 'success');
                                // Refresh the URL detail view
                                if (self.currentDetailUrl) {
                                    self.loadUrlDetailViewInBulk(self.currentDetailUrl);
                                }
                            } else {
                                window.SchemafyUtilities.showNotification(response.data || 'Error duplicating schema', 'error');
                            }
                        },
                        error: function() {
                            window.SchemafyUtilities.showNotification('Network error', 'error');
                        }
                    });
                }
            );
        },

        /**
         * Delete schema and refresh view
         */
        deleteSchemaInUrlView: function(id) {
            const self = this;
            window.SchemafyUtilities.confirm(
                'Are you sure you want to delete this schema? This action cannot be undone.',
                function() {
                    $.ajax({
                        url: schemafy_ajax.ajax_url,
                        type: 'POST',
                        data: {
                            action: 'schemafy_delete_schema',
                            nonce: schemafy_ajax.nonce,
                            id: id
                        },
                        success: function(response) {
                            if (response.success) {
                                window.SchemafyUtilities.showNotification('Schema deleted successfully', 'success');
                                // Refresh the URL detail view
                                if (self.currentDetailUrl) {
                                    self.loadUrlDetailViewInBulk(self.currentDetailUrl);
                                }
                                // Also refresh dashboard stats
                                if (window.SchemafyDashboard) {
                                    window.SchemafyDashboard.refreshStats();
                                }
                            } else {
                                window.SchemafyUtilities.showNotification(response.data || 'Error deleting schema', 'error');
                            }
                        },
                        error: function() {
                            window.SchemafyUtilities.showNotification('Network error', 'error');
                        }
                    });
                }
            );
        },

        /**
         * Close URL detail view in bulk tab
         */
        closeUrlDetailViewInBulk: function() {
            $('#schemafy-url-detail-container-bulk').hide().empty();
            $('#schemafy-bulk-manager-main-card').show();
            this.currentDetailUrl = null;
            // Refresh the bulk table to reflect any changes made in URL detail view
            if (window.SchemafyBulk && typeof window.SchemafyBulk.loadBulkSchemas === 'function') {
                window.SchemafyBulk.loadBulkSchemas();
            }
        },

        /**
         * Load URL detail view (dashboard)
         */
        loadUrlDetailView: function(url) {
            // Store current URL for refresh
            this.currentDetailUrl = url;

            const $container = $('#schemafy-url-detail-view');
            const $dashboardContent = $('#schemafy-tab-dashboard');

            $container.html(`
                <div class="schemafy-card-v2">
                    <div class="schemafy-loading-v2">
                        <div class="schemafy-spinner-v2"></div>
                        <p>Loading schemas for this URL...</p>
                    </div>
                </div>
            `).show();

            $dashboardContent.hide();

            $.ajax({
                url: schemafy_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'schemafy_get_schemas_by_url',
                    nonce: schemafy_ajax.nonce,
                    url: url
                },
                success: (response) => {
                    if (response.success) {
                        this.renderUrlDetailView(response.data);
                    } else {
                        $container.html(`
                            <div class="schemafy-card-v2">
                                <div class="schemafy-empty-state-v2">
                                    <h3>Error loading schemas</h3>
                                    <p>${response.data || 'Unknown error'}</p>
                                </div>
                            </div>
                        `);
                    }
                },
                error: () => {
                    $container.html('<p>Connection error</p>');
                }
            });
        },

        /**
         * Render URL detail view (dashboard)
         */
        renderUrlDetailView: function(data) {
            const $container = $('#schemafy-url-detail-view');
            const schemas = data.schemas || [];
            const url = data.url;

            let html = `
                <div class="schemafy-card-v2">
                    <div class="schemafy-url-detail-header">
                        <button class="schemafy-btn-icon" onclick="SchemafyUrlManager.closeUrlDetailView()" title="Go Back">
                            <span class="dashicons dashicons-arrow-left-alt"></span>
                        </button>
                        <div>
                            <h2>Schemas for URL</h2>
                            <a href="${url}" target="_blank">${url}</a>
                        </div>
                        <div class="schemafy-schema-count-badge">${schemas.length} Schema${schemas.length !== 1 ? 's' : ''}</div>
                    </div>
            `;

            if (schemas.length === 0) {
                html += '<div class="schemafy-empty-state-v2"><h3>No schemas found</h3></div>';
            } else {
                html += '<div class="schemafy-url-schemas-list">';
                schemas.forEach(schema => {
                    html += this.renderSchemaCard(schema, url);
                });
                html += '</div>';
            }

            html += '</div>';
            $container.html(html);
            this.bindUrlDetailEvents($container);
        },

        /**
         * Close URL detail view (dashboard)
         */
        closeUrlDetailView: function() {
            $('#schemafy-url-detail-view').hide().empty();
            $('#schemafy-tab-dashboard').show();
            this.currentDetailUrl = null;
            // Refresh dashboard to reflect any changes
            if (window.SchemafyDashboard) {
                window.SchemafyDashboard.loadDashboard();
            }
        }
    };

})(jQuery);
