/**
 * DazyDay Engine — admin JS.
 */
(function ($) {
    'use strict';

    var cfg = window.dazydayEngineAdmin || {};
    if (!cfg.ajaxUrl) { return; }

    function ajaxPost(data) {
        data.action = data.action || '';
        data.nonce  = cfg.adminNonce || '';
        return $.ajax({ url: cfg.ajaxUrl, method: 'POST', dataType: 'json', data: data });
    }

    var pollTimer = null;
    var polling   = false;
    var activeImports = {};
    var activeHosts   = {};

    function showNotice(msg, kind) {
        var el = $('#dazyday-engine-csv-notice');
        el.removeClass('dazyday-engine-status--error dazyday-engine-status--ok');
        if (kind) { el.addClass('dazyday-engine-status--' + kind); }
        el.text(msg).prop('hidden', false);
        window.setTimeout(function () { el.prop('hidden', true); }, 6000);
    }

    /* --- Create modal --- */

    function openCreateModal() {
        $('#dazyday-engine-create-modal').prop('hidden', false);
        $('#dazyday-create-name').trigger('focus');
    }
    function closeCreateModal() {
        $('#dazyday-engine-create-modal').prop('hidden', true);
        $('#dazyday-engine-create-form')[0].reset();
        $('#dazyday-engine-create-error').prop('hidden', true);
    }

    $(document).on('click', '#dazyday-engine-open-create', function (e) { e.preventDefault(); openCreateModal(); });
    $(document).on('click', '#dazyday-engine-create-cancel, .dazyday-engine-modal__backdrop', function (e) { e.preventDefault(); closeCreateModal(); });
    $(document).on('keydown', function (e) {
        if (e.key === 'Escape' && !$('#dazyday-engine-create-modal').prop('hidden')) { closeCreateModal(); }
    });

    $(document).on('submit', '#dazyday-engine-create-form', function (e) {
        e.preventDefault();
        var $form = $(this);
        var name  = $.trim($form.find('#dazyday-create-name').val());
        var year  = parseInt($form.find('#dazyday-create-year').val(), 10);
        var $err  = $('#dazyday-engine-create-error');
        $err.prop('hidden', true).find('p').text('');

        // Detect the import type from the parent container
        var importType = $('#dazyday-engine-csv-data').data('type') || 'movies';

        if (!name) { $err.prop('hidden', false).find('p').text('Please enter a name.'); return; }
        if (!year || year < 1800 || year > 2200) { $err.prop('hidden', false).find('p').text('Enter a year between 1800 and 2200.'); return; }

        var $btn = $('#dazyday-engine-create-submit');
        $btn.prop('disabled', true).text('Creating…');

        ajaxPost({ action: 'dazyday_engine_csv_create', name: name, year: year, import_type: importType })
        .done(function (resp) {
            if (!resp || !resp.success) {
                $err.prop('hidden', false).find('p').text((resp && resp.data && resp.data.message) || 'Could not create CSV.');
                $btn.prop('disabled', false).text('Create');
                return;
            }
            window.location.href = resp.data.redirect;
        }).fail(function (xhr, status) {
            var extra = xhr && xhr.responseText ? ' — ' + xhr.responseText.substring(0, 200) : '';
            $err.prop('hidden', false).find('p').text('Network error: ' + status + extra);
            $btn.prop('disabled', false).text('Create');
        });
    });

    /* --- Delete batch --- */

    $(document).on('click', '.dazyday-engine-delete-batch', function (e) {
        e.preventDefault();
        var $btn = $(this);
        var batchId = parseInt($btn.data('batch-id'), 10);
        var name = $btn.data('batch-name') || 'this CSV';
        var confirmMsg = (cfg.i18n && cfg.i18n.confirmDel) ? cfg.i18n.confirmDel : 'Delete this CSV and all its imported movies and hosted images?';
        if (!window.confirm(name + '\n\n' + confirmMsg)) { return; }

        $btn.prop('disabled', true).text('Deleting…');
        showNotice('Deleting ' + name + '…');

        ajaxPost({ action: 'dazyday_engine_csv_delete', batch_id: batchId })
        .done(function (resp) {
            if (!resp || !resp.success) {
                showNotice((resp && resp.data && resp.data.message) || 'Delete failed.', 'error');
                $btn.prop('disabled', false).text('Delete');
                return;
            }
            $('#dazyday-engine-csv-table tr[data-batch-id="' + batchId + '"]').fadeOut(200, function () {
                $(this).remove();
                if ($('#dazyday-engine-csv-table tbody tr').length === 0) {
                    $('#dazyday-engine-csv-table tbody').html(
                        '<tr><td colspan="8" class="dazyday-engine-csv-table__empty">No CSV files yet. Click "Create CSV" to make your first one.</td></tr>'
                    );
                }
            });
            showNotice('Deleted ' + name + '.', 'ok');
        }).fail(function () {
            showNotice('Network error while deleting.', 'error');
            $btn.prop('disabled', false).text('Delete');
        });
    });

    /* --- Host Images button --- */

    $(document).on('click', '.dazyday-engine-host-images', function (e) {
        e.preventDefault();
        var $btn = $(this);
        var batchId = parseInt($btn.data('batch-id'), 10);
        if (!batchId) { return; }

        if (!window.confirm('Start hosting all images for this CSV? This will download from TMDB and may take several minutes.')) { return; }

        $btn.prop('disabled', true).text('Queuing…');
        showNotice('Queuing images…');

        ajaxPost({ action: 'dazyday_engine_queue_images', batch_id: batchId })
        .done(function (resp) {
            if (!resp || !resp.success) {
                showNotice((resp && resp.data && resp.data.message) || 'Could not queue images.', 'error');
                $btn.prop('disabled', false).text('Host Images');
                return;
            }
            showNotice('Queued ' + resp.data.queued + ' new images. Hosting started.', 'ok');
            $btn.text('Hosting…');
            // Start worker for this batch immediately.
            if (!activeHosts[batchId]) {
                activeHosts[batchId] = true;
                runHostChunk(batchId);
            }
            // Kick off a stats refresh so we see progress.
            window.setTimeout(pollStats, 500);
        }).fail(function () {
            showNotice('Network error while queuing images.', 'error');
            $btn.prop('disabled', false).text('Host Images');
        });
    });

    /* --- Live counters --- */

    function formatNumber(n) { return (parseInt(n, 10) || 0).toLocaleString(); }

    function updateRowFromStats(row) {
        var $tr = $('#dazyday-engine-csv-table tr[data-batch-id="' + row.id + '"]');
        if (!$tr.length) { return; }

        var $cell = $tr.find('.dazyday-engine-csv-images');
        if ($cell.length) {
            var total = parseInt(row.image_total, 10) || 0;
            var hosted = parseInt(row.image_hosted, 10) || 0;
            var text = total > 0 ? (formatNumber(hosted) + ' / ' + formatNumber(total)) : '—';
            if ($cell.text().trim() !== text) { $cell.text(text); }
        }

        var $statusCell = $tr.children('td').eq(5);
        if ($statusCell.length) {
            var currentStatus = $tr.data('status');
            if (currentStatus !== row.status) {
                $tr.data('status', row.status);
                var pill = $statusCell.find('.dazyday-engine-status-pill');
                pill.attr('class', 'dazyday-engine-status-pill dazyday-engine-status-pill--' + row.status).text(row.status);
            }
        }

        var $importedCell = $tr.find('.dazyday-engine-csv-imported');
        if ($importedCell.length) {
            var processed = parseInt(row.processed_rows, 10) || 0;
            var imported = parseInt(row.imported_rows, 10) || 0;
            var failed = parseInt(row.failed_rows, 10) || 0;
            var rowCount = parseInt(row.row_count, 10) || 0;

            var isImporting = (row.status === 'importing' || row.status === 'queued');

            if (isImporting) {
                var pct = rowCount > 0 ? Math.min(100, Math.round((processed / rowCount) * 100)) : 0;
                var miniHtml =
                    '<div class="dazyday-engine-mini-progress">' +
                    '<div class="dazyday-engine-mini-progress__bar"><span style="width:' + pct + '%"></span></div>' +
                    '<span class="dazyday-engine-mini-progress__text">' + formatNumber(processed) + ' / ' + formatNumber(rowCount) + '</span>' +
                    '</div>';
                if ($importedCell.html() !== miniHtml) { $importedCell.html(miniHtml); }
                if (!activeImports[row.id]) {
                    activeImports[row.id] = true;
                    resumeImport(row.id);
                }
            } else {
                var finalHtml = '';
                if (imported > 0 || failed > 0) {
                    finalHtml = formatNumber(imported);
                    if (failed > 0) { finalHtml += ' <span class="dazyday-engine-text-error">(' + formatNumber(failed) + ' failed)</span>'; }
                } else { finalHtml = '—'; }
                if ($importedCell.html().trim() !== finalHtml.trim()) { $importedCell.html(finalHtml); }
                delete activeImports[row.id];
            }
        }

        // Auto-start hosting worker if the batch is in 'hosting' state.
        if (row.status === 'hosting' && row.image_total > 0 && row.image_hosted < row.image_total) {
            if (!activeHosts[row.id]) {
                activeHosts[row.id] = true;
                runHostChunk(row.id);
            }
        } else if (row.status !== 'hosting') {
            delete activeHosts[row.id];
        }
    }

    function resumeImport(batchId) {
        var sendChunk = function () {
            ajaxPost({ action: 'dazyday_engine_csv_import_chunk', batch_id: batchId })
            .done(function (resp) {
                if (!resp || !resp.success) { window.setTimeout(sendChunk, 3000); return; }
                var d = resp.data;
                if (d.done) { delete activeImports[batchId]; window.setTimeout(pollStats, 500); return; }
                window.setTimeout(sendChunk, 200);
            }).fail(function () { window.setTimeout(sendChunk, 3000); });
        };
        sendChunk();
    }

    function runHostChunk(batchId) {
        var send = function () {
            ajaxPost({ action: 'dazyday_engine_host_images_chunk', batch_id: batchId })
            .done(function (resp) {
                if (!resp || !resp.success) {
                    window.setTimeout(send, 3000);
                    return;
                }
                var d = resp.data || {};
                window.setTimeout(pollStats, 100);
                if (d.done) {
                    delete activeHosts[batchId];
                    return;
                }
                // Slight delay between chunks so the server can breathe.
                window.setTimeout(send, 200);
            }).fail(function () {
                window.setTimeout(send, 3000);
            });
        };
        send();
    }

    function pollStats() {
        if (polling) { return; }
        polling = true;

        ajaxPost({ action: 'dazyday_engine_csv_stats' }).done(function (resp) {
            polling = false;
            if (!resp || !resp.success) { return; }
            var data = resp.data || {};
            var batches = data.batches || [];
            batches.forEach(updateRowFromStats);

            var $storageBar = $('.dazyday-engine-csv-data__storage .dazyday-engine-storage__bar span');
            if ($storageBar.length && data.storage_limit > 0) {
                var pct = Math.min(100, Math.round((data.storage_used / data.storage_limit) * 10000) / 100);
                $storageBar.css('width', pct + '%');
            }
        }).fail(function () { polling = false; });
    }

    function startPolling() {
        if (pollTimer) { return; }
        pollTimer = window.setInterval(pollStats, 3000);
    }
    function stopPolling() {
        if (pollTimer) { window.clearInterval(pollTimer); pollTimer = null; }
    }

    if ($('#dazyday-engine-csv-table').length) {
        startPolling();
        window.setTimeout(pollStats, 500);
    }

    document.addEventListener('visibilitychange', function () {
        if (document.hidden) { stopPolling(); }
        else if ($('#dazyday-engine-csv-table').length) { startPolling(); pollStats(); }
    });

})(jQuery);