/**
 * Dashboard Module
 * Handles: Stats loading, URL map, charts
 */
(function($) {
    'use strict';

    window.SchemafyDashboard = {
        /**
         * Load entire dashboard
         */
        loadDashboard: function() {
            this.loadStats();
            this.loadUrlMap();
            this.loadTypesChart();
        },

        /**
         * Load statistics
         */
        loadStats: function() {
            $.ajax({
                url: schemafy_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'schemafy_get_stats',
                    nonce: schemafy_ajax.nonce
                },
                success: (response) => {
                    if (response.success) {
                        const stats = response.data;
                        $('#schemafy-stat-urls').text(stats.total_urls || 0);
                        $('#schemafy-stat-total').text(stats.total_schemas || 0);
                        $('#schemafy-stat-active').text(stats.active_schemas || 0);
                        $('#schemafy-stat-inactive').text(stats.inactive_schemas || 0);
                        this.renderCoverageChart(stats);
                    }
                }
            });
        },

        /**
         * Render the donut coverage chart
         */
        renderCoverageChart: function(stats) {
            const totalPages  = stats.total_published_pages || 0;
            const covered     = stats.total_urls            || 0;
            const totalSchemas = stats.total_schemas        || 0;
            const active      = stats.active_schemas        || 0;
            const missing     = Math.max(0, totalPages - covered);

            // If WordPress has no published pages yet, treat covered URLs as 100%
            const base = totalPages > 0 ? totalPages : (covered > 0 ? covered : 1);
            const pct  = Math.min(100, Math.round((covered / base) * 100));
            const activeRate = totalSchemas > 0 ? Math.round((active / totalSchemas) * 100) : 0;

            // SVG donut math — r=50, circumference ≈ 314.16
            const circumference = 2 * Math.PI * 50;
            const coveredArc    = (covered / base) * circumference;

            // Colour by coverage bracket
            const color = pct >= 70 ? '#22c55e' : pct >= 30 ? '#f59e0b' : '#ef4444';

            // Animate the arc
            const arc = document.getElementById('schemafy-donut-arc-covered');
            if (arc) {
                arc.style.stroke = color;
                arc.setAttribute('stroke-dasharray', coveredArc.toFixed(2) + ' ' + circumference.toFixed(2));
            }

            // % label
            const $pct = $('#schemafy-coverage-pct');
            $pct.text(pct + '%').css('color', color);

            // Headline
            const $hl = $('#schemafy-coverage-headline');
            if (pct >= 70) {
                $hl.text('Great coverage! Keep it up.').removeClass('schemafy-cov-ok schemafy-cov-bad').addClass('schemafy-cov-good');
            } else if (pct >= 30) {
                $hl.text('Room to grow — ' + missing + ' page' + (missing !== 1 ? 's' : '') + ' still need schemas.').removeClass('schemafy-cov-good schemafy-cov-bad').addClass('schemafy-cov-ok');
            } else if (covered === 0) {
                $hl.text('No schemas yet — add your first schema to get started.').removeClass('schemafy-cov-good schemafy-cov-ok').addClass('schemafy-cov-bad');
            } else {
                $hl.text('Low coverage — most pages lack schema markup.').removeClass('schemafy-cov-good schemafy-cov-ok').addClass('schemafy-cov-bad');
            }

            // Stat values
            $('#schemafy-cov-covered-val').text(covered + ' / ' + totalPages);
            $('#schemafy-cov-missing-val').text(missing);
            $('#schemafy-cov-schemas-val').text(totalSchemas);
            $('#schemafy-cov-active-val').text(activeRate + '%');

            // Tip
            const $tip = $('#schemafy-coverage-tip');
            if (totalSchemas === 0) {
                $tip.html('<strong>Tip:</strong> Add your first schema using the <a href="#" data-tab="builder">Smart Builder</a> — it takes under a minute.').show();
            } else if (missing > 0) {
                $tip.html('<strong>Tip:</strong> Use the <a href="#" data-tab="auto-generator">Auto Generator</a> to detect and add schemas to your ' + missing + ' uncovered page' + (missing !== 1 ? 's' : '') + ' in bulk.').show();
            } else {
                $tip.html('<strong>All pages covered!</strong> Your site has excellent schema markup. Keep schemas active for best SEO results.').show();
            }

            // Tip link tab switching
            $tip.find('a[data-tab]').off('click.covTip').on('click.covTip', function(e) {
                e.preventDefault();
                const tab = $(this).data('tab');
                $('[data-tab="' + tab + '"]').first().trigger('click');
            });
        },

        /**
         * Load URL map with pagination and optional search
         */
        loadUrlMap: function(page = 1, search = '') {
            const $container = $('#schemafy-url-map-container');
            $container.html('<div class="schemafy-loading-v2"><div class="schemafy-spinner-v2"></div><p>Loading URL map...</p></div>');

            $.ajax({
                url: schemafy_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'schemafy_get_url_map',
                    page: page,
                    per_page: 20,
                    search: search,
                    nonce: schemafy_ajax.nonce
                },
                success: (response) => {
                    if (response.success && response.data) {
                        const data = response.data;
                        const urls = data.urls || [];

                        if (Array.isArray(urls) && urls.length > 0) {
                            this.renderUrlMap(urls, data);
                        } else {
                            // Page has no URLs but others may exist — keep pagination visible
                            const totalUrls = data.total || 0;
                            let emptyHtml = `
                                <div class="schemafy-builder-placeholder">
                                    <span class="dashicons dashicons-location"></span>
                                    <h3>No schemas found on this page</h3>
                                    <p>Create your first schema to see it here</p>
                                    ${totalUrls > 0 ? `<p style="font-size:12px;color:#666;">Total URLs with schemas: ${totalUrls}</p>` : ''}
                                </div>
                            `;
                            if (data.total_pages > 1 && window.SchemafyUtilities) {
                                emptyHtml += window.SchemafyUtilities.renderPagination(data);
                            }
                            $container.html(emptyHtml);
                            this.bindPaginationHandlers($container);
                        }
                    } else {
                        const errMsg = (response && response.data) ? response.data : 'Server error loading URL map';
                        $container.html(`<div class="schemafy-error-state"><span class="dashicons dashicons-warning"></span><p>${errMsg}</p></div>`);
                    }
                },
                error: () => {
                    $container.html('<div class="schemafy-error-state"><span class="dashicons dashicons-warning"></span><p>Network error loading URL map. Please refresh the page.</p></div>');
                }
            });
        },

        /**
         * Map schema type → chip colour category.
         */
        _schemaCategory: function(type) {
            const map = {
                structural: ['Organization','WebSite','WebPage','AboutPage','ContactPage','BreadcrumbList'],
                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';
        },

        /**
         * Split a URL into { domain, path } for display.
         */
        _splitUrl: function(url) {
            try {
                const u = new URL(url);
                const path = u.pathname === '/' ? '/ (Home)' : u.pathname;
                return { domain: u.hostname, path };
            } catch(e) {
                return { domain: '', path: url };
            }
        },

        /**
         * Render URL map grid
         */
        renderUrlMap: function(urlData, pagination) {
            const $container = $('#schemafy-url-map-container');
            const MAX_CHIPS   = 5;
            let html = '<div class="schemafy-url-map-grid">';

            urlData.forEach(item => {
                const urlForAttr = item.url.replace(/"/g, '&quot;');
                const { domain, path } = this._splitUrl(item.url);
                const safePath   = window.SchemafyUtilities.escapeHtml(path);
                const safeDomain = window.SchemafyUtilities.escapeHtml(domain);
                const safeUrl    = window.SchemafyUtilities.escapeHtml(item.url);

                // Detect dominant category for left accent
                const catCounts = {};
                item.schemas.forEach(s => {
                    if (s.is_active) {
                        const c = this._schemaCategory(s.type);
                        catCounts[c] = (catCounts[c] || 0) + 1;
                    }
                });
                const accent = Object.keys(catCounts).length
                    ? Object.keys(catCounts).reduce((a, b) => catCounts[a] >= catCounts[b] ? a : b)
                    : 'structural';

                // Build chips — max MAX_CHIPS visible
                const visible  = item.schemas.slice(0, MAX_CHIPS);
                const overflow = item.schemas.length - MAX_CHIPS;

                const schemaChips = visible.map(schema => {
                    const safeType = window.SchemafyUtilities.escapeHtml(schema.type);
                    if (!schema.is_active) {
                        return `<span class="schemafy-schema-chip schemafy-schema-chip-inactive" title="Inactive">○ ${safeType}</span>`;
                    }
                    const cat = this._schemaCategory(schema.type);
                    return `<span class="schemafy-schema-chip schemafy-chip-${cat}"><span class="schemafy-chip-dot"></span>${safeType}</span>`;
                }).join('');

                const overflowChip = overflow > 0
                    ? `<span class="schemafy-schema-chip schemafy-chip-overflow">+${overflow}</span>`
                    : '';

                html += `
                    <div class="schemafy-url-card" data-url="${urlForAttr}" data-accent="${accent}" tabindex="0" role="button" aria-label="View schemas for ${safeUrl}">
                        <div class="schemafy-url-card-header">
                            <div class="schemafy-url-card-meta">
                                <div class="schemafy-url-card-path">${safePath}</div>
                                <div class="schemafy-url-card-domain">${safeDomain}</div>
                            </div>
                            <div class="schemafy-url-badge">${item.count}</div>
                        </div>
                        <div class="schemafy-url-card-schemas">${schemaChips}${overflowChip}</div>
                        <div class="schemafy-url-card-actions">
                            <button class="schemafy-url-card-action schemafy-url-action-open" data-url="${urlForAttr}">
                                <span class="dashicons dashicons-arrow-right-alt"></span>Open
                            </button>
                            <button class="schemafy-url-card-action schemafy-url-action-add" data-url="${urlForAttr}">
                                <span class="dashicons dashicons-plus-alt2"></span>Add
                            </button>
                            <button class="schemafy-url-card-action schemafy-url-action-visit" data-url="${urlForAttr}">
                                <span class="dashicons dashicons-external"></span>Visit
                            </button>
                        </div>
                    </div>
                `;
            });

            html += '</div>';

            if (pagination && pagination.total_pages > 1) {
                html += window.SchemafyUtilities.renderPagination(pagination);
            }

            $container.html(html);

            // Card click — open URL detail (ignore action bar clicks)
            $container.off('click', '.schemafy-url-card').on('click', '.schemafy-url-card', function(e) {
                if ($(e.target).closest('.schemafy-url-card-action').length) return;
                const url = $(this).data('url');
                if (window.SchemafyUrlManager) window.SchemafyUrlManager.openUrlSchemas(url);
            });

            // Action: Open
            $container.off('click', '.schemafy-url-action-open').on('click', '.schemafy-url-action-open', function(e) {
                e.stopPropagation();
                const url = $(this).data('url');
                if (window.SchemafyUrlManager) window.SchemafyUrlManager.openUrlSchemas(url);
            });

            // Action: Add schema — open Smart Builder pre-filtered to URL
            $container.off('click', '.schemafy-url-action-add').on('click', '.schemafy-url-action-add', function(e) {
                e.stopPropagation();
                const url = $(this).data('url');
                // Switch to builder tab and pass URL as filter
                $('[data-tab="builder"]').trigger('click');
                setTimeout(() => {
                    const $search = $('#schemafy-url-search, #schemafy-smart-builder-url-search, .schemafy-url-search').first();
                    if ($search.length) {
                        $search.val(url).trigger('input');
                    }
                }, 200);
            });

            // Action: Visit page in new tab
            $container.off('click', '.schemafy-url-action-visit').on('click', '.schemafy-url-action-visit', function(e) {
                e.stopPropagation();
                window.open($(this).data('url'), '_blank', 'noopener');
            });

            // Keyboard support for URL cards (accessibility + fix Enter key bug)
            $container.off('keydown', '.schemafy-url-card').on('keydown', '.schemafy-url-card', function(e) {
                // Handle Enter or Space key
                if (e.key === 'Enter' || e.keyCode === 13 || e.key === ' ' || e.keyCode === 32) {
                    e.preventDefault(); // Prevent form submission or page scroll
                    e.stopPropagation(); // Prevent event bubbling

                    const url = $(this).data('url');
                    if (window.SchemafyUrlManager) {
                        window.SchemafyUrlManager.openUrlSchemas(url);
                    }
                }
            });

            this.bindPaginationHandlers($container);
        },

        bindPaginationHandlers: function($container) {
            $container.off('click', '.schemafy-pagination-btn').on('click', '.schemafy-pagination-btn', (e) => {
                const page = parseInt($(e.currentTarget).data('page'));
                const currentSearch = $('#schemafy-url-map-search').val() || '';
                this.loadUrlMap(page, currentSearch.trim());
            });
        },

        /**
         * Filter URL map by search query (server-side)
         */
        filterUrlMap: function(search) {
            const query = (search || '').trim();
            this.loadUrlMap(1, query);
        },

        /**
         * Load schema types distribution chart
         */
        loadTypesChart: function() {
            $.ajax({
                url: schemafy_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'schemafy_get_types_distribution',
                    nonce: schemafy_ajax.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.renderTypesChart(response.data);
                    }
                }
            });
        },

        /**
         * Render types distribution chart
         */
        renderTypesChart: function(typesData) {
            const $container = $('#schemafy-types-chart');

            const sorted = Object.entries(typesData).sort((a, b) => b[1] - a[1]);

            if (!sorted.length) {
                $container.html('<p style="color:var(--schemafy-gray-400);font-size:13px;padding:4px 0;">No schemas found yet.</p>');
                return;
            }

            let html = '<div class="schemafy-types-list">';
            sorted.forEach(([type, count]) => {
                const safeType = window.SchemafyUtilities.escapeHtml(type);
                html += `
                    <div class="schemafy-type-row">
                        <span class="schemafy-type-name">${safeType}</span>
                        <span class="schemafy-type-count">${count}</span>
                    </div>
                `;
            });
            html += '</div>';
            $container.html(html);
        },

        /**
         * Refresh all stats
         */
        refreshStats: function() {
            this.loadStats();
            this.loadUrlMap();
            this.loadTypesChart();
            if (window.SchemafyUtilities) {
                window.SchemafyUtilities.showNotification('Stats refreshed', 'success');
            }
        },

        /**
         * Bind dashboard-specific UI events
         */
        bindEvents: function() {
            const self = this;
            // "#schemafy-refresh-dashboard" button in the dashboard tab header
            $(document).off('click.schemafyDashRefresh', '#schemafy-refresh-dashboard')
                .on('click.schemafyDashRefresh', '#schemafy-refresh-dashboard', function() {
                    self.refreshStats();
                });
        }
    };

    $(document).ready(function() {
        if (typeof schemafy_ajax !== 'undefined' && window.SchemafyDashboard) {
            window.SchemafyDashboard.bindEvents();
        }
    });

})(jQuery);
