<div id="ai-generator-modal" class="fixed inset-0 z-[100] hidden items-center justify-center bg-slate-950/60 p-4">
    <div class="w-full max-w-2xl rounded-2xl bg-white shadow-2xl">
        <div class="flex items-center justify-between border-b border-slate-200 px-6 py-4">
            <div>
                <h2 class="text-lg font-semibold text-slate-900">AI diye content banan</h2>
                <p id="ai-generator-subtitle" class="text-sm text-slate-500">Prompt din, system apnar field-er jonno text toiri korbe.</p>
            </div>
            <button type="button" id="ai-generator-close" class="rounded-lg px-3 py-2 text-sm text-slate-500 hover:bg-slate-100 hover:text-slate-700">Close</button>
        </div>

        <div class="space-y-4 px-6 py-5">
            <div class="rounded-xl border border-blue-100 bg-blue-50 px-4 py-3 text-sm text-blue-700">
                Selected provider: <strong><?php echo e(strtoupper($generalSettings['ai']['provider'] ?? 'openai')); ?></strong>
            </div>

            <div>
                <label for="ai-generator-prompt" class="mb-1 block text-sm font-medium text-slate-700">What should AI write?</label>
                <textarea id="ai-generator-prompt" rows="5" class="w-full rounded-xl border-slate-300 text-sm focus:border-blue-500 focus:ring-blue-500" placeholder="Example: Write a compelling homepage hero title and short paragraph for Bangladeshi students who want to study in Canada."></textarea>
            </div>

            <div>
                <label for="ai-generator-extra-context" class="mb-1 block text-sm font-medium text-slate-700">Extra context (optional)</label>
                <textarea id="ai-generator-extra-context" rows="3" class="w-full rounded-xl border-slate-300 text-sm focus:border-blue-500 focus:ring-blue-500" placeholder="Tone, audience, word limit, language, CTA style, etc."></textarea>
            </div>

            <div id="ai-generator-error" class="hidden rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700"></div>
        </div>

        <div class="flex flex-wrap items-center justify-between gap-3 border-t border-slate-200 px-6 py-4">
            <p class="text-xs text-slate-500">Existing field content will be replaced with the generated result.</p>
            <div class="flex items-center gap-3">
                <button type="button" id="ai-generator-cancel" class="rounded-xl border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">Cancel</button>
                <button type="button" id="ai-generator-submit" class="rounded-xl bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700">Generate Content</button>
            </div>
        </div>
    </div>
</div>

<script>
(() => {
    const modal = document.getElementById('ai-generator-modal');
    const subtitle = document.getElementById('ai-generator-subtitle');
    const promptInput = document.getElementById('ai-generator-prompt');
    const extraContextInput = document.getElementById('ai-generator-extra-context');
    const errorBox = document.getElementById('ai-generator-error');
    const submitButton = document.getElementById('ai-generator-submit');
    const closeButton = document.getElementById('ai-generator-close');
    const cancelButton = document.getElementById('ai-generator-cancel');

    if (!modal || !promptInput || !extraContextInput || !submitButton) {
        return;
    }

    const skipPattern = /(slug|email|phone|password|api|model|host|port|username|encryption|sender|address|favicon|logo)/i;
    let activeField = null;
    let activeLabel = '';
    let activeFormContext = '';

    const getFieldLabel = (field) => {
        const container = field.closest('div');
        const label = container?.querySelector('label');
        return label?.textContent?.trim() || field.name || 'Content field';
    };

    const updateFieldValue = (field, value) => {
        const normalized = String(value || '').trim();
        field.value = normalized;
        field.dispatchEvent(new Event('input', { bubbles: true }));
        field.dispatchEvent(new Event('change', { bubbles: true }));

        if (window.tinymce && field.id) {
            const editor = window.tinymce.get(field.id);
            if (editor) {
                editor.setContent(normalized);
                editor.save();
            }
        }
    };

    const closeModal = () => {
        modal.classList.add('hidden');
        modal.classList.remove('flex');
        promptInput.value = '';
        extraContextInput.value = '';
        errorBox.classList.add('hidden');
        errorBox.textContent = '';
        activeField = null;
    };

    const openModal = (field, label, formContext) => {
        activeField = field;
        activeLabel = label;
        activeFormContext = formContext;
        subtitle.textContent = `${formContext ? formContext + ' - ' : ''}${label}`;
        promptInput.value = `Write content for "${label}".`;
        extraContextInput.value = '';
        errorBox.classList.add('hidden');
        errorBox.textContent = '';
        modal.classList.remove('hidden');
        modal.classList.add('flex');
        promptInput.focus();
        promptInput.select();
    };

    const injectAiButtons = () => {
        document.querySelectorAll('form[data-ai-form="true"]').forEach((form) => {
            const formContext = form.dataset.aiContext || 'Admin CMS';

            form.querySelectorAll('input:not([type]), input[type="text"], textarea').forEach((field) => {
                if (field.dataset.aiBound === 'true' || field.readOnly || field.disabled || skipPattern.test(field.name || '')) {
                    return;
                }

                field.dataset.aiBound = 'true';

                const wrapper = document.createElement('div');
                wrapper.className = 'mt-2 flex items-center gap-2';

                const button = document.createElement('button');
                button.type = 'button';
                button.className = 'inline-flex items-center rounded-lg border border-blue-200 bg-blue-50 px-3 py-1.5 text-xs font-semibold text-blue-700 transition hover:bg-blue-100';
                button.textContent = 'AI diye content banan';
                button.addEventListener('click', () => openModal(field, getFieldLabel(field), formContext));

                const badge = document.createElement('span');
                badge.className = 'text-[11px] text-slate-400';
                badge.textContent = 'AI helper';

                wrapper.appendChild(button);
                wrapper.appendChild(badge);
                field.insertAdjacentElement('afterend', wrapper);
            });
        });
    };

    submitButton.addEventListener('click', async () => {
        if (!activeField) {
            return;
        }

        const prompt = promptInput.value.trim();
        const extraContext = extraContextInput.value.trim();
        const currentValue = activeField.value.trim();

        if (prompt.length < 3) {
            errorBox.textContent = 'Please enter a prompt with at least 3 characters.';
            errorBox.classList.remove('hidden');
            return;
        }

        submitButton.disabled = true;
        submitButton.textContent = 'Generating...';
        errorBox.classList.add('hidden');
        errorBox.textContent = '';

        try {
            const response = await fetch(<?php echo json_encode(route('admin.settings.ai.generate'), 15, 512) ?>, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || '',
                },
                body: JSON.stringify({
                    prompt,
                    context: [
                        activeFormContext ? `Module: ${activeFormContext}` : '',
                        activeLabel ? `Field: ${activeLabel}` : '',
                        currentValue ? `Current content:\n${currentValue}` : '',
                        extraContext ? `Extra instructions:\n${extraContext}` : '',
                    ].filter(Boolean).join("\n\n"),
                }),
            });

            const payload = await response.json();

            if (!response.ok) {
                throw new Error(payload.message || 'AI generation failed.');
            }

            updateFieldValue(activeField, payload.text || '');
            closeModal();
        } catch (error) {
            errorBox.textContent = error.message || 'AI generation failed.';
            errorBox.classList.remove('hidden');
        } finally {
            submitButton.disabled = false;
            submitButton.textContent = 'Generate Content';
        }
    });

    closeButton.addEventListener('click', closeModal);
    cancelButton.addEventListener('click', closeModal);
    modal.addEventListener('click', (event) => {
        if (event.target === modal) {
            closeModal();
        }
    });
    document.addEventListener('keydown', (event) => {
        if (event.key === 'Escape' && !modal.classList.contains('hidden')) {
            closeModal();
        }
    });
    injectAiButtons();
    document.addEventListener('DOMContentLoaded', injectAiButtons);
})();
</script>
<?php /**PATH C:\xampp\htdocs\gps-migration\resources\views/admin/partials/ai-modal.blade.php ENDPATH**/ ?>