<?php
// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

// Display typing text for this section
if (function_exists('aysa_display_typing_text_section')) {
    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
    $competition_text = "Add your initial target keywords and known competitors. You can edit these manually anytime and continue setup with your starting data.";
    echo wp_kses_post(aysa_display_typing_text_section($competition_text, 'competition'));
}

?>

<div class="aysa-wizard-section">
    <div class="aysa-wizard-header">
        <h2>Competitors & Keywords</h2>
        <p class="aysa-text-muted">Set your initial competitors and target keywords.</p>

        <div class="aysa-info-box">
            <span class="dashicons dashicons-info-outline"></span>
            <p>Complete only the initial data you already know. You can update these values later.</p>
        </div>
    </div>

    <form id="aysa-competition-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
        <input type="hidden" name="action" value="aysa_save_wizard_data">
        <input type="hidden" name="step" value="competition">
        <input type="hidden" name="nonce" value="<?php echo esc_attr(wp_create_nonce('aysa_nonce')); ?>">

        <div class="aysa-form-container">
        <!-- Keywords Section -->
            <div class="aysa-card">
                <div class="aysa-card-header">
                    <span class="dashicons dashicons-search"></span>
                    <h3>Seed Keywords</h3>
                </div>
                
                <p class="aysa-text-muted">Enter the seed keywords that best describe your business, products, or services.</p>
                
                <div id="keywords-container">
            <?php // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
             for($i = 1; $i <= 3; $i++) { ?>
                    <div class="aysa-form-group" data-keyword-index="<?php echo absint($i); ?>">
                        <label for="keyword<?php echo absint($i); ?>">Keyword <?php echo absint($i); ?><span class="aysa-required">*</span></label>
                        <div class="aysa-input-with-buttons">
                        <input type="text" 
                                   class="aysa-input" 
                               name="keyword<?php echo absint($i); ?>" 
                                   id="keyword<?php echo absint($i); ?>"
                                   placeholder="Ex: WordPress SEO Plugin"
                                   <?php echo $i === 1 ? 'required' : ''; ?>>
                            <div class="aysa-button-group">
                                <button type="button" class="aysa-button-secondary aysa-button-delete remove-keyword-btn" data-keyword-id="<?php echo absint($i); ?>" title="Remove this keyword">
                                    <span class="dashicons dashicons-no"></span>
                                </button>
                            </div>
                    </div>
                        <p class="aysa-form-hint">Enter a keyword or phrase your potential customers might search for</p>
            </div>
            <?php } ?>
                </div>
                
                <div class="aysa-button-container">
                    <button type="button" id="add-keyword-btn" class="aysa-button-secondary aysa-btn-green">
                        <span class="dashicons dashicons-plus"></span> Add Keyword
                    </button>
                </div>
        </div>

        <!-- Competitors Section -->
            <div class="aysa-card">
                <div class="aysa-card-header">
                    <span class="dashicons dashicons-groups"></span>
                    <h3>Competitors</h3>
        </div>

                <p class="aysa-text-muted">Add competitor websites you already know.</p>
                
                <div id="competitors-container">
            <?php // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
             for($i = 1; $i <= 3; $i++) { ?>
                    <div class="aysa-form-group">
                        <label for="competitor<?php echo absint($i); ?>">Competitor <?php echo absint($i); ?><span class="aysa-required">*</span></label>
                        <div class="aysa-input-with-buttons">
                            <input type="url" 
                                   class="aysa-input" 
                           name="competitor<?php echo absint($i); ?>" 
                                   id="competitor<?php echo absint($i); ?>"
                                   placeholder="https://competitor-website.com"
                                   <?php echo $i === 1 ? 'required' : ''; ?>>
                            <div class="aysa-button-group">
                                <button type="button" class="aysa-button-secondary aysa-button-delete remove-competitor-btn" data-competitor-id="<?php echo absint($i); ?>" title="Remove this competitor">
                                    <span class="dashicons dashicons-no"></span>
                                </button>
                            </div>
                    </div>
                        <p class="aysa-form-hint">Enter the full URL of your competitor's website</p>
            </div>
            <?php } ?>
                </div>
                
                <div class="aysa-button-container">
                    <button type="button" id="add-competitor-btn" class="aysa-button-secondary aysa-btn-green">
                        <span class="dashicons dashicons-plus"></span> Add Competitor
                    </button>
                </div>
            </div>
        </div>
    </form>
</div>

<style>
/* Enhanced styling with modern design */
.aysa-wizard-section {
    max-width: 100%;
    margin: 24px;
    padding: 0;
    font-family: 'Roboto', sans-serif;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.aysa-wizard-header {
    padding: 24px 32px;
    border-bottom: 1px solid #e0e0e0;
}

.aysa-wizard-header h2 {
    font-size: 24px;
    font-weight: 500;
    color: #1a1a1a;
    margin-bottom: 8px;
}

.aysa-text-muted {
    color: #666;
    font-size: 14px;
    line-height: 1.6;
    margin-bottom: 8px;
}

.aysa-info-box {
    background: #f8f9fa;
    border-left: 4px solid #0066ff;
    padding: 16px;
    border-radius: 4px;
    margin: 16px 0 0 0;
    display: flex;
    align-items: flex-start;
    gap: 16px;
}

.aysa-info-box .dashicons {
    font-size: 24px;
    color: #0066ff;
    width: 24px;
    height: 24px;
}

.aysa-info-box p {
    margin: 0;
    font-size: 14px;
    color: #1a1a1a;
    line-height: 1.6;
}

.aysa-form-container {
    padding: 32px;
}

.aysa-card {
    background: transparent;
    border-radius: 0;
    box-shadow: none;
    padding: 0;
    margin-bottom: 32px;
}

.aysa-card:hover {
    transform: none;
    box-shadow: none;
}

.aysa-card-header {
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e0e0e0;
    display: flex;
    align-items: center;
    gap: 16px;
}

.aysa-card-header .dashicons {
    font-size: 24px;
    width: 24px;
    height: 24px;
    color: #0066ff;
}

.aysa-card-header h3 {
    font-size: 20px;
    font-weight: 600;
    color: #1a1a1a;
    margin: 0;
}

.aysa-form-group {
    margin-bottom: 24px;
}

.aysa-form-group:last-child {
    margin-bottom: 0;
}

.aysa-form-group label {
    display: block;
    font-weight: 500;
    color: #1a1a1a;
    margin-bottom: 8px;
}

.aysa-required {
    color: #dc3545;
    margin-left: 4px;
}

.aysa-input {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    font-size: 14px;
    color: #1a1a1a;
    background-color: #fff;
}

.aysa-input-with-button {
    display: flex;
    gap: 8px;
}

.aysa-input-with-button .aysa-input {
    flex: 1;
}

.aysa-input-with-buttons {
    display: flex;
    gap: 8px;
    align-items: center;
}

.aysa-input-with-buttons .aysa-input {
    flex: 1;
}

.aysa-button-group {
    display: flex;
    gap: 4px;
    align-items: center;
}

.aysa-button-group .remove-keyword-btn {
    min-width: 32px;
    padding: 6px 8px;
    border-radius: 4px;
    transition: all 0.2s ease;
}

.aysa-button-group .remove-keyword-btn:hover {
    transform: scale(1.05);
    box-shadow: 0 2px 4px rgba(220, 53, 69, 0.3);
}

.aysa-form-hint {
    margin-top: 4px;
    font-size: 12px;
    color: #666;
}

.aysa-button-container {
    display: flex;
    gap: 8px;
    margin-top: 16px;
    margin-bottom: 24px;
}

.aysa-button-secondary {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    background: #f5f5f5;
    color: #333;
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 6px 12px;
    font-size: 13px;
    cursor: pointer;
    transition: all 0.2s;
}

.aysa-button-secondary:hover {
    background: #e9e9e9;
    color: #000;
}

.aysa-button-secondary .dashicons {
    font-size: 16px;
    width: 16px;
    height: 16px;
}

.aysa-spinning {
    animation: aysa-spin 2s linear infinite;
}

.aysa-loading-spinner {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #666;
    font-size: 14px;
    margin: 16px 0;
}

@keyframes aysa-spin {
    to { transform: rotate(360deg); }
}

.aysa-suggestions-container {
    margin-top: 24px;
    padding: 16px;
    background: #f9f9f9;
    border-radius: 4px;
    border: 1px solid #e0e0e0;
}

.aysa-suggestions-container h4 {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    margin: 0 0 16px 0;
}

.aysa-table-container {
    overflow-x: auto;
}

.aysa-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 14px;
}

.aysa-table th, 
.aysa-table td {
    padding: 10px;
    text-align: left;
    border-bottom: 1px solid #e0e0e0;
}

.aysa-table th {
    background: #f5f5f5;
    font-weight: 500;
    color: #333;
}

.aysa-table tr:hover {
    background: #f5f5f5;
}

.aysa-add-button {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    background: #0066ff;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 4px 8px;
    font-size: 12px;
    cursor: pointer;
}

.aysa-add-button:hover {
    background: #0052cc;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .aysa-wizard-section {
        margin: 16px;
    }
    
    .aysa-wizard-header,
    .aysa-form-container {
        padding: 20px;
    }
    
    .aysa-input-with-button {
        flex-direction: column;
    }
    
    .aysa-button-container {
        flex-direction: column;
    }
}

/* Delete variant for buttons */
.aysa-button-delete {
    background-color: #dc3545 !important;
    border-color: #dc3545 !important;
    color: #fff !important;
}

.aysa-button-delete:hover {
    background-color: #c82333 !important;
    border-color: #c82333 !important;
    color: #fff !important;
}

/* Verde pentru Add Keyword/Competitor */
.aysa-btn-green, .aysa-btn-green:visited {
    background: #2f7d32 !important;
    color: #fff !important;
    border: 1px solid #2f7d32 !important;
    font-weight: 500;
    transition: background 0.2s, box-shadow 0.2s;
}
.aysa-btn-green:hover, .aysa-btn-green:focus {
    background: #256427 !important;
    color: #fff !important;
}

/* Albastru pentru butoane secundare */
.aysa-btn-blue, .aysa-btn-blue:visited {
    background: #1a73e8 !important;
    color: #fff !important;
    border: 1px solid #1a73e8 !important;
    font-weight: 500;
    transition: background 0.2s, box-shadow 0.2s;
}
.aysa-btn-blue:hover, .aysa-btn-blue:focus {
    background: #1557b0 !important;
    color: #fff !important;
}

.aysa-input-duplicate {
    border-color: #dc3545 !important;
    box-shadow: 0 0 0 1px rgba(220, 53, 69, 0.25);
}

/* Pagination and Filtering Styles */
.aysa-keywords-controls {
    background: #f8f9fa;
    border: 1px solid #e0e0e0;
    border-radius: 6px;
    padding: 16px;
    margin-bottom: 16px;
}

.aysa-controls-row {
    display: flex;
    gap: 16px;
    align-items: center;
    flex-wrap: wrap;
    margin-bottom: 12px;
}

.aysa-search-box {
    position: relative;
    flex: 1;
    min-width: 200px;
}

.aysa-search-box input {
    padding-right: 32px;
}

.aysa-search-box .dashicons {
    position: absolute;
    right: 8px;
    top: 50%;
    transform: translateY(-50%);
    color: #666;
    pointer-events: none;
}

.aysa-filter-group {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
}

.aysa-select {
    padding: 6px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    background: white;
    font-size: 14px;
    min-width: 120px;
}

.aysa-results-info {
    color: #666;
    font-size: 14px;
    font-weight: 500;
}

.aysa-pagination {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 0;
    border-top: 1px solid #e0e0e0;
    margin-top: 16px;
}

.aysa-pagination-info {
    color: #666;
    font-size: 14px;
}

.aysa-pagination-controls {
    display: flex;
    align-items: center;
    gap: 8px;
}

.aysa-page-numbers {
    display: flex;
    gap: 4px;
    margin: 0 12px;
}

.aysa-page-btn {
    padding: 6px 12px;
    border: 1px solid #ddd;
    background: white;
    color: #333;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.2s;
}

.aysa-page-btn:hover {
    background: #f5f5f5;
    border-color: #999;
}

.aysa-page-btn.active {
    background: #0066ff;
    color: white;
    border-color: #0066ff;
}

.aysa-page-btn.active:hover {
    background: #0052cc;
    border-color: #0052cc;
}

/* Responsive adjustments for controls */
@media (max-width: 768px) {
    .aysa-controls-row {
        flex-direction: column;
        align-items: stretch;
    }
    
    .aysa-search-box {
        min-width: auto;
    }
    
    .aysa-filter-group {
        justify-content: space-between;
    }
    
    .aysa-select {
        flex: 1;
        min-width: auto;
    }
    
    .aysa-pagination {
        flex-direction: column;
        gap: 12px;
    }
    
    .aysa-pagination-controls {
        flex-wrap: wrap;
        justify-content: center;
    }
    
    .aysa-page-numbers {
        margin: 0 8px;
    }
}
</style>

<script>
jQuery(document).ready(function($) {
    let keywordCount = $('#keywords-container .aysa-form-group').length || 1;
    let competitorCount = $('#competitors-container .aysa-form-group').length || 1;

    function normalizeKeyword(value) {
        return String(value || '')
            .trim()
            .toLowerCase()
            .replace(/\s+/g, ' ');
    }

    function normalizeCompetitor(value) {
        const raw = String(value || '').trim().toLowerCase();
        if (!raw) {
            return '';
        }
        let candidate = raw;
        if (!/^https?:\/\//i.test(candidate)) {
            candidate = 'https://' + candidate;
        }
        try {
            const u = new URL(candidate);
            const host = (u.hostname || '').replace(/^www\./, '');
            const path = (u.pathname || '').replace(/\/+$/, '');
            return host + path;
        } catch (e) {
            return raw.replace(/^https?:\/\//, '').replace(/^www\./, '').replace(/\/+$/, '');
        }
    }

    function markDuplicateInputs($inputs, normalizer) {
        const seen = {};
        const duplicateIndexes = {};
        $inputs.removeClass('aysa-input-duplicate');
        $inputs.each(function(index) {
            const normalized = normalizer($(this).val());
            if (!normalized) {
                return;
            }
            if (!seen[normalized]) {
                seen[normalized] = [];
            }
            seen[normalized].push(index);
        });

        Object.keys(seen).forEach(function(key) {
            if (seen[key].length > 1) {
                seen[key].forEach(function(idx) {
                    duplicateIndexes[idx] = true;
                });
            }
        });

        $inputs.each(function(index) {
            if (duplicateIndexes[index]) {
                $(this).addClass('aysa-input-duplicate');
            }
        });

        return Object.keys(duplicateIndexes).length > 0;
    }

    function getProjectId() {
        let projectId = localStorage.getItem('aysa_project_id');
        if (projectId && Number(projectId) > 0) {
            return projectId;
        }
        const phpProjectId = '<?php echo intval(get_option('aysa_project_id', 0)); ?>';
        if (phpProjectId && Number(phpProjectId) > 0) {
            localStorage.setItem('aysa_project_id', phpProjectId);
            return phpProjectId;
        }
        return null;
    }

    function validateForm() {
        if (!$('#keyword1').val().trim()) {
            alert('Please enter at least one keyword.');
            $('#keyword1').focus();
            return false;
        }
        if (!$('#competitor1').val().trim()) {
            alert('Please enter at least one competitor.');
            $('#competitor1').focus();
            return false;
        }

        const hasDuplicateKeywords = markDuplicateInputs(
            $('#keywords-container input.aysa-input'),
            normalizeKeyword
        );
        if (hasDuplicateKeywords) {
            alert('Duplicate keywords are not allowed. Please keep each keyword unique.');
            $('#keywords-container input.aysa-input.aysa-input-duplicate').first().focus();
            return false;
        }

        const hasDuplicateCompetitors = markDuplicateInputs(
            $('#competitors-container input.aysa-input'),
            normalizeCompetitor
        );
        if (hasDuplicateCompetitors) {
            alert('Duplicate competitors are not allowed. Please keep each competitor unique.');
            $('#competitors-container input.aysa-input.aysa-input-duplicate').first().focus();
            return false;
        }

        return true;
    }

    function renumberKeywords() {
        $('#keywords-container .aysa-form-group').each(function(index) {
            const newIndex = index + 1;
            const $formGroup = $(this);
            const $label = $formGroup.find('label');
            const $input = $formGroup.find('input.aysa-input');
            const $removeBtn = $formGroup.find('.remove-keyword-btn');
            $formGroup.attr('data-keyword-index', newIndex);
            $label.attr('for', 'keyword' + newIndex).html('Keyword ' + newIndex + (newIndex === 1 ? '<span class="aysa-required">*</span>' : ''));
            $input.attr('name', 'keyword' + newIndex).attr('id', 'keyword' + newIndex).prop('required', newIndex === 1);
            $removeBtn.attr('data-keyword-id', newIndex);
        });
    }

    function renumberCompetitors() {
        $('#competitors-container .aysa-form-group').each(function(index) {
            const newIndex = index + 1;
            const $formGroup = $(this);
            const $label = $formGroup.find('label');
            const $input = $formGroup.find('input.aysa-input');
            const $removeBtn = $formGroup.find('.remove-competitor-btn');
            $label.attr('for', 'competitor' + newIndex).html('Competitor ' + newIndex + (newIndex === 1 ? '<span class="aysa-required">*</span>' : ''));
            $input.attr('name', 'competitor' + newIndex).attr('id', 'competitor' + newIndex).prop('required', newIndex === 1);
            $removeBtn.attr('data-competitor-id', newIndex);
        });
    }

    $('#add-keyword-btn').on('click', function() {
        keywordCount++;
        const $newField = $(`
            <div class="aysa-form-group" data-keyword-index="${keywordCount}">
                <label for="keyword${keywordCount}">Keyword ${keywordCount}</label>
                <div class="aysa-input-with-buttons">
                    <input type="text" class="aysa-input" name="keyword${keywordCount}" id="keyword${keywordCount}" placeholder="Ex: WordPress SEO Plugin">
                    <div class="aysa-button-group">
                        <button type="button" class="aysa-button-secondary aysa-button-delete remove-keyword-btn" data-keyword-id="${keywordCount}" title="Remove this keyword">
                            <span class="dashicons dashicons-no"></span>
                        </button>
                    </div>
                </div>
                <p class="aysa-form-hint">Enter a keyword or phrase your potential customers might search for</p>
            </div>
        `);
        $('#keywords-container').append($newField);
    });

    $(document).on('click', '.remove-keyword-btn', function() {
        if ($('#keywords-container .aysa-form-group').length <= 1) {
            return;
        }
        $(this).closest('.aysa-form-group').remove();
        keywordCount = $('#keywords-container .aysa-form-group').length;
        renumberKeywords();
        markDuplicateInputs($('#keywords-container input.aysa-input'), normalizeKeyword);
    });

    $('#add-competitor-btn').on('click', function() {
        competitorCount++;
        const $newCompetitorField = $(`
            <div class="aysa-form-group">
                <label for="competitor${competitorCount}">Competitor ${competitorCount}</label>
                <div class="aysa-input-with-buttons">
                    <input type="url" class="aysa-input" name="competitor${competitorCount}" id="competitor${competitorCount}" placeholder="https://competitor-website.com">
                    <div class="aysa-button-group">
                        <button type="button" class="aysa-button-secondary aysa-button-delete remove-competitor-btn" data-competitor-id="${competitorCount}" title="Remove this competitor">
                            <span class="dashicons dashicons-no"></span>
                        </button>
                    </div>
                </div>
                <p class="aysa-form-hint">Enter the full URL of your competitor's website</p>
            </div>
        `);
        $('#competitors-container').append($newCompetitorField);
    });

    $(document).on('click', '.remove-competitor-btn', function() {
        if ($('#competitors-container .aysa-form-group').length <= 1) {
            return;
        }
        $(this).closest('.aysa-form-group').remove();
        competitorCount = $('#competitors-container .aysa-form-group').length;
        renumberCompetitors();
        markDuplicateInputs($('#competitors-container input.aysa-input'), normalizeCompetitor);
    });

    $(document).on('input blur', '#keywords-container input.aysa-input', function() {
        markDuplicateInputs($('#keywords-container input.aysa-input'), normalizeKeyword);
    });

    $(document).on('input blur', '#competitors-container input.aysa-input', function() {
        markDuplicateInputs($('#competitors-container input.aysa-input'), normalizeCompetitor);
    });

    if (!window.aysaWizardUseGlobalNavigation) {
    $('#aysa-next-step').off('click.aysaCompetitionStep').on('click.aysaCompetitionStep', function(e) {
        e.preventDefault();
        const $button = $(this);
        const originalText = $button.html();
        $button.prop('disabled', true).html('<span class="dashicons dashicons-update aysa-spinning"></span> Saving...');

        if (!validateForm()) {
            $button.prop('disabled', false).html(originalText);
            return;
        }

        const projectId = getProjectId();
        if (projectId) {
            $('input[name="project_id"]').remove();
            $('#aysa-competition-form').append('<input type="hidden" name="project_id" value="' + String(projectId) + '">');
        }

        const setupNonce = '<?php echo esc_attr(wp_create_nonce('aysa_nonce')); ?>';
        const formData = $('#aysa-competition-form').serialize();

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: formData + '&action=aysa_save_wizard_data&step=competition&nonce=' + encodeURIComponent(setupNonce),
            success: function(resp) {
                if (!resp || !resp.success) {
                    alert('Failed to save data. Please try again.');
                    $button.prop('disabled', false).html(originalText);
                    return;
                }
                $button.html('<span class="dashicons dashicons-yes"></span> Saved!');
                setTimeout(function() {
                    window.location.href = '?page=aysa-setup-seo-profile&step=tone-of-voice';
                }, 500);
            },
            error: function() {
                alert('Failed to save data. Please try again.');
                $button.prop('disabled', false).html(originalText);
            }
        });
    });

    $('#aysa-prev-step').off('click.aysaCompetitionStep').on('click.aysaCompetitionStep', function(e) {
        e.preventDefault();
        window.location.href = '?page=aysa-setup-seo-profile&step=seo-settings';
    });
    }
});
</script>
