<div class="modal fade" id="aiModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title"><?= __('ai_content_creator'); ?></h4>
            </div>
            <div class="modal-body">
                <input type="hidden" id="hidden_target">
                <input type="hidden" id="hidden_label">
                <textarea id="ai_input_prompt" class="form-control" rows="3" placeholder="<?= __('describe_item'); ?>"></textarea>
                <?php $glang = glang(auth('id')); ?>

                <div class="form-group mt-10 <?= isset($glang['is_glang']) && $glang['is_glang'] == 1 ? '' : 'd-none' ?>">
                    <select id="ai_response_lang" class="form-control">
                        <?php foreach (shop_languages(auth('id')) as $key => $row) : ?>
                            <option value="<?= $row->lang_name; ?>" data-slug="<?= $row->slug; ?>" <?= site_lang() == $row->slug ? 'selected' : ''; ?>><?= $row->lang_name; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>


                <div id="ai_result_area" class="mt-10 p-10 border bg-light" style="display:none; white-space: pre-wrap; "></div>
                <div id="ai_image_preview" class="mt-10 text-center" style="display:none;">
                    <img id="generated_image" src="" style="max-width: 100%; border: 1px solid var(--border-color); border-radius: 8px;">
                    <p class="text-sm text-muted mt-5"><?= __('generated_image_preview'); ?></p>
                </div>
            </div>
            <div class="modal-footer">
                <?php if (is_demo() == 1) : ?>
                    <button class="btn btn-primary" onclick="alert('Demo mode is enabled. You cannot generate content in demo mode.')"><?= __('generate_regenerate'); ?></button>
                <?php else : ?>
                    <button id="btn_generate" class="btn btn-primary"><?= __('generate_regenerate'); ?></button>
                    <button id="btn_accept" class="btn btn-success" style="display:none;"><?= __('accept_apply'); ?></button>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
    const AIManager = {
        config: {
            processUrl: "<?= base_url('admin/aihandler/process') ?>",
            saveImageUrl: "<?= base_url('admin/aihandler/save_image') ?>",
            csrf: {
                name: "<?= $this->security->get_csrf_token_name(); ?>",
                hash: "<?= $this->security->get_csrf_hash(); ?>"
            }
        },

        // Context definitions with field-level relations
        contexts: {
            'items': {
                modalTitle: '<?= __('ai_item_generator'); ?>',
                placeholder: '<?= __('describe_item'); ?>',
                sources: {
                    title: '#item_title',
                    category: 'select[name="cat_id"]'
                },
                relations: {
                    'Title': 'category',
                    'Description': 'title',
                    'Details': 'title',
                    'Image': 'title'
                },
                imageInputs: {
                    img: '#ai_images',
                    thumb: '#ai_thumb'
                },
                imagePreviews: {
                    img: '.imgPreview',
                    div: '.imgPreviewDiv'
                },
                tabTarget: 'a[href="#image_tab"]'
            },
            'category': {
                modalTitle: '<?= __('ai_category_generator'); ?>',
                placeholder: '<?= __('describe_category'); ?>',
                sources: {
                    title: '#name'
                },
                relations: {
                    'Details': 'title',
                    'Image': 'title'
                },
                imageInputs: {
                    img: '#ai_images_cat',
                    thumb: '#ai_thumb_cat'
                },
                imagePreviews: {
                    img: '.imgPreview',
                    div: '.imgPreviewDiv'
                }
            }
        },

        init: function() {
            const self = this;

            $('#btn_generate').click(function() {
                const prompt = $('#ai_input_prompt').val();
                const fieldLabel = $('#hidden_label').val();

                if (!prompt) return alert("Please type something first!");

                let $this = $(this);
                $this.html('<i class="fa fa-spinner fa-spin"></i> Processing...').prop('disabled', true);

                const data = {
                    prompt: prompt,
                    field: fieldLabel,
                    lang: $('#ai_response_lang').val()
                };
                data[self.config.csrf.name] = self.config.csrf.hash;

                $.post(self.config.processUrl, data, function(res) {
                    $this.html('Regenerate').prop('disabled', false);
                    let obj;
                    try {
                        obj = typeof res === 'object' ? res : JSON.parse(res);
                    } catch (e) {
                        alert("<?= __('failed_to_parse_ai_response'); ?>");
                        return;
                    }

                    if (obj.status === 'success') {
                        if (obj.is_image) {
                            $('#generated_image').attr('src', obj.data).on('error', function() {
                                alert("The AI service is temporarily busy. Please click Regenerate to try again.");
                                $(this).hide();
                            }).show();

                            $('#ai_image_preview').show();
                            $('#ai_result_area').text(obj.data).hide();
                            $('#ai_input_prompt').val(obj.raw_prompt || prompt);
                        } else {
                            $('#ai_result_area').text(obj.data).show();
                        }
                        $('#btn_accept').show();
                    } else {
                        alert(obj.message || "Unknown error occurred.");
                    }
                });
            });

            $('#btn_accept').click(function() {
                const resultText = $('#ai_result_area').text();
                const targetInput = $('#hidden_target').val();
                const fieldLabel = $('#hidden_label').val();
                const currentConfig = $(this).data('config') || {};

                if (fieldLabel === "Image") {
                    let $this = $(this);
                    $this.html('<i class="fa fa-spinner fa-spin"></i> Saving...').prop('disabled', true);

                    const data = {
                        url: resultText
                    };
                    data[self.config.csrf.name] = self.config.csrf.hash;

                    $.post(self.config.saveImageUrl, data, function(res) {
                        $this.html('Accept & Apply').prop('disabled', false);
                        let obj = typeof res === 'object' ? res : JSON.parse(res);
                        if (obj.status === 'success') {

                            $(currentConfig.imgInput).val(obj.image);
                            $(currentConfig.thumbInput).val(obj.thumb);

                            // Update Preview
                            $(currentConfig.previewClass).attr('src', "<?= asset_url() ?>" + obj.thumb).show();
                            $(currentConfig.previewDiv).addClass('opacity_0');
                            $(currentConfig.previewClass).removeClass('opacity_0');

                            if (currentConfig.tabTarget && $(currentConfig.tabTarget).length) {
                                $(currentConfig.tabTarget).tab('show');
                                $('.img_type').val(1);
                            }

                            $('#aiModal').modal('hide');
                        } else {
                            alert(obj.message);
                        }
                    });
                } else {
                    const $target = $(targetInput);
                    if ($target.hasClass('data_textarea') || $target.hasClass('textarea')) {
                        $target.summernote('code', resultText);
                    } else {
                        $target.val(resultText).trigger('change').trigger('keyup');
                    }
                    $('#aiModal').modal('hide');
                }
            });
        }
    };

    /**
     * GLOBAL AI CALL FUNCTION
     * @param {string} context - 'items', 'category', etc.
     * @param {string} field - 'Title', 'Description', 'Details', 'Image'
     * @param {string} target - The CSS selector for the input field to populate
     * @param {object} options - Custom overrides for inputs/previews
     */
    window.openAi = function(context, field, target, options = {}) {
        const ctx = AIManager.contexts[context] || {};

        const config = {
            imgInput: options.imgInput || (ctx.imageInputs ? ctx.imageInputs.img : '#ai_images'),
            thumbInput: options.thumbInput || (ctx.imageInputs ? ctx.imageInputs.thumb : '#ai_thumb'),
            previewClass: options.previewClass || (ctx.imagePreviews ? ctx.imagePreviews.img : '.imgPreview'),
            previewDiv: options.previewDiv || (ctx.imagePreviews ? ctx.imagePreviews.div : '.imgPreviewDiv'),
            tabTarget: options.tabTarget || ctx.tabTarget
        };

        $('#hidden_target').val(target);
        $('#hidden_label').val(field);
        $('#btn_accept').data('config', config);

        if (options.lang) {
            $(`#ai_response_lang option[data-slug="${options.lang}"]`).prop('selected', true);
        }

        // Dynamic Header and Placeholder
        $('#aiModal .modal-title').text(ctx.modalTitle || 'AI Content Creator');
        $('#ai_input_prompt').attr('placeholder', ctx.placeholder || 'Describe your requirement...');

        $('#ai_result_area').hide();
        $('#ai_image_preview').hide();
        $('#btn_accept').hide();

        // ---------------------------------------------------------
        // RELATION-BASED AUTO-PROMPT LOGIC
        // ---------------------------------------------------------
        let autoPrompt = "";
        const mapping = ctx.relations || {};
        const sourceKey = mapping[field]; // e.g. 'category' or 'title'
        const sourceSelector = ctx.sources ? ctx.sources[sourceKey] : null;

        let sourceValue = "";
        if (sourceSelector) {
            const el = $(sourceSelector);
            if (el.is('select')) {
                sourceValue = el.find('option:selected').text().trim();
                if (["Select category", "Select"].includes(sourceValue)) sourceValue = "";
            } else {
                sourceValue = el.val() ? el.val().trim() : "";
            }
        }

        if (field === "Title") {
            if (sourceValue) {
                autoPrompt = "A delicious dish for the " + sourceValue + " category";
            }
        } else if (field === "Description" || field === "Details") {
            if (sourceValue) {
                autoPrompt = "Describe " + sourceValue + " including ingredients and taste profile";
            }
        } else if (field === "Image") {
            if (sourceValue) {
                autoPrompt = "Photorealistic high-quality image of " + sourceValue;
            }
        }

        $('#ai_input_prompt').val(autoPrompt);
        $('#aiModal').modal('show');
    };

    $(document).ready(function() {
        AIManager.init();
    });
</script>