// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * @module     block_mwa_dashboard/content
 * @copyright  2026 Bruno Porto
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
define(['block_mwa_dashboard/dashboardstore','core/ajax','core/log','core/templates'], function(Store, Ajax, Log, Templates) {
    'use strict';
    var w = Store.windowFacade();

    (function(){
    'use strict';

    function tr(k,fb){var S=Store.getStrings?Store.getStrings():{};var v=Object.prototype.hasOwnProperty.call(S,k)?S[k]:'';return(v&&!/^\[\[/.test(v))?v:(fb!==undefined?fb:k);}
    function esc(v){return String(v==null?'':v).replace(/[&<>"']/g,function(c){return{'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];});}
    function norm(v){return v==null?'':String(v).trim();}
    function $(id){return document.getElementById(id);}
    function mdToHtml(t){if(!t)return '';t=t.replace(/&/g,'&amp;');t=t.replace(/[*][*]([^*]+)[*][*]/g,'<strong>$1</strong>');t=t.replace(/[*]([^*]+)[*]/g,'<em>$1</em>');t=t.replace(/(\d+)[.]\s+/g,'<br><strong>$1.</strong> ');t=t.replace(/\n\n/g,'<br><br>');t=t.replace(/\n/g,'<br>');return t;}

    function renderTemplate(node, template, context){
        if(!node)return Promise.resolve(null);
        return Templates.render('block_mwa_dashboard/'+template, context||{}).then(function(html){
            Templates.replaceNodeContents(node, html, '');
            return node;
        }).catch(function(e){Log.error(e);return node;});
    }

    function parseDate(l){
        if(l._ts){return new Date(Number(l._ts)*1000);}
        var s=norm(l.hora);var m=s.match(/(\d{2})\/(\d{2})\/(\d{2}),?\s*(\d{2}):(\d{2})/);
        if(m){return new Date(2000+Number(m[3]),Number(m[2])-1,Number(m[1]),Number(m[4]),Number(m[5]));}
        return null;
    }

    function getEventType(r){
        var ev=norm(r.nomedoevento).toLowerCase();
        var comp=norm(r.componente||r.component||'');
        var compL=comp.toLowerCase();
        var modtype=(r._modtype||'').toLowerCase();
        if(modtype==='assign'||modtype==='assignsubmission'||
           comp==='Tarefa'||comp==='Assignment'||compL==='tarefa'||
           comp==='Envio de arquivos'||compL==='envio de arquivos'||
           ev.indexOf('prorrogão')>=0||
           (ev.indexOf('avaliado')>=0&&(compL.indexOf('tarefa')>=0||modtype==='assign'))) return 'tarefa';
        if(ev.indexOf('envio')>=0||ev.indexOf('submiss')>=0||ev.indexOf('entrega')>=0||
           ev.indexOf('submitted')>=0||ev.indexOf('submission')>=0) return 'tarefa';
        if(modtype==='quiz'||modtype==='h5pactivity'||modtype==='scorm'||modtype==='lesson'||
           comp==='Questionário'||comp==='Quiz'||comp==='H5P'||comp==='Pacote H5P'||comp==='Pacote SCORM'||
           comp==='Jogo'||comp==='Ferramenta externa - LTI'||comp==='Ferramenta externa'||
           comp==='External tool'||
           compL.indexOf('questionário')>=0||compL.indexOf('h5p')>=0||compL.indexOf('scorm')>=0||
           compL.indexOf('jogo')>=0||ev.indexOf('tentativa')>=0||ev.indexOf('attempt')>=0||
           ev.indexOf('xapi')>=0) return 'quiz';
        if(modtype==='forum'||modtype==='glossary'||modtype==='wiki'||modtype==='workshop'||
           comp==='Forum'||comp==='Forum'||comp==='Glossário'||compL==='fórum'||compL==='forum'||
           comp==='Wiki'||comp==='Workshop'||
           ev.indexOf('discuss')>=0||ev.indexOf('glossári')>=0) return 'forum';
        if(modtype==='page'||modtype==='book'||modtype==='url'||modtype==='resource'||
           modtype==='folder'||modtype==='label'||modtype==='imscp'||
           comp==='Página'||comp==='Page'||comp==='Livro'||comp==='Book'||
           comp==='URL'||comp==='Arquivo'||comp==='File'||comp==='Pasta'||comp==='Folder'||
           compL==='página'||compL==='livro'||compL==='url'||compL==='arquivo'||compL==='pasta'||
           compL==='recurso'||ev.indexOf('capítulo')>=0||ev.indexOf('chapter')>=0) return 'video';
        if(ev.indexOf('módulo do curso visualizado')>=0||ev.indexOf('course module viewed')>=0) return 'video';
        if(modtype==='chat'||modtype==='bigbluebuttonbn'||
           comp==='Chat'||comp==='BigBlueButton'||compL.indexOf('videoconf')>=0||
           compL.indexOf('bbb')>=0||compL.indexOf('chat')>=0) return 'video';
        if(modtype==='data'||modtype==='choice'||modtype==='survey'||
           comp==='Base de dados'||comp==='Database'||comp==='Escolha'||comp==='Choice'||
           comp==='Pesquisa'||comp==='Survey'||
           compL.indexOf('base de dados')>=0||compL.indexOf('workshop')>=0||
           compL.indexOf('escolha')>=0) return 'forum';
        if(ev.indexOf('login')>=0||ev.indexOf('loggedin')>=0||ev.indexOf('loggedout')>=0||
           ev.indexOf('curso visto')>=0||ev.indexOf('course viewed')>=0||
           modtype==='system'||comp==='Sistema'||comp==='System') return 'login';

        return 'outro';
    }

    function isCourseGeneral(name){
        var n=norm(name);
        if(/^curso\s*:/i.test(n))return true;
        if(/^sistema$/i.test(n))return true;
        if(/exclu[íi]d[oa]/i.test(n))return true;
        if(/^área de texto/i.test(n))return true;
        if(/^mídia/i.test(n))return true;
        if(/^área de texto e mídia/i.test(n))return true;
        return false;
    }

    var _prompt = '';
    function whoNotDone(r) {
        var mwa = window.MWADashboard;
        var logs = (mwa && mwa.state && mwa.state.logs) || [];
        var accessed = {};
        logs.forEach(function(l) {
            if (String(l.contextinstanceid) === String(r.cmid) ||
                String(l.objectid) === String(r.cmid) ||
                String(l._cmid) === String(r.cmid)) {
                var n = norm(l.nomecompleto); if (n) accessed[n] = l.nomecompleto;
            }
        });
        return Object.values(accessed).slice(0, 8);
    }

    function render(){
        var el=$('prescriptiveContent');
        if(!el)return;
        var mwa=w.MWADashboard||{};
        var state=(mwa&&mwa.state)||{};
        var logs=state.logs||[];
        var grades=state.grades||[];
        if(!logs.length){
            var _db=Store.getModule?Store.getModule('MWADashboard'):null;
            if(_db&&_db.state){state=_db.state;logs=state.logs||[];grades=state.grades||[];}
        }

        if(!logs.length){
            renderTemplate(el, 'empty_state', {
                class: 'empty',
                icon: '📖',
                iconstyle: 'font-size:2rem;',
                message: tr('ct_no_data')
            });
            return;
        }
        var data=logs.map(function(r){
            var d=parseDate(r);
            return d?Object.assign({},r,{_date:d}):null;
        }).filter(Boolean);
        var allStu={};
        data.forEach(function(r){if(norm(r.nomecompleto))allStu[norm(r.nomecompleto)]=1;});
        var total=Math.max(1,Object.keys(allStu).length);
        var actMap={};
        data.forEach(function(r){
            var k=norm(r.contextodoevento||r.nomedoevento||'');
            if(!k||isCourseGeneral(k))return;
            var t=getEventType(r);
            if(t==='login')return;
            if(!actMap[k])actMap[k]={count:0,students:{},concluded:{},type:t};
            actMap[k].count++;
            actMap[k].students[norm(r.nomecompleto)]=1;
            var ev=norm(r.nomedoevento).toLowerCase();
            var isSubmit=ev.indexOf('um envio foi submetido')>=0||ev.indexOf('submissão criada')>=0||
                         ev.indexOf('usuário salvou um envio')>=0||ev.indexOf('submit')>=0;
            var isForumSubmit=ev.indexOf('post criado')>=0||ev.indexOf('resposta adicionada')>=0||
                              ev.indexOf('discussão adicionada')>=0||ev.indexOf('discussão criada')>=0||
                              ev.indexOf('discussion created')>=0||ev.indexOf('post created')>=0;
            // For content/resources: any access counts as completion
            var isVideoAccess=(t==='video');
            if(isSubmit||isForumSubmit||ev.indexOf('entregue')>=0||isVideoAccess){
                actMap[k].concluded[norm(r.nomecompleto)]=1;
            }
        });

        var res=Object.keys(actMap).map(function(name){
            var v=actMap[name];
            var stuCount=Object.keys(v.students).length;
            var concCount=Object.keys(v.concluded).length;
            return {
                name:name, type:v.type, count:v.count,
                uniqueStudents:stuCount, concluded:concCount,
                reachPct:Math.round((stuCount/total)*100),
                complPct:Math.round((concCount/Math.max(1,stuCount))*100)
            };
        }).sort(function(a,b){return a.reachPct-b.reachPct;});
        var gradeMap={};
        if(grades&&grades.length){
            grades.forEach(function(g){if(g.grade!=null)gradeMap[norm(g.student_name||g.name||'')]=Number(g.grade);});
        }
        var gVals=Object.values(gradeMap);
        var avgG=gVals.length?Math.round(gVals.reduce(function(s,v){return s+v;},0)/gVals.length):null;

        var low=res.filter(function(r){return r.reachPct<40;});
        var mid=res.filter(function(r){return r.reachPct>=40&&r.reachPct<70;});
        // Activities WITH a grade item -> stuck card
        // Activities WITHOUT a grade item -> low-access card
        // Build graded names from state.grades (first row has __mwa_type__=activity_names)
        var gradedNames={};
        var _gradesRaw=grades||[];
        var _actRow=_gradesRaw[0]&&_gradesRaw[0]['__mwa_type__']==='activity_names'?_gradesRaw[0]:null;
        if(_actRow){
            Object.keys(_actRow).forEach(function(k){
                if(k==='__mwa_type__'||k.indexOf('cmid')>=0||k.indexOf('module')>=0)return;
                var n=norm(_actRow[k]||'');
                if(n)gradedNames[n]=1;
            });
        }
        // Also use MWA_ACT_NAMES if grades tab was already opened
        var actNamesMap=window.MWA_ACT_NAMES||{};
        Object.keys(actNamesMap).forEach(function(k){
            var n=norm(actNamesMap[k]||'');
            if(n)gradedNames[n]=1;
        });
        function isGraded(name){
            var n=norm(name);
            if(!n||n.length<3)return false;
            if(gradedNames[n])return true;
            // partial match: activity name contained in grade item name or vice-versa
            return Object.keys(gradedNames).some(function(g){
                return g.length>4&&(g.indexOf(n)>=0||n.indexOf(g)>=0);
            });
        }

        var stuck=res.filter(function(r){
            // Only show in stuck if activity HAS a grade item
            return isGraded(r.name)&&r.uniqueStudents>=1;
        }).map(function(r){
            var notDelivered=total-r.concluded;
            var dp=Math.round((notDelivered/total)*100);
            return Object.assign({},r,{dropPct:dp,notDelivered:notDelivered});
        }).filter(function(r){return r.dropPct>0;})
          .sort(function(a,b){return b.dropPct-a.dropPct;}).slice(0,6);

        var stuckCount=stuck.filter(function(r){return r.dropPct>=50;}).length;
        var _lowThreshold = total < 10 ? 70 : total < 30 ? 50 : 35;
        var lowAccess=res.filter(function(r){
            // Low-access card: only materials WITHOUT a grade item
            return r.reachPct<_lowThreshold&&!isGraded(r.name);
        }).sort(function(a,b){return a.uniqueStudents-b.uniqueStudents;}).slice(0,6);

        var cfg=(mwa&&mwa.state&&mwa.config)||Store.getConfig()||{};
        var courseName=cfg.coursename||'';
        var kpiHtml=
            mkKpi('c-red',   '🔥 '+tr('ct_stuck_modules'),    stuckCount, tr('ct_of_eval')+res.filter(function(r){return r.type==='tarefa'||r.type==='quiz'||r.type==='forum'||r.type==='video';}).length+' '+tr('ct_eval_activities'))+
            mkKpi('c-amber', '📦 '+tr('ct_low_access'),   lowAccess.length, tr('ct_reach_below')+' < '+_lowThreshold+'%');
        window._ctStuck=stuck;
        window._ctLowAccess=lowAccess.map(function(r){return Object.assign({},r,{total:total});});

        var stuckHtml=stuck.length?stuck.map(function(r,si){
            var dropColor=r.dropPct>=70?'var(--red)':r.dropPct>=50?'var(--amber)':'var(--green)';
            var badge=r.dropPct>=70?{t:tr('ct_critical'),c:'var(--red)',bg:'var(--red-dim)'}:
                      r.dropPct>=50?{t:tr('ct_attention'),c:'var(--amber)',bg:'rgba(201,138,42,.13)'}:
                      {t:tr('ct_low_label'),c:'var(--green)',bg:'rgba(58,171,122,.12)'};
            var typeIcon={tarefa:'📝',quiz:'❓',forum:'💬',video:'📖',outro:'📌'}[r.type]||'📌';
            var label=r.name.length>55?r.name.slice(0,52)+'…':r.name;
            var notDoneNames=whoNotDone(r);
            var notDoneHtml=notDoneNames.length
                ?'<div style="font-size:.65rem;color:var(--muted);margin-top:2px;">'+tr('ct_who_stuck')+notDoneNames.map(function(n){return esc(n.split(' ')[0]);}).join(', ')+'</div>'
                :'';
            return '<div style="padding:.55rem 1rem;border-bottom:.5px solid var(--line);">'
                +'<div style="display:flex;align-items:center;gap:.5rem;">'
                +'<div style="flex:1;min-width:0;">'
                +'<div style="font-size:.8rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-weight:600;" title="'+esc(r.name)+'">'+typeIcon+' '+esc(label)+'</div>'
                +'<div style="font-size:.68rem;color:var(--muted);margin-top:1px;">'
                +'<span style="color:var(--green);">'+r.concluded+' '+tr('ct_delivered')+'</span>'
                +' · <span style="color:var(--red);">'+r.notDelivered+' '+tr('ct_not_delivered')+'</span>'
                +'</div>'
                +notDoneHtml
                +'</div>'
                +'<div style="display:flex;align-items:center;gap:.35rem;flex-shrink:0;">'
                +'<div style="width:60px;height:5px;background:var(--line);border-radius:3px;overflow:hidden;"><div style="width:'+r.dropPct+'%;height:100%;background:'+dropColor+';border-radius:3px;"></div></div>'
                +'<span style="font-size:.72rem;font-family:monospace;font-weight:700;color:'+dropColor+';">'+r.dropPct+'%</span>'
                +'<span style="font-size:.64rem;font-weight:700;color:'+badge.c+';background:'+badge.bg+';padding:1px 7px;border-radius:99px;">'+badge.t+'</span>'
                +'<button class="ct-stuck-ia-btn" data-stuck-idx="'+si+'" style="font-size:.65rem;padding:2px 8px;border-radius:8px;border:1px solid var(--line2);background:var(--panel2);cursor:pointer;color:var(--muted);">✨ IA</button>'
                +'</div></div>'
                +'<div class="ct-stuck-ia-result" id="ctStuckIA'+si+'" style="display:none;margin-top:.4rem;font-size:.78rem;line-height:1.55;color:var(--text);background:var(--blue-dim);border-radius:8px;padding:.5rem .7rem;"></div>'
                +'</div>';
        }).join(''):'<div style="padding:1rem;color:var(--muted);font-size:.82rem;text-align:center;">'+tr('ct_no_stuck')+'</div>';
        var lowHtml=lowAccess.length?lowAccess.map(function(r,li){
            var _typeLabels={forum:'💬 '+tr('ct_forum'),quiz:'❓ '+tr('ct_quiz_short'),tarefa:'📝 '+tr('ct_task'),video:'📖 '+tr('ct_material'),outro:'📌 '+tr('ct_resource')};
            var tl=_typeLabels[r.type]||'📌 '+tr('ct_resource');
            var pc=r.reachPct<20?'var(--red)':'var(--amber)';
            var label=r.name.length>70?r.name.slice(0,67)+'…':r.name;
            var reachSummary=tr('ct_reach_summary').replace('{type}',tl).replace('{unique}',r.uniqueStudents).replace('{total}',total);
            return '<div style="padding:.5rem 1rem;border-bottom:.5px solid var(--line);">'
                +'<div style="display:flex;align-items:center;gap:.6rem;">'
                +'<div style="flex:1;min-width:0;">'
                +'<div style="font-size:.8rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;" title="'+esc(r.name)+'">'+esc(label)+'</div>'
                +'<div style="font-size:.68rem;color:var(--muted);">'+reachSummary+'</div>'
                +'</div>'
                +'<div style="display:flex;align-items:center;gap:5px;flex-shrink:0;">'
                +'<div style="width:60px;height:5px;background:var(--line);border-radius:3px;overflow:hidden;">'
                +'<div style="width:'+r.reachPct+'%;height:100%;background:'+pc+';border-radius:3px;"></div></div>'
                +'<span style="font-size:.72rem;font-family:\'DM Mono\';font-weight:700;color:'+pc+';">'+r.reachPct+'%</span>'
                +'<button class="ct-low-ia-btn" data-low-idx="'+li+'" style="font-size:.65rem;padding:2px 8px;border-radius:8px;border:1px solid var(--line2);background:var(--panel2);cursor:pointer;color:var(--muted);">✨ IA</button>'
                +'</div>'
                +'</div>'
                +'<div class="ct-low-ia-result" id="ctLowIA'+li+'" style="display:none;margin-top:.4rem;font-size:.78rem;line-height:1.55;color:var(--text);background:var(--blue-dim);border-radius:8px;padding:.5rem .7rem;"></div>'
                +'</div>';
        }).join(''):'<div style="padding:1rem;color:var(--muted);font-size:.82rem;text-align:center;">'+tr('ct_all_good')+'</div>';
        var tableTypeLabels={
            forum:  '💬 '+tr('ct_forum'),
            quiz:   '❓ '+tr('ct_quiz_short'),
            tarefa: '📝 '+tr('ct_task'),
            video:  '📖 '+tr('ct_material'),
            outro:  '📌 '+tr('ct_other')
        };
        var tableRows=res.map(function(r){
            var bar=r.reachPct>=70?'var(--green)':r.reachPct>=40?'var(--amber)':'var(--red)';
            var sbg=r.reachPct>=70?'rgba(58,171,122,.13)':r.reachPct>=40?'rgba(201,138,42,.13)':'var(--red-dim)';
            var tl=tableTypeLabels[r.type]||'📌';
            var missing=total-r.uniqueStudents;
            var label=r.name.length>80?r.name.slice(0,77)+'…':r.name;
            return '<div style="display:flex;align-items:center;gap:.75rem;padding:.5rem 1rem;border-bottom:.5px solid var(--line);transition:background .12s;" onmouseenter="this.style.background=\'var(--panel2)\'" onmouseleave="this.style.background=\'\'">'
                +'<div style="width:110px;flex-shrink:0;font-size:.72rem;color:var(--muted);">'+tl+'</div>'
                +'<div style="flex:1;font-size:.78rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;" title="'+esc(r.name)+'">'+esc(label)+'</div>'
                +'<div style="width:170px;flex-shrink:0;display:flex;align-items:center;gap:6px;">'
                +'<div style="flex:1;height:6px;background:var(--line);border-radius:3px;overflow:hidden;">'
                +'<div style="width:'+r.reachPct+'%;height:100%;background:'+bar+';border-radius:3px;"></div></div>'
                +'<span style="font-size:.72rem;font-family:\'DM Mono\';font-weight:700;color:'+bar+';min-width:34px;text-align:right;">'+r.reachPct+'%</span>'
                +'<span style="font-size:.66rem;font-weight:700;color:'+bar+';background:'+sbg+';padding:1px 7px;border-radius:99px;flex-shrink:0;">'+r.uniqueStudents+' '+tr('ct_students_short')+'</span>'
                +'</div>'
                +'<div style="width:80px;flex-shrink:0;text-align:right;font-size:.72rem;font-family:\'DM Mono\';">'
                +(missing>0?'<span style="color:var(--red);font-weight:700;">'+missing+' ❌</span>':'<span style="color:var(--green);">✓ '+tr('ct_all_reached')+'</span>')
                +'</div></div>';
        }).join('');
        _prompt=tr('ct_prompt_intro')
            .replace('{course}', courseName||tr('ct_prompt_unknown'))+'\n'
            +tr('ct_prompt_data').replace('{n}',total)
            +(avgG!=null?tr('ct_prompt_avg').replace('{avg}',avgG):'')
            +'\n\n'+tr('ct_prompt_stuck_section')+'\n'
            +(stuck.length?stuck.map(function(r){
                var names=whoNotDone(r);
                var stuckNames=names.length?tr('ct_prompt_stuck_names').replace('{names}',names.map(function(n){return n.split(' ')[0];}).join(', ')):'';
                return tr('ct_prompt_stuck_item').replace('{name}',r.name).replace('{pct}',r.dropPct).replace('{names}',stuckNames);
            }).join('\n'):tr('ct_no_stuck_found'))
            +'\n\n'+tr('ct_prompt_low_access_section')+'\n'
            +(lowAccess.length?lowAccess.map(function(r){
                return tr('ct_low_access_prompt_item').replace('{name}',r.name).replace('{unique}',r.uniqueStudents).replace('{pct}',r.reachPct);
            }).join('\n'):tr('ct_prompt_none'))
            +'\n\n'+tr('ct_prompt_instruction')+'\n'
            +tr('ct_prompt_s1')+'\n\n'
            +tr('ct_prompt_s2')+'\n\n'
            +tr('ct_prompt_s3')+'\n\n'
            +tr('ct_prompt_footer');

        renderTemplate(el, 'content_analysis', {
            updated: tr('ct_updated'),
            kpishtml: kpiHtml,
            stucktitle: tr('ct_where_stuck'),
            stuckhtml: stuckHtml,
            stucknote: tr('ct_stuck_note'),
            lowtitle: tr('ct_low_access'),
            lowhtml: lowHtml,
            aititle: tr('ct_ai_suggestions'),
            refresh: tr('ct_refresh'),
            aidesc: tr('ct_ai_desc'),
            generate: tr('ct_generate_btn'),
            tabletitle: tr('ct_reach_table'),
            total: total,
            studentstotal: tr('ct_students_total'),
            typehead: tr('ct_th_type'),
            resourcehead: tr('ct_th_content'),
            coveragehead: tr('ct_th_coverage'),
            missinghead: tr('ct_missing'),
            tablerows: tableRows
        });
        bindContentEvents(el);

    }
    function bindContentEvents(el) {
        if (!el || el._ctBound) return;
        el._ctBound = true;
        el.addEventListener('click', function(e) {
            if (e.target.id === 'btnGenerateContent' || e.target.closest('#btnGenerateContent')) {
                generateIA(); return;
            }
            if (e.target.id === 'btnRefreshContent' || e.target.closest('#btnRefreshContent')) {
                refreshIA(); return;
            }
            // Per-item AI button - low-access materials
            var lowIaBtn = e.target.closest('.ct-low-ia-btn');
            if (lowIaBtn) {
                var li = parseInt(lowIaBtn.getAttribute('data-low-idx'), 10);
                var lr = (window._ctLowAccess || [])[li];
                if (!lr) return;
                var lowResultEl = document.getElementById('ctLowIA' + li);
                if (!lowResultEl) return;
                lowResultEl.style.display = 'block';
                renderTemplate(lowResultEl, 'content_ai_loading', {
                    message: tr('ct_ai_analyzing')
                });
                var cfg3 = Store.getConfig ? Store.getConfig() : {};
                var cid3 = parseInt(cfg3.courseid || 0, 10);
                var lowPrompt = 'You are an educational design expert.\n\n'
                    + 'LOW-ACCESS MATERIAL:\n'
                    + '- Name: ' + lr.name + '\n'
                    + '- Type: ' + lr.type + '\n'
                    + '- Reach: ' + lr.reachPct + '% (' + lr.uniqueStudents + ' of ' + lr.total + ' students accessed it)\n\n'
                    + 'Based on the name and type of this resource, provide:\n'
                    + '1. **Diagnosis** (1-2 sentences): why are students not accessing this material?\n'
                    + '2. **Content improvement** (2-3 sentences): how to make this material more engaging or visible?\n'
                    + '3. **Immediate action** (1 sentence): what to do now to increase access?\n\n'
                    + 'Use the real name of the material. Max 150 words. Be specific and practical.';
                Store.callAction('block_mwa_dashboard_get_ai_recommendation', {
                    courseid: cid3, student_name: lr.name, prompt: lowPrompt
                }).then(function(res) {
                    var text = (res && (res.recommendation || res.response || res.content)) || '';
                    if (!text) throw new Error(tr('err_ajax_bridge'));
                    renderTemplate(lowResultEl, 'content_ai_result', {
                        bodyhtml: mdToHtml(text)
                    });
                }).catch(function(e2) {
                    renderTemplate(lowResultEl, 'content_ai_error', {
                        message: String(e2.message || e2)
                    });
                });
                return;
            }
            var stuckBtn = e.target.closest('.ct-stuck-ia-btn');
            if (stuckBtn) {
                var idx = Number(stuckBtn.getAttribute('data-stuck-idx'));
                var r = (window._ctStuck || [])[idx];
                if (!r) return;
                var resultEl = document.getElementById('ctStuckIA' + idx);
                if (!resultEl) return;
                resultEl.style.display = 'block';
                renderTemplate(resultEl, 'content_ai_loading', {
                    message: tr('ct_ai_analyzing')
                });
                var cfg = Store.getConfig ? Store.getConfig() : {};
                var courseid = parseInt(cfg.courseid||0, 10);
                var names = whoNotDone(r);
                var typeLabel = {tarefa:tr('ct_task'), quiz:tr('ct_quiz_short'), forum:tr('ct_forum'), video:tr('ct_material'), outro:tr('ct_other')}[r.type] || r.type;
                var stuckLine = names.length ? tr('ct_item_prompt_stuck_line').replace('{names}', names.map(function(n){return n.split(' ')[0];}).join(', ')) : '';
                var itemPrompt = tr('ct_item_prompt')
                    .replace('{name}', r.name)
                    .replace('{type}', typeLabel)
                    .replace('{dropPct}', r.dropPct)
                    .replace('{notDelivered}', r.notDelivered)
                    .replace('{total}', r.concluded + r.notDelivered)
                    .replace('{concluded}', r.concluded)
                    .replace('{stuckLine}', stuckLine);
                Store.callAction('block_mwa_dashboard_get_ai_recommendation', {
                    courseid: courseid, student_name: '', prompt: itemPrompt
                }).then(function(res) {
                    var text = (res && (res.recommendation || res.response || res.content)) || '';
                    if (!text) throw new Error('vazio');
                    renderTemplate(resultEl, 'content_ai_result', {
                        bodyhtml: mdToHtml(text)
                    });
                }).catch(function(e) {
                    renderTemplate(resultEl, 'content_ai_error', {
                        message: String(e.message || e)
                    });
                });
            }
        });
    }

    function generateIA(){
        var iaEl=$('prescriptiveIA');
        var btn=$('btnGenerateContent');
        var refreshBtn=$('btnRefreshContent');
        if(iaEl){
            renderTemplate(iaEl, 'content_ai_loading', {
                message: tr('ct_ai_generating')
            });
        }
        if(btn)btn.style.display='none';
        if(refreshBtn)refreshBtn.style.display='';
        _callIA(_prompt);
    }

    function refreshIA(){
        var iaEl=$('prescriptiveIA');
        if(iaEl){
            renderTemplate(iaEl, 'content_ai_loading', {
                message: tr('ct_ai_generating')
            });
        }
        _callIA(_prompt);
    }

    function _callIA(prompt){
        var iaEl=$('prescriptiveIA');
        if(!iaEl)return;
        var cfg=Store.getConfig?Store.getConfig():{};
        var courseid=parseInt(cfg.courseid||0,10);
        Store.callAction('block_mwa_dashboard_get_ai_recommendation',{
            courseid:courseid, student_name:'', prompt:prompt
        }).then(function(res){
            var text=(res&&(res.recommendation||res.response||res.content))||'';
            if(!text){throw new Error('Resposta vazia');}
            text=text
                .replace(/^## (.+)$/gm,'<h3 style="font-size:.95rem;font-weight:700;margin:1rem 0 .4rem;color:var(--text);">$1</h3>')
                .replace(/\*\*(.+?)\*\*/g,'<strong>$1</strong>')
                .replace(/\n/g,'<br>');
            renderTemplate(iaEl, 'content_ai_result', {bodyhtml:text});
        }).catch(function(e){
            Log.error(e);
            renderTemplate(iaEl, 'content_ai_error', {
                message: tr('ct_ai_error')+': '+(e.message||'')
            });
        });
    }

    function mkKpi(cls, label, val, sub){
        return '<div class="kpi '+cls+'">'
            +'<div class="kpi-top"><span class="kpi-label">'+label+'</span></div>'
            +'<div class="kpi-val">'+val+'</div>'
            +'<div class="kpi-delta">'+esc(String(sub))+'</div>'
            +'</div>';
    }

    w.MWAContent={render:render, generateIA:generateIA, refreshIA:refreshIA};

    })();
    return w.MWAContent;
});
