function generateShortcode() {
    const slugInput = document.getElementById('slug');
    const videoIdInput = document.getElementById('videoid');
    const playerSelect = document.getElementById('media_player');
    const output = document.getElementById('generated_shortcode');

    // Remove any previous errors
    clearError(slugInput);
    clearError(videoIdInput);
    clearError(playerSelect);

    let hasError = false;
    const slug = slugInput?.value.trim();
    let videoid = videoIdInput?.value.trim();
    const mediaPlayer = playerSelect?.value.trim();

    if (!slug) {
        showError(slugInput, 'Rental ID is required.');
        hasError = true;
    }

    if (!videoid) {
        showError(videoIdInput, 'Video ID or shortcode is required.');
        hasError = true;
    }

    if (!mediaPlayer) {
        showError(playerSelect, 'Media Player is required.');
        hasError = true;
    }

    if (hasError || !output) return;

    // Strip [videopress ...] for Jetpack
    if (mediaPlayer === 'jetpack') {
        const match = videoid.match(/^\[videopress\s+(.+?)\]$/i);
        if (match) {
            videoid = match[1].trim();
        }
    }

    // Extract mp4 from [aiovg_video mp4="..."]
    if (mediaPlayer === 'aiovg') {
        const match = videoid.match(/\[aiovg_video\s+mp4="([^"]+)"\]/i);
        if (match) {
            videoid = match[1];
        }
    }

    // Extract ID from [html5_video id="..."]
    if (mediaPlayer === 'html5') {
        const match = videoid.match(/\[html5_video\s+id="?(\d+)"?\]/i);
        if (match) {
            videoid = match[1];
        }
    }

    // Extract ID from [fvplayer id="..."]
    if (mediaPlayer === 'fv_player') {
        const match = videoid.match(/\[fvplayer\s+id="?(\d+)"?\]/i);
        if (match) {
            videoid = match[1];
        }
    }

    // Generate final shortcode
    output.value = `[paytoviewlite rentalid="${slug}" videoid="${videoid}" media_player="${mediaPlayer}"]`;
    return {
        slug,
        videoid,
        mediaPlayer,
        shortcode: output.value
    };
}

function updateGeneratedShortcodePreview() {
    const slugInput = document.getElementById('slug');
    const videoIdInput = document.getElementById('videoid');
    const playerSelect = document.getElementById('media_player');
    const output = document.getElementById('generated_shortcode');

    if (!slugInput || !videoIdInput || !playerSelect || !output) return;

    const slug = slugInput.value.trim();
    let videoid = videoIdInput.value.trim();
    const mediaPlayer = playerSelect.value.trim();

    if (!slug && !videoid && !mediaPlayer) {
        output.value = '';
        return;
    }

    if (mediaPlayer === 'jetpack') {
        const match = videoid.match(/^\[videopress\s+(.+?)\]$/i);
        if (match) videoid = match[1].trim();
    }

    if (mediaPlayer === 'aiovg') {
        const match = videoid.match(/\[aiovg_video\s+mp4="([^"]+)"\]/i);
        if (match) videoid = match[1];
    }

    if (mediaPlayer === 'html5') {
        const match = videoid.match(/\[html5_video\s+id="?(\d+)"?\]/i);
        if (match) videoid = match[1];
    }

    if (mediaPlayer === 'fv_player') {
        const match = videoid.match(/\[fvplayer\s+id="?(\d+)"?\]/i);
        if (match) videoid = match[1];
    }

    output.value = `[paytoviewlite rentalid="${slug}" videoid="${videoid}" media_player="${mediaPlayer}"]`;
}

function escapeHtml(value) {
    return String(value ?? '')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

function createShortcodeCopyButton(shortcode) {
    const button = document.createElement('button');
    button.type = 'button';
    button.className = 'button paytoview-icon-button copy-shortcode-button';
    button.dataset.shortcode = shortcode;
    button.setAttribute('aria-label', 'Copy shortcode');
    button.setAttribute('title', 'Copy shortcode');
    button.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="9" y="9" width="10" height="10" rx="2"></rect><path d="M5 15V7a2 2 0 0 1 2-2h8"></path></svg>';
    attachCopyShortcodeHandler(button);
    return button;
}

function createShortcodeDeleteButton(deleteKey) {
    const button = document.createElement('button');
    button.type = 'button';
    button.className = 'button paytoview-icon-button paytoview-trash-button delete-shortcode-button';
    button.dataset.deleteKey = deleteKey;
    button.setAttribute('aria-label', 'Delete shortcode');
    button.setAttribute('title', 'Delete shortcode');
    button.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M3 6h18"></path><path d="M8 6V4h8v2"></path><path d="M6 6l1 15h10l1-15"></path><path d="M10 11v6"></path><path d="M14 11v6"></path></svg>';
    attachDeleteShortcodeHandler(button);
    return button;
}

function attachCopyShortcodeHandler(button) {
    button.addEventListener('click', (event) => {
        event.preventDefault();
        const shortcode = button.dataset.shortcode;
        if (!shortcode) return;

        const markCopied = () => {
            button.classList.add('copied');
            setTimeout(() => button.classList.remove('copied'), 1600);
        };

        if (navigator.clipboard) {
            navigator.clipboard.writeText(shortcode).then(markCopied).catch(() => {});
            return;
        }

        const temp = document.createElement('textarea');
        temp.value = shortcode;
        temp.setAttribute('readonly', 'readonly');
        temp.style.position = 'absolute';
        temp.style.left = '-9999px';
        document.body.appendChild(temp);
        temp.select();
        document.execCommand('copy');
        document.body.removeChild(temp);
        markCopied();
    });
}

function appendSavedShortcodeRow(data) {
    const tbody = document.getElementById('paytoviewlite-shortcode-list-body');
    if (!tbody) return;

    const emptyRow = tbody.querySelector('td[colspan="7"]');
    if (emptyRow) emptyRow.closest('tr')?.remove();

    const row = document.createElement('tr');
    row.dataset.deleteKey = data.delete_key;
    row.innerHTML = `
        <td class="paytoview-shortcode-col-slug">${escapeHtml(data.slug)}</td>
        <td class="paytoview-shortcode-col-file">${escapeHtml(data.media_file)}</td>
        <td class="paytoview-shortcode-col-price">${escapeHtml(data.price)}</td>
        <td class="paytoview-shortcode-col-duration">${escapeHtml(data.duration)}</td>
        <td class="paytoview-shortcode-col-media">${escapeHtml(data.media_player)}</td>
        <td class="paytoview-shortcode-col-code"><code>${escapeHtml(data.shortcode)}</code></td>
        <td class="paytoview-shortcode-col-actions"><div class="paytoview-actions-cell"></div></td>
    `;
    const actionsCell = row.querySelector('.paytoview-actions-cell');
    actionsCell.appendChild(createShortcodeCopyButton(data.wrapped_shortcode));
    actionsCell.appendChild(createShortcodeDeleteButton(data.delete_key));
    tbody.prepend(row);
}

function attachDeleteShortcodeHandler(button) {
    button.addEventListener('click', (event) => {
        event.preventDefault();
        const deleteKey = button.dataset.deleteKey;
        if (!deleteKey || typeof PayToViewLiteAdmin === 'undefined') return;
        if (!window.confirm('Delete this shortcode?')) return;

        button.disabled = true;

        const formData = new FormData();
        formData.append('action', 'paytoviewlite_delete_shortcode');
        formData.append('nonce', PayToViewLiteAdmin.delete_shortcode_nonce);
        formData.append('delete_key', deleteKey);

        fetch(PayToViewLiteAdmin.ajax_url, {
            method: 'POST',
            body: formData
        })
            .then((response) => response.json())
            .then((response) => {
                if (!response.success) {
                    throw new Error(response.data?.message || 'Could not delete shortcode.');
                }
                button.closest('tr')?.remove();
            })
            .catch((error) => {
                window.alert(error.message);
                button.disabled = false;
            });
    });
}

function bindShortcodeListActions(scope = document) {
    scope.querySelectorAll('.copy-shortcode-button').forEach((button) => {
        if (button.dataset.paytoviewBound === '1') return;
        button.dataset.paytoviewBound = '1';
        attachCopyShortcodeHandler(button);
    });

    scope.querySelectorAll('.delete-shortcode-button').forEach((button) => {
        if (button.dataset.paytoviewBound === '1') return;
        button.dataset.paytoviewBound = '1';
        attachDeleteShortcodeHandler(button);
    });
}

function loadShortcodeListPage(page) {
    const tbody = document.getElementById('paytoviewlite-shortcode-list-body');
    const footer = document.querySelector('.paytoview-shortcode-table-footer');

    if (!tbody || !footer || typeof PayToViewLiteAdmin === 'undefined') return;

    const formData = new FormData();
    formData.append('action', 'paytoviewlite_load_shortcode_list');
    formData.append('nonce', PayToViewLiteAdmin.load_shortcode_list_nonce);
    formData.append('page', page);

    footer.classList.add('is-loading');

    fetch(PayToViewLiteAdmin.ajax_url, {
        method: 'POST',
        body: formData
    })
        .then((response) => response.json())
        .then((response) => {
            if (!response.success) {
                throw new Error(response.data?.message || 'Could not load shortcode list.');
            }

            tbody.innerHTML = response.data.rows;
            footer.innerHTML = response.data.pagination;
            bindShortcodeListActions(tbody);
        })
        .catch((error) => {
            window.alert(error.message);
        })
        .finally(() => {
            footer.classList.remove('is-loading');
        });
}

function attachShortcodeListPagination() {
    const footer = document.querySelector('.paytoview-shortcode-table-footer');
    if (!footer) return;

    footer.addEventListener('click', (event) => {
        const button = event.target.closest('.paytoview-page-button');
        if (!button || button.classList.contains('disabled') || button.classList.contains('current-page')) return;

        const page = parseInt(button.dataset.page || '', 10);
        if (!page) return;

        event.preventDefault();
        loadShortcodeListPage(page);
    });
}

function saveGeneratedShortcode() {
    const generated = generateShortcode();
    if (!generated || typeof PayToViewLiteAdmin === 'undefined') return;

    const button = document.getElementById('paytoviewlite_generate_shortcode');
    const status = document.getElementById('paytoviewlite_save_shortcode_status');
    if (button) button.disabled = true;
    if (status) {
        status.textContent = '';
        status.classList.remove('is-visible');
    }

    const formData = new FormData();
    formData.append('action', 'paytoviewlite_save_shortcode');
    formData.append('nonce', PayToViewLiteAdmin.save_shortcode_nonce);
    formData.append('slug', generated.slug);
    formData.append('videoid', generated.videoid);
    formData.append('media_player', generated.mediaPlayer);

    fetch(PayToViewLiteAdmin.ajax_url, {
        method: 'POST',
        body: formData
    })
        .then((response) => response.json())
        .then((response) => {
            if (!response.success) {
                throw new Error(response.data?.message || 'Could not save shortcode.');
            }
            appendSavedShortcodeRow(response.data);
            if (status) {
                status.textContent = 'Saved!';
                status.classList.add('is-visible');
            }
        })
        .catch((error) => {
            window.alert(error.message);
        })
        .finally(() => {
            if (button) button.disabled = false;
        });
}


function copyShortcode() {
    const output = document.getElementById('generated_shortcode');
    const status = document.getElementById('copy_status');
    const button = document.getElementById('copy_generated_shortcode');

    if (!output || !status) return;

    const markCopied = () => {
        if (button) {
            button.classList.add('copied');
            setTimeout(() => button.classList.remove('copied'), 1600);
        }
    };

    output.select();
    output.setSelectionRange(0, 99999); // For mobile

    try {
        const successful = document.execCommand('copy');
        status.textContent = successful ? '' : 'Copy failed.';
        status.style.color = successful ? 'green' : 'red';
        if (successful) markCopied();
    } catch {
        status.textContent = 'Copy not supported.';
        status.style.color = 'red';
    }

    setTimeout(() => {
        status.textContent = '';
    }, 2000);
}

function showError(inputElement, message) {
    if (!inputElement) return;

    clearError(inputElement);

    inputElement.style.border = '1px solid red';

    const error = document.createElement('div');
    error.className = 'paytoview-error';
    error.textContent = message;
    error.style.color = 'red';
    error.style.marginTop = '4px';

    inputElement.parentNode.appendChild(error);
    inputElement.addEventListener('input', () => clearError(inputElement), { once: true });
}

function clearError(inputElement) {
    if (!inputElement) return;

    inputElement.style.border = '';
    const error = inputElement.parentNode?.querySelector('.paytoview-error');
    if (error) error.remove();
}

// === Settings form validation on submit ===
document.addEventListener('DOMContentLoaded', () => {
    const generateButton = document.getElementById('paytoviewlite_generate_shortcode');
    if (generateButton) {
        generateButton.addEventListener('click', saveGeneratedShortcode);
    }

    ['slug', 'videoid', 'media_player'].forEach((id) => {
        const field = document.getElementById(id);
        if (!field) return;
        field.addEventListener('input', updateGeneratedShortcodePreview);
        field.addEventListener('change', updateGeneratedShortcodePreview);
        field.addEventListener('input', () => {
            const status = document.getElementById('paytoviewlite_save_shortcode_status');
            if (!status) return;
            status.textContent = '';
            status.classList.remove('is-visible');
        });
    });
    updateGeneratedShortcodePreview();

    bindShortcodeListActions();
    attachShortcodeListPagination();

    const resetEmailTemplateButton = document.getElementById('paytoview-reset-email-template');
    if (resetEmailTemplateButton) {
        resetEmailTemplateButton.addEventListener('click', () => {
            const subjectInput = document.getElementById('email_subject');
            const messageInput = document.getElementById('email_message');

            if (subjectInput) {
                subjectInput.value = resetEmailTemplateButton.dataset.defaultSubject || '';
                clearError(subjectInput);
            }

            if (messageInput) {
                messageInput.value = resetEmailTemplateButton.dataset.defaultMessage || '';
                clearError(messageInput);
            }
        });
    }

    const settingsForm = document.querySelector('form[action="options.php"]');
    if (!settingsForm) return;

    settingsForm.addEventListener('submit', function(e) {
        const requiredFields = [
            'paypal_client_id',
            'paypal_email',
            'fixed_price',
            'custom_currency',
            'fixed_duration'
        ];

        let hasError = false;

        requiredFields.forEach(id => {
            const input = document.getElementById(id);
            clearError(input);
            if (!input || !input.value.trim()) {
                let labelText = id;
                const label = document.querySelector(`label[for="${id}"]`);
                if (label) {
                    labelText = label.textContent.replace('*', '').trim();
                }
                showError(input, `${labelText} is required.`);
                hasError = true;
            }
        });

        if (hasError) {
            e.preventDefault();
            const firstError = document.querySelector('.paytoview-error');
            if (firstError) firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
    });
});
