jQuery(document).ready(function ($) {
    const schedulerGrid = $('.scheduler-grid');

    function showLoadingState() {
        schedulerGrid.css('opacity', '0.5');
    }

    function hideLoadingState() {
        schedulerGrid.css('opacity', '1');
    }

    function renderSchedule(prompts) {
        // Clear existing prompts
        $('.prompt-card-wrapper').each(function () {
            const wrapper = $(this);
            wrapper.html(`
                <div class="prompt-card empty">
                    <div class="prompt-content">
                        <p>${saiapAdmin.i18n.noPromptScheduled}</p>
                    </div>
                    <div class="prompt-actions">
                        <button class="button-secondary edit-prompt" data-date="${wrapper.data('date')}">${saiapAdmin.i18n.add}</button>
                    </div>
                </div>
            `);
        });

        // Populate with new prompts
		if (prompts && prompts.length > 0) {
			prompts.forEach(prompt => {
				const promptDate = (prompt && prompt.scheduled_at ? String(prompt.scheduled_at) : '').split('T')[0];
                const wrapper = $(`.prompt-card-wrapper[data-date="${promptDate}"]`);
                if (wrapper.length) {
                    wrapper.html(`
                        <div class="prompt-card" data-id="${prompt.id}">
                            <div class="prompt-content">
                                <p>${prompt.prompt}</p>
                            </div>
                            <div class="prompt-actions">
                                <button class="button-secondary edit-prompt">${saiapAdmin.i18n.edit}</button>
                            </div>
                        </div>
                    `);
                }
            });
        }
    }

    function fetchSchedule() {
        showLoadingState();
        $.ajax({
            url: saiapAdmin.ajaxurl,
            method: 'POST',
            data: {
                action: 'saiap_get_schedule',
                nonce: saiapAdmin.schedulerNonce
            },
            success: function (response) {
                if (response.success) {
                    renderSchedule(response.data);
                } else {
                    handleScheduleError(response.data);
                }
            },
            error: function () {
                alert(saiapAdmin.i18n.errorLoadingSchedule);
            },
            complete: function () {
                hideLoadingState();
            }
        });
    }

    function getErrorMessage(errorData) {
        // Handle both string error messages (from wp_send_json_error) and object errors
        if (typeof errorData === 'string') {
            return errorData;
        } else if (errorData && errorData.error) {
            return errorData.error;
        } else if (errorData && errorData.message) {
            return errorData.message;
        } else {
            return 'Unknown error';
        }
    }

    function handleScheduleError(errorData) {
        const errorMessage = getErrorMessage(errorData);

        // Check if this is a missing license key error for free users
        if (errorMessage.includes('Missing license key') || errorMessage.includes('license key')) {
            showFreeUserMessage();
        } else {
            alert(saiapAdmin.i18n.errorLoadingSchedule + ': ' + errorMessage);
        }
    }

    function showFreeUserMessage() {
        // Show an admin notice above the scheduler grid because this feature requires use of our cloud service
        const noticeHtml = `
            <div class="notice notice-info saiap-scheduler-premium-notice">
                <p><strong>Post Scheduler - Generate organic traffic on autopilot</strong></p>
                <p>Watch as ClearPost learns what your audience wants and schedules posts that get traffic while you sleep.</p>
                <p style="margin-top:8px;">Get found on Google. Get recommended by ChatGPT. On autopilot.</p>
                <p>
                    <a class="button-link" href="https://clearpostplugin.com/" target="_blank" style="margin-left: 10px;">Grow traffic automatically</a>
                    <button class="button-secondary notice-dismiss-btn" style="margin-left: 10px;">Dismiss</button>
                </p>
            </div>
        `;
        
        // Add notice before the scheduler grid if it doesn't already exist
        if (!$('.saiap-scheduler-premium-notice').length) {
            schedulerGrid.before(noticeHtml);
        }

        // Handle dismiss button
        $('.notice-dismiss-btn').on('click', function(e) {
            e.preventDefault();
            $(this).closest('.notice').fadeOut();
        });
    }

    // Initial load - only if scheduler tab is active scheduler-grid is visible
    if ($('.scheduler-grid').length && $('.scheduler-grid').is(':visible')) {
        fetchSchedule();
        checkPostTypesForCta();
    }

    // Check when tab changes
    $(document).on('click', 'a[href*="tab=scheduler"]', function() {
        // Small delay to allow tab content to load
        setTimeout(function() {
            if ($('.scheduler-grid').length && $('.scheduler-grid').is(':visible')) {
                fetchSchedule();
                checkPostTypesForCta();
            }
        }, 100);
    });

    /**
     * Check if user has post types and show/hide the post map CTA accordingly.
     */
    function checkPostTypesForCta() {
        const $cta = $('#saiap-post-map-cta');
        if (!$cta.length || !saiapAdmin.contextNonce) return;

        $.ajax({
            url: saiapAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'saiap_post_types_list',
                nonce: saiapAdmin.contextNonce
            }
        }).done(function(resp) {
            if (!resp || !resp.success || !resp.data) {
                $cta.show();
                return;
            }
            const items = resp.data.items || resp.data.types || [];
            if (!items || items.length === 0) {
                $cta.show();
            } else {
                $cta.hide();
            }
        }).fail(function() {
            // On failure, show the CTA as a fallback
            $cta.show();
        });
    }

    

    // Modal handling
    const modal = $('#saiap-scheduler-modal');
    const form = $('#saiap-scheduler-form');
    const promptIdField = $('#saiap-modal-prompt-id');
    const dateField = $('#saiap-modal-date');
    const promptTextField = $('#saiap-modal-prompt-text');
    const modalTitle = $('#saiap-modal-title');

    function openModalForEdit(promptId, promptText) {
        promptIdField.val(promptId);
        dateField.val('');
        promptTextField.val(promptText);
        modalTitle.text(saiapAdmin.i18n.editPrompt);
        modal.show();
    }

    function openModalForAdd(date) {
        promptIdField.val('');
        dateField.val(date);
        promptTextField.val('');
        modalTitle.text(saiapAdmin.i18n.addPrompt);
        modal.show();
    }

    function closeModal() {
        modal.hide();
        form[0].reset();
    }

    schedulerGrid.on('click', '.edit-prompt', function() {
        const button = $(this);
        const card = button.closest('.prompt-card');
        
        if (card.hasClass('empty')) {
            const date = button.data('date');
            openModalForAdd(date);
        } else {
            const promptId = card.data('id');
            const promptText = card.find('.prompt-content p').text();
            openModalForEdit(promptId, promptText);
        }
    });

    $('#saiap-modal-cancel').on('click', closeModal);

    form.on('submit', function(e) {
        e.preventDefault();
        const promptId = promptIdField.val();
        const promptText = promptTextField.val();
        const scheduledDate = dateField.val();
		const pendingResearchId = modal.data('research-id');

        if (!promptText) {
            alert('Prompt text cannot be empty.');
            return;
        }

        const isUpdate = !!promptId;
        const ajaxAction = isUpdate ? 'saiap_update_prompt' : 'saiap_create_prompt';
        
        const data = {
            action: ajaxAction,
            nonce: saiapAdmin.schedulerNonce,
            prompt_text: promptText,
        };

        if (isUpdate) {
            data.prompt_id = promptId;
        } else {
            data.scheduled_date = scheduledDate;
        }

        // Show loading state on save button
        const saveButton = $('#saiap-modal-save');
        saveButton.prop('disabled', true).text('Saving...');

        $.ajax({
            url: saiapAdmin.ajaxurl,
            method: 'POST',
            data: data,
            success: function (response) {
                if (response.success) {
                    closeModal();
                    fetchSchedule(); // Refresh the schedule
					// Only now remove the originating research result if any
					if (pendingResearchId) {
						removeStoredResearchById(pendingResearchId);
						researchResultsPanel.find(`.saiap-result-card[data-id="${pendingResearchId}"]`).remove();
						modal.removeData('research-id');
					}

                    if (window.saiapTriggerStepCompletion && typeof window.saiapTriggerStepCompletion === 'function' && saiapAdmin && saiapAdmin.licenseKey) {
                        window.saiapTriggerStepCompletion(4);
                    }
                } else {
                    const errorMessage = getErrorMessage(response.data);
                    alert('Error saving prompt: ' + errorMessage);
                }
            },
            error: function () {
                alert('Server error while saving prompt.');
            },
            complete: function () {
                saveButton.prop('disabled', false).text(saiapAdmin.i18n.savePrompt);
            }
        });
    });

    // Research Agent
    const fillCalendarBtn = $('#saiap-fill-calendar-btn');
    const researchPrompt = $('#saiap-research-prompt');
    const researchResultsPanel = $('#saiap-research-results');
    const recosContainer = $('#saiap-research-recos');
    let researchProgressTimer = null;

	// Research results persistence helpers
	const RESEARCH_STORAGE_KEY = 'saiap_research_results_v1';

	function buildResearchId(result) {
		const title = (result && result.title ? String(result.title) : '').trim();
		const summary = (result && result.summary ? String(result.summary) : '').trim();
		const url = (result && result.url ? String(result.url) : '').trim();
		return [title, summary, url].join('|');
	}

	function normalizeResearchResult(result) {
		return {
			title: result && result.title ? String(result.title) : '',
			summary: result && result.summary ? String(result.summary) : '',
			url: result && result.url ? String(result.url) : ''
		};
	}

	function getStoredResearchResults() {
		try {
			const raw = localStorage.getItem(RESEARCH_STORAGE_KEY);
			if (!raw) return [];
			const parsed = JSON.parse(raw);
			return Array.isArray(parsed) ? parsed : [];
		} catch (e) {
			return [];
		}
	}

	function saveStoredResearchResults(results) {
		try {
			localStorage.setItem(RESEARCH_STORAGE_KEY, JSON.stringify(results));
		} catch (e) {}
	}

	function persistLatestResearchBatch(results) {
		const normalized = (Array.isArray(results) ? results : []).map(normalizeResearchResult);
		const seen = new Set();
		const deduped = [];
		for (const r of normalized) {
			const id = buildResearchId(r);
			if (!seen.has(id)) {
				seen.add(id);
				deduped.push(r);
			}
		}
		const limited = deduped.slice(0, 10);
		saveStoredResearchResults(limited);
	}

	function removeStoredResearchById(id) {
		if (!id) return;
		const current = getStoredResearchResults();
		const next = current.filter(r => buildResearchId(r) !== id);
		saveStoredResearchResults(next);
	}

	function renderStoredResearchOnLoad() {
		const stored = getStoredResearchResults();
		if (stored && stored.length > 0) {
			renderResearchResults(stored);
		}
	}

    function showResearchLoading() {
        fillCalendarBtn.text('Researching...').prop('disabled', true);
        researchResultsPanel.html('<p class="saiap-research-status">Starting research…</p><div class="saiap-progress"><div class="saiap-progress-bar" style="width: 5%"></div></div>').show();
        if (recosContainer && recosContainer.length) {
            recosContainer.find('button').prop('disabled', true);
        }
    }

    function hideResearchLoading() {
        fillCalendarBtn.text('Fill Calendar').prop('disabled', false);
        if (recosContainer && recosContainer.length) {
            recosContainer.find('button').prop('disabled', false);
        }
    }

    function renderResearchResults(results) {
        researchResultsPanel.empty();
        if (results && results.length > 0) {
			results.forEach(result => {
				const sourceUrl = result.url || '';
				const id = buildResearchId({ title: result.title || '', summary: result.summary || '', url: sourceUrl });
                let sourceLabel = 'Source';
                try {
                    if (sourceUrl) {
                        sourceLabel = new URL(sourceUrl).hostname || 'Source';
                    }
                } catch (e) {}

                const sourceMarkup = sourceUrl ? `<p class="saiap-result-source"><a href="${sourceUrl}" target="_blank" rel="noopener">${sourceLabel}</a></p>` : '';

				const resultCard = `
					<div class="saiap-result-card" data-id="${id}">
                        <button class="saiap-result-close discard-result" aria-label="Dismiss">×</button>
                        <h4>${result.title}</h4>
                        <p>${result.summary}</p>
                        ${sourceMarkup}
                        <div class="saiap-result-actions">
                            <button class="button-primary add-to-calendar" data-title="${encodeURIComponent(result.title)}" data-summary="${encodeURIComponent(result.summary || '')}" data-url="${encodeURIComponent(sourceUrl)}">Add to Calendar</button>
                        </div>
                    </div>
                `;
                researchResultsPanel.append(resultCard);
            });
        } else {
            researchResultsPanel.html('<p>No results found. Try a different prompt.</p>');
        }
    }

    function updateResearchStatus(message) {
        const existing = researchResultsPanel.find('.saiap-research-status');
        if (existing.length) {
            existing.text(message);
        } else {
            researchResultsPanel.prepend(`<p class="saiap-research-status">${message}</p>`);
        }
        const bar = researchResultsPanel.find('.saiap-progress-bar');
        const map = {
            'Starting research…': 5,
            'Connecting…': 10,
            'Searching web…': 35,
            'Removing duplicates…': 65,
            'Summarizing ideas…': 70
        };
        const pct = map[message] || 15;
        if (bar.length) bar.css('width', pct + '%');

        // Manage slow progress animation during long LLM summarization
        if (message === 'Summarizing ideas…') {
            // Clear any existing timer
            if (researchProgressTimer) {
                clearInterval(researchProgressTimer);
                researchProgressTimer = null;
            }
            // Slowly move toward 98% until done event arrives
            researchProgressTimer = setInterval(() => {
                const current = parseFloat((bar.css('width') || '0').replace('%','')) || 0;
                const target = 98;
                const next = Math.min(target, current + 0.8); // ~0.8% per tick
                bar.css('width', next + '%');
                if (next >= target) {
                    clearInterval(researchProgressTimer);
                    researchProgressTimer = null;
                }
            }, 800);
        } else {
            // On other phases, stop slow animation
            if (researchProgressTimer) {
                clearInterval(researchProgressTimer);
                researchProgressTimer = null;
            }
        }
    }

    async function startResearchStream(opts) {
        const { baseUrl, token, domain, prompt, siteContext } = opts;
        updateResearchStatus('Connecting…');
        const url = baseUrl.replace(/\/$/, '') + '/api/research/stream';
        const resp = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + token
            },
            body: JSON.stringify({ domain, prompt, siteContext })
        });

        if (!resp.ok || !resp.body) {
            throw new Error('Streaming not available');
        }

        const reader = resp.body.getReader();
        const decoder = new TextDecoder('utf-8');
        let buffer = '';
        updateResearchStatus('Searching web…');

        while (true) {
            const { value, done } = await reader.read();
            if (done) break;
            buffer += decoder.decode(value, { stream: true });

            let idx;
            while ((idx = buffer.indexOf('\n\n')) !== -1) {
                const chunk = buffer.slice(0, idx).trim();
                buffer = buffer.slice(idx + 2);
                if (!chunk) continue;
                const lines = chunk.split('\n');
                let evt = 'message';
                let data = '';
                for (const line of lines) {
                    if (line.startsWith('event:')) evt = line.slice(6).trim();
                    if (line.startsWith('data:')) data += line.slice(5).trim();
                }
                try {
                    const parsed = data ? JSON.parse(data) : {};
                    if (evt === 'searching') updateResearchStatus('Searching web…');
                    else if (evt === 'clustering') updateResearchStatus('Removing duplicates…');
                    else if (evt === 'summarizing') updateResearchStatus('Summarizing ideas…');
					else if (evt === 'done' && parsed.ideas) {
						renderResearchResults(parsed.ideas);
						persistLatestResearchBatch(parsed.ideas);
                        if (window.saiapTriggerStepCompletion && typeof window.saiapTriggerStepCompletion === 'function' && saiapAdmin && saiapAdmin.licenseKey) {
                            window.saiapTriggerStepCompletion(3);
                        }
                        updateResearchStatus('');
                        const bar = researchResultsPanel.find('.saiap-progress-bar');
                        if (bar.length) bar.css('width', '100%');
                        if (researchProgressTimer) {
                            clearInterval(researchProgressTimer);
                            researchProgressTimer = null;
                        }
                    } else if (evt === 'error') {
                        researchResultsPanel.append(`<p>Error: ${parsed.message || 'Unknown error'}</p>`);
                        if (researchProgressTimer) {
                            clearInterval(researchProgressTimer);
                            researchProgressTimer = null;
                        }
                    }
                } catch (e) {
                    // ignore JSON errors
                }
            }
        }
    }

    // Recommendation buttons
    const RECOS_CACHE_KEY = 'saiap_research_recos_v1';

    function renderRecos(topics) {
        if (!recosContainer || !recosContainer.length) return;
        recosContainer.empty();
        (topics || []).slice(0, 3).forEach(function(topic) {
            const label = String(topic || '').trim();
            if (!label) return;
            const btn = $('<button class="button-secondary saiap-reco-btn"></button>')
                .text(label)
                .attr('data-topic', label);
            recosContainer.append(btn);
        });
    }

    function cacheRecos(topics) {
        try { localStorage.setItem(RECOS_CACHE_KEY, JSON.stringify((topics || []).slice(0,3))); } catch (e) {}
    }

    function getCachedRecos() {
        try {
            const raw = localStorage.getItem(RECOS_CACHE_KEY);
            if (!raw) return null;
            const arr = JSON.parse(raw);
            return Array.isArray(arr) ? arr : null;
        } catch (e) { return null; }
    }

    function fetchRecos() {
        const cached = getCachedRecos();
        if (cached && cached.length) {
            renderRecos(cached);
        }
        $.ajax({
            url: saiapAdmin.ajaxurl,
            method: 'POST',
            data: { action: 'saiap_get_research_recommendations', nonce: saiapAdmin.schedulerNonce },
            success: function(resp) {
                if (resp && resp.success && resp.data && Array.isArray(resp.data.topics)) {
                    renderRecos(resp.data.topics);
                    cacheRecos(resp.data.topics);
                }
            }
        });
    }

    if (recosContainer && recosContainer.length) {
        fetchRecos();
        recosContainer.on('click', '.saiap-reco-btn', function() {
            const topic = $(this).attr('data-topic') || '';
            if (!topic) return;
            researchPrompt.val(topic);
            fillCalendarBtn.trigger('click');
        });
    }

    fillCalendarBtn.on('click', function() {
        const prompt = researchPrompt.val();
        if (!prompt) {
            alert('Please enter a research prompt.');
            return;
        }

        showResearchLoading();

        // Try streaming path first: get short-lived token
        (async () => {
            try {
                const tokenResp = await $.ajax({
                    url: saiapAdmin.ajaxurl,
                    method: 'POST',
                    data: {
                        action: 'saiap_get_stream_token',
                        nonce: saiapAdmin.schedulerNonce
                    }
                });

                if (tokenResp && tokenResp.success && tokenResp.data && tokenResp.data.token) {
                    const siteContext = ''; // optional: can include stored context
                    await startResearchStream({
                        baseUrl: tokenResp.data.base_url,
                        token: tokenResp.data.token,
                        domain: tokenResp.data.domain,
                        prompt,
                        siteContext
                    });
                    hideResearchLoading();
                    return;
                }
                throw new Error('Token not available');
            } catch (err) {
                // Fallback to non-streaming request
				$.ajax({
                    url: saiapAdmin.ajaxurl,
                    method: 'POST',
                    data: {
                        action: 'saiap_generate_research',
                        nonce: saiapAdmin.schedulerNonce,
                        prompt: prompt,
                    },
                    success: function (response) {
                        if (response.success) {
							renderResearchResults(response.data);
							persistLatestResearchBatch(response.data);
                            if (window.saiapTriggerStepCompletion && typeof window.saiapTriggerStepCompletion === 'function' && saiapAdmin && saiapAdmin.licenseKey) {
                                window.saiapTriggerStepCompletion(3);
                            }
                        } else {
                            const errorMessage = getErrorMessage(response.data);
                            if (errorMessage.includes('Missing required fields') || errorMessage.includes('Invalid or expired license key')) {
                                showFreeUserMessage();
                                researchResultsPanel.empty();
                            } else {
                                researchResultsPanel.html(`<p>Error: ${errorMessage}</p>`);
                            }
                        }
                    },
                    error: function () {
                        researchResultsPanel.html('<p>An unknown server error occurred.</p>');
                    },
                    complete: function () {
                        hideResearchLoading();
                    }
                });
            }
        })();
    });

    // Optional: future enhancement — native streaming client hitting premium directly after getting token via a separate AJAX.

	researchResultsPanel.on('click', '.add-to-calendar', function() {
        const title = decodeURIComponent($(this).data('title'));
        const summary = decodeURIComponent($(this).data('summary') || '');
        const url = decodeURIComponent($(this).data('url') || '');
		const card = $(this).closest('.saiap-result-card');
		const id = card.data('id');
        
        // Find the next empty slot
        const emptySlot = $('.prompt-card.empty').first();
        if (emptySlot.length) {
            const date = emptySlot.closest('.prompt-card-wrapper').data('date');
            openModalForAdd(date);
            // Pre-fill the prompt text with title, summary, and source link for downstream AI generation
            const parts = [title];
            if (summary) parts.push('', summary);
            if (url) parts.push(`Source: ${url}`);
            promptTextField.val(parts.join('\n'));

			// Defer removal until prompt is saved successfully
			if (id) {
				modal.data('research-id', id);
			}
        } else {
            alert('No empty slots available in the calendar.');
        }
    });

	researchResultsPanel.on('click', '.discard-result', function() {
		const card = $(this).closest('.saiap-result-card');
		const id = card.data('id');
		if (id) {
			removeStoredResearchById(id);
		}
		card.remove();
	});

	// Render any stored results on page load
	renderStoredResearchOnLoad();
}); 