/* global podcastmakerBulk */
(function () {
    'use strict';

    var pollTimer     = null;
    var statusInFlight = false;

    function el(id) { return document.getElementById(id); }

    function post(action, data) {
        var body = new URLSearchParams(
            Object.assign({ action: action, nonce: podcastmakerBulk.nonce }, data)
        );
        return fetch(podcastmakerBulk.ajaxUrl, { method: 'POST', body: body })
            .then(function (r) { return r.json(); });
    }

    var PAGE_SIZE     = 10;
    var searchResults = [];
    var currentPage   = 1;

    var searchBtn = el('pm-bulk-search-btn');
    if (searchBtn) {
        searchBtn.addEventListener('click', function () {
            searchBtn.disabled = true;
            searchBtn.textContent = '検索中...';
            post('podcastmaker_bulk_search', {
                category_id:   el('pm-bulk-category')   ? el('pm-bulk-category').value   : '0',
                author_id:     el('pm-bulk-author')      ? el('pm-bulk-author').value     : '0',
                date_after:    el('pm-bulk-date-after')  ? el('pm-bulk-date-after').value : '',
                date_before:   el('pm-bulk-date-before') ? el('pm-bulk-date-before').value: '',
                no_audio_only: el('pm-bulk-no-audio') && el('pm-bulk-no-audio').checked ? '1' : '0',
            }).then(function (res) {
                searchBtn.disabled = false;
                searchBtn.textContent = '絞り込みを実行';
                if (!res.success) { return; }
                searchResults = res.data.posts;
                currentPage   = 1;
                var count = res.data.count;
                var countEl    = el('pm-bulk-count');
                var countBadge = el('pm-bulk-count-badge');
                if (countEl)    { countEl.textContent    = count; }
                if (countBadge) { countBadge.style.display = ''; }
                var previewCard = el('pm-bulk-preview-card');
                if (previewCard) { previewCard.style.display = ''; }
                renderPreviewList(searchResults, 1);
                if (startBtn) { startBtn.disabled = count === 0; }
            });
        });
    }

    function buildPreviewItem(p) {
        var li = document.createElement('li');
        li.className = 'pm-preview-item';

        var titleLink = document.createElement('a');
        titleLink.href      = p.url;
        titleLink.target    = '_blank';
        titleLink.rel       = 'noopener noreferrer';
        titleLink.textContent = p.title;
        titleLink.className = 'pm-preview-title';

        var excerpt = document.createElement('p');
        excerpt.textContent = p.excerpt;
        excerpt.className   = 'pm-preview-excerpt';

        var meta = document.createElement('div');
        meta.className = 'pm-preview-meta';

        var authorSpan = document.createElement('span');
        authorSpan.textContent = p.author;
        var dateSpan = document.createElement('span');
        dateSpan.textContent = p.date;
        var catSpan = document.createElement('span');
        catSpan.textContent = Array.isArray(p.categories) ? p.categories.join(', ') : '';

        meta.appendChild(authorSpan);
        meta.appendChild(dateSpan);
        meta.appendChild(catSpan);

        li.appendChild(titleLink);
        li.appendChild(excerpt);
        li.appendChild(meta);
        return li;
    }

    function renderPreviewList(posts, page) {
        var container = el('pm-bulk-preview-list');
        if (!container) { return; }
        container.textContent = '';

        if (posts.length === 0) {
            var emptyMsg = document.createElement('p');
            emptyMsg.textContent = '対象投稿が見つかりませんでした。';
            emptyMsg.className   = 'podcastmaker-bulk-note';
            container.appendChild(emptyMsg);
            return;
        }

        var totalPages = Math.ceil(posts.length / PAGE_SIZE);
        var start      = (page - 1) * PAGE_SIZE;
        var pageItems  = posts.slice(start, start + PAGE_SIZE);

        var ul = document.createElement('ul');
        ul.className = 'pm-preview-list';
        pageItems.forEach(function (p) { ul.appendChild(buildPreviewItem(p)); });
        container.appendChild(ul);

        if (totalPages > 1) {
            var pager = document.createElement('div');
            pager.className = 'pm-pagination';

            var prevBtn = document.createElement('button');
            prevBtn.className   = 'pm-page-btn';
            prevBtn.textContent = '← 前へ';
            prevBtn.disabled    = page <= 1;
            prevBtn.addEventListener('click', function () {
                currentPage--;
                renderPreviewList(searchResults, currentPage);
            });

            var info = document.createElement('span');
            info.className   = 'pm-page-info';
            info.textContent = page + ' / ' + totalPages + ' ページ（' + posts.length + ' 件）';

            var nextBtn = document.createElement('button');
            nextBtn.className   = 'pm-page-btn';
            nextBtn.textContent = '次へ →';
            nextBtn.disabled    = page >= totalPages;
            nextBtn.addEventListener('click', function () {
                currentPage++;
                renderPreviewList(searchResults, currentPage);
            });

            pager.appendChild(prevBtn);
            pager.appendChild(info);
            pager.appendChild(nextBtn);
            container.appendChild(pager);
        }
    }

    var scriptModeEl = el('pm-bulk-script-mode');
    if (scriptModeEl) {
        scriptModeEl.addEventListener('change', function () {
            var isMulti      = this.value === 'multi';
            var voiceBGroup  = el('pm-bulk-voice-b-group');
            var voiceALabel  = el('pm-bulk-voice-a-label');
            if (voiceBGroup) { voiceBGroup.style.display = isMulti ? '' : 'none'; }
            if (voiceALabel) { voiceALabel.textContent   = isMulti ? 'ボイスA（1人目）' : 'ボイス'; }
        });
    }

    var startBtn = el('pm-bulk-start-btn');
    if (startBtn) {
        startBtn.addEventListener('click', function () {
            startBtn.disabled = true;
            var voiceBId = el('pm-bulk-voice-b-id') ? el('pm-bulk-voice-b-id').value : '';
            var smartToneEl = el('pm-bulk-smart-tone-id');
            post('podcastmaker_bulk_start', {
                category_id:   el('pm-bulk-category')   ? el('pm-bulk-category').value   : '0',
                author_id:     el('pm-bulk-author')     ? el('pm-bulk-author').value     : '0',
                date_after:    el('pm-bulk-date-after') ? el('pm-bulk-date-after').value : '',
                date_before:   el('pm-bulk-date-before')? el('pm-bulk-date-before').value: '',
                no_audio_only: el('pm-bulk-no-audio') && el('pm-bulk-no-audio').checked ? '1' : '0',
                language:      el('pm-bulk-language')   ? el('pm-bulk-language').value   : 'ja',
                tts_model:     el('pm-bulk-tts-model')  ? el('pm-bulk-tts-model').value  : '',
                script_mode:   el('pm-bulk-script-mode')? el('pm-bulk-script-mode').value: 'single',
                voice_id:      el('pm-bulk-voice-id')   ? el('pm-bulk-voice-id').value   : '',
                voice_b_id:    voiceBId,
                prompt_id:     el('pm-bulk-prompt-id')  ? el('pm-bulk-prompt-id').value  : '',
                smart_tone_id: smartToneEl              ? smartToneEl.value              : '',
            }).then(function (res) {
                if (!res.success) {
                    alert(res.data.message);
                    startBtn.disabled = false;
                    return;
                }
                var progressCard = el('pm-bulk-progress-card');
                if (progressCard) { progressCard.style.display = ''; }
                startPolling();
            });
        });
    }

    function startPolling() {
        if (pollTimer) { clearInterval(pollTimer); }
        pollTimer = setInterval(fetchStatus, 3000);
        fetchStatus();
    }

    function fetchStatus() {
        if (statusInFlight) { return; }
        statusInFlight = true;
        post('podcastmaker_bulk_status', {}).then(function (res) {
            statusInFlight = false;
            if (!res.success) { return; }
            var data = res.data;
            if (data.status === 'idle') { return; }
            updateProgress(data);
            if (data.status === 'completed') {
                clearInterval(pollTimer);
                pollTimer = null;
                if (startBtn) { startBtn.disabled = false; }
            }
        }).catch(function () {
            statusInFlight = false;
        });
    }

    function updateProgress(data) {
        var done    = data.success + data.failed;
        var pct     = data.total > 0 ? Math.round((done / data.total) * 100) : 0;
        var barEl   = el('pm-bulk-bar');
        var textEl  = el('pm-bulk-progress-text');
        var startEl = el('pm-bulk-started-at');

        if (barEl)   { barEl.style.width = pct + '%'; }
        if (textEl)  {
            textEl.textContent = data.status === 'completed'
                ? '完了 ' + data.total + '/' + data.total + ' 件'
                : '処理中... ' + done + ' / ' + data.total + ' 件';
        }
        if (startEl) { startEl.textContent = '開始: ' + (data.started_at || ''); }

        var sucEl  = el('pm-bulk-stat-success');
        var failEl = el('pm-bulk-stat-failed');
        var pendEl = el('pm-bulk-stat-pending');
        if (sucEl)  { sucEl.textContent  = data.success; }
        if (failEl) { failEl.textContent = data.failed; }
        if (pendEl) { pendEl.textContent = data.pending; }

        var procItem = el('pm-bulk-processing-item');
        if (procItem) {
            if (data.processing_title) {
                procItem.style.display = '';
                procItem.textContent   = '処理中：' + data.processing_title;
            } else {
                procItem.style.display = 'none';
            }
        }

        renderTable(data.items);
    }

    function renderTable(items) {
        if (!items) { return; }
        var tbody = el('pm-bulk-results-tbody');
        if (!tbody) { return; }
        tbody.textContent = '';

        items.forEach(function (item, index) {
            var tr = document.createElement('tr');

            var tdNum = document.createElement('td');
            tdNum.textContent = index + 1;
            tr.appendChild(tdNum);

            var tdTitle = document.createElement('td');
            tdTitle.textContent = item.title;
            if (item.error) {
                var errSpan = document.createElement('small');
                errSpan.style.color   = '#d63638';
                errSpan.style.display = 'block';
                errSpan.textContent   = item.error;
                tdTitle.appendChild(errSpan);
            }
            tr.appendChild(tdTitle);

            var tdStatus = document.createElement('td');
            var badge    = document.createElement('span');
            badge.className = 'pm-badge';
            if (item.status === 'success') {
                badge.classList.add('pm-badge-success');
                badge.textContent = '✓ 成功';
            } else if (item.status === 'failed') {
                badge.classList.add('pm-badge-fail');
                badge.textContent = '✗ 失敗';
            } else if (item.status === 'processing') {
                badge.classList.add('pm-badge-processing');
                badge.textContent = '⟳ 処理中';
            } else {
                badge.classList.add('pm-badge-pending');
                badge.textContent = '待機中';
            }
            tdStatus.appendChild(badge);
            tr.appendChild(tdStatus);

            var tdDur = document.createElement('td');
            tdDur.textContent = item.duration > 0 ? item.duration + 's' : '—';
            tr.appendChild(tdDur);

            var tdAction = document.createElement('td');
            if (item.status === 'failed') {
                var retryBtn = document.createElement('button');
                retryBtn.className       = 'pm-retry-btn';
                retryBtn.textContent     = '再試行';
                retryBtn.dataset.postId  = item.post_id;
                retryBtn.addEventListener('click', function () {
                    this.disabled = true;
                    post('podcastmaker_bulk_retry', { post_id: this.dataset.postId })
                        .then(function (res) {
                            if (!res.success) { alert(res.data.message); return; }
                            startPolling();
                        });
                });
                tdAction.appendChild(retryBtn);
            } else {
                tdAction.textContent = '—';
            }
            tr.appendChild(tdAction);

            tbody.appendChild(tr);
        });
    }

    post('podcastmaker_bulk_status', {}).then(function (res) {
        if (res.success && res.data.status !== 'idle') {
            var progressCard = el('pm-bulk-progress-card');
            if (progressCard) { progressCard.style.display = ''; }
            updateProgress(res.data);
            if (res.data.status === 'processing') {
                startPolling();
                if (startBtn) { startBtn.disabled = true; }
            }
        }
    });

}());
