{{!
    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/>.
}}
{{!
    @template local_unifiedgrader/feedback_view

    Student read-only feedback view with annotated PDF and grade/feedback display.

    Context variables required:
    - cmid: Course module ID
    - activityname: Activity name
    - activityurl: URL to the activity
    - gradedisplay: Formatted grade string (e.g. "85 / 100")
    - feedback: HTML feedback text
    - hasfeedback: Whether feedback text exists
    - selectedfileid: Currently selected file ID
    - selectedfileurl: Preview URL of the selected PDF (annotated if available)
    - selectedfilename: Filename of the selected PDF
    - pdffiles: Array of PDF files
    - hasmultiplefiles: Whether there are multiple PDF files
    - pdffilesjson: JSON-encoded array of PDF files
    - hasannotatedpdf: Whether an annotated PDF exists for the selected file
    - annotatedpdfurl: URL of the annotated PDF (for inline viewer)
    - downloadfilename: Suggested filename for the feedback PDF download
    - annotatedpdfmapjson: JSON map of fileid to annotated PDF URL
    - feedbackdownloadurl: URL to download the combined feedback summary + annotated PDF
    - userid: Current student user ID
    - hasfeedbackfiles: Whether there are feedback files to display
    - feedbackfiles: Array of feedback file objects (filename, filesize, url, iconurl)
    - feedbackfilecount: Number of feedback files
    - feedbackfilesjson: JSON-encoded array of feedback files (for JS popout)
    - hascommentsfeature: Whether submission comments plugin is enabled
    - commentcount: Number of existing submission comments
    - canpostcomments: Whether the student can post comments
    - showrightcolumn: Whether to show the right column (feedback or comments)
    - hasrubric: Whether rubric grading is used
    - rubriccriteria: Array of rubric criteria with levels
    - rubrictotal: Sum of selected rubric level scores
    - hasguide: Whether marking guide is used
    - guidecriteria: Array of guide criteria with scores and remarks
    - guidetotal: Sum of achieved guide scores
    - guidemaxtotal: Sum of max guide scores
    - hasadvancedgrading: Whether rubric or guide is active
    - gradingmethodname: Display name of the grading method
    - haspdffiles: Whether there are PDF files to display
    - submissionpreviewurl: URL for iframe-based submission preview (non-PDF)
    - hasmultipleattempts: Whether there are multiple submission attempts
    - attempts: Array of attempt objects with attemptnumber, label, date, selected, url

    Example context (json):
    {
        "cmid": 1,
        "activityname": "Assignment 1",
        "activityurl": "https://example.com",
        "gradedisplay": "85 / 100",
        "feedback": "<p>Good work.</p>",
        "hasfeedback": true,
        "selectedfileid": 1,
        "selectedfileurl": "https://example.com/file.pdf",
        "selectedfilename": "submission.pdf",
        "pdffiles": [
            {
                "fileid": 1,
                "previewurl": "https://example.com/file.pdf",
                "filename": "submission.pdf",
                "selected": true
            }
        ],
        "hasmultiplefiles": false,
        "pdffilesjson": "[]",
        "hasannotatedpdf": true,
        "annotatedpdfurl": "https://example.com/annotated.pdf",
        "downloadfilename": "feedback.pdf",
        "annotatedpdfmapjson": "{}",
        "feedbackdownloadurl": "https://example.com/download",
        "userid": 2,
        "hasfeedbackfiles": false,
        "feedbackfiles": [],
        "feedbackfilecount": 0,
        "feedbackfilesjson": "[]",
        "hascommentsfeature": true,
        "commentcount": 2,
        "canpostcomments": true,
        "showrightcolumn": true,
        "hasrubric": false,
        "rubriccriteria": [],
        "rubrictotal": 0,
        "hasguide": false,
        "guidecriteria": [],
        "guidetotal": 0,
        "guidemaxtotal": 0,
        "hasadvancedgrading": false,
        "gradingmethodname": "",
        "haspdffiles": true,
        "submissionpreviewurl": "https://example.com/preview",
        "hasmultipleattempts": false,
        "attempts": [],
        "haspenalties": false,
        "penalties": []
    }
}}
<div class="local-unifiedgrader-feedback" data-region="feedback-viewer"
     data-cmid="{{cmid}}" data-fileid="{{selectedfileid}}"
     data-pdfurl="{{selectedfileurl}}" data-pdffiles="{{pdffilesjson}}"
     data-annotatedpdfmap="{{annotatedpdfmapjson}}">

    {{! Header bar with back button, activity name, download, grade badge, comments icon }}
    <div class="d-flex align-items-center justify-content-between border-bottom py-2 px-3 mb-3">
        <div class="d-flex align-items-center gap-2">
            <a href="{{activityurl}}" class="btn btn-sm btn-outline-secondary"
               title="{{#str}} backtocourse, local_unifiedgrader {{/str}}">
                <i class="fa fa-arrow-left" aria-hidden="true"></i>
            </a>
            <h5 class="mb-0">{{activityname}}</h5>
            {{#hasmultipleattempts}}
                <div class="dropdown ms-2">
                    <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button"
                            data-bs-toggle="dropdown" aria-expanded="false"
                            title="{{#str}} select_attempt, local_unifiedgrader {{/str}}">
                        <i class="fa fa-list-ol me-1" aria-hidden="true"></i>
                        {{#attempts}}
                            {{#selected}}{{label}}{{/selected}}
                        {{/attempts}}
                    </button>
                    <ul class="dropdown-menu">
                        {{#attempts}}
                            <li>
                                <a class="dropdown-item {{#selected}}active{{/selected}}" href="{{url}}">
                                    {{label}} <span class="text-muted small ms-2">{{date}}</span>
                                </a>
                            </li>
                        {{/attempts}}
                    </ul>
                </div>
            {{/hasmultipleattempts}}
            {{#gradedisplay}}
                <a href="{{feedbackdownloadurl}}" class="btn btn-sm btn-outline-primary ms-2" download="{{downloadfilename}}">
                    <i class="fa fa-download me-1" aria-hidden="true"></i>
                    {{#str}} download_feedback_pdf, local_unifiedgrader {{/str}}
                </a>
            {{/gradedisplay}}
        </div>
        <div class="d-flex align-items-center gap-3">
            {{#hascommentsfeature}}
                <div data-region="feedback-comments" data-cmid="{{cmid}}" data-userid="{{userid}}"
                     class="position-relative d-inline-block">
                    <button type="button"
                            class="btn btn-link btn-sm p-0 text-muted"
                            data-action="toggle-comments"
                            title="{{#str}} submissioncomments, local_unifiedgrader {{/str}}">
                        <i class="fa fa-comments" style="font-size: 1.25rem;"></i>
                    </button>
                    <span data-region="comment-count-badge"
                          class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger {{^commentcount}}d-none{{/commentcount}}"
                          style="font-size: 0.6rem;">
                        {{commentcount}}
                    </span>
                    <div data-region="comments-popout"
                         class="d-none local-unifiedgrader-comments-popout">
                    </div>
                </div>
            {{/hascommentsfeature}}
            {{#hasfeedbackfiles}}
                <span data-region="feedback-files-icon" class="position-relative d-inline-block"
                      data-files="{{feedbackfilesjson}}">
                    <button type="button"
                            class="btn btn-link btn-sm p-0 text-muted"
                            data-action="toggle-feedback-files"
                            title="{{#str}} feedbackfiles, local_unifiedgrader {{/str}}">
                        <i class="fa fa-paperclip" style="font-size: 1.25rem;"></i>
                    </button>
                    <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-secondary"
                          style="font-size: 0.6rem;">
                        {{feedbackfilecount}}
                    </span>
                    <div data-region="feedback-files-popout"
                         class="d-none local-unifiedgrader-files-popout">
                    </div>
                </span>
            {{/hasfeedbackfiles}}
            {{#gradedisplay}}
                <span class="badge bg-primary fs-6">
                    {{#str}} grade, local_unifiedgrader {{/str}}: {{gradedisplay}}
                </span>
            {{/gradedisplay}}
            {{#haspenalties}}
                {{#penalties}}
                    <span class="badge bg-warning text-dark local-unifiedgrader-penalty-badge">
                        {{text}}
                    </span>
                {{/penalties}}
            {{/haspenalties}}
        </div>
    </div>

    <div class="row g-3 px-3">
        {{! Left: Submission viewer }}
        <div class="{{#showrightcolumn}}col-lg-9{{/showrightcolumn}}{{^showrightcolumn}}col-12{{/showrightcolumn}}">
            {{#haspdffiles}}
                {{! File selector for multiple PDFs }}
                {{#hasmultiplefiles}}
                    <div class="mb-2">
                        <select data-action="file-selector" class="form-select form-select-sm">
                            {{#pdffiles}}
                                <option value="{{fileid}}" data-url="{{previewurl}}"
                                        {{#selected}}selected{{/selected}}>
                                    {{filename}}
                                </option>
                            {{/pdffiles}}
                        </select>
                    </div>
                {{/hasmultiplefiles}}

                {{! PDF viewer with read-only annotation layer }}
                <div data-region="pdf-viewer-wrapper"
                     style="height: calc(100vh - 200px); border: 1px solid var(--bs-border-color, #dee2e6); border-radius: 0.375rem; overflow: hidden;">
                    <div data-region="pdf-viewer-component" class="h-100" data-readonly="1">
                        {{> local_unifiedgrader/pdf_viewer }}
                    </div>
                </div>
            {{/haspdffiles}}
            {{^haspdffiles}}
                {{! Non-PDF submission rendered via iframe (e.g. YouTube, online text) }}
                <div data-region="submission-preview-wrapper"
                     style="height: calc(100vh - 200px); border: 1px solid var(--bs-border-color, #dee2e6); border-radius: 0.375rem; overflow: hidden;">
                    <iframe src="{{submissionpreviewurl}}"
                            style="width: 100%; height: 100%; border: none;"
                            allowfullscreen></iframe>
                </div>
            {{/haspdffiles}}
        </div>

        {{! Right: Feedback + submission comments panel }}
        {{#showrightcolumn}}
            <div class="col-lg-3">
                {{#hasfeedback}}
                    <div class="card">
                        <div class="card-header py-2">
                            <h6 class="mb-0">
                                <i class="fa fa-comment-o me-1" aria-hidden="true"></i>
                                {{#str}} overall_feedback, local_unifiedgrader {{/str}}
                            </h6>
                        </div>
                        <div class="card-body">
                            {{{feedback}}}
                        </div>
                    </div>
                {{/hasfeedback}}

                {{! Rubric display (read-only) }}
                {{#hasrubric}}
                    <div class="card {{#hasfeedback}}mt-3{{/hasfeedback}}" data-region="grading-card">
                        <div class="card-header py-2 d-flex justify-content-between align-items-center">
                            <h6 class="mb-0">
                                <i class="fa fa-th me-1" aria-hidden="true"></i>
                                {{gradingmethodname}}
                            </h6>
                            <div class="d-flex align-items-center gap-2">
                                <span class="badge bg-primary">{{rubrictotal}} pts</span>
                                <button type="button" class="btn btn-link btn-sm p-0 text-muted"
                                        data-action="expand-grading"
                                        data-bs-toggle="modal"
                                        data-bs-target="#grading-expand-modal"
                                        title="{{#str}} expand, local_unifiedgrader {{/str}}">
                                    <i class="fa fa-expand"></i>
                                </button>
                            </div>
                        </div>
                        <div class="card-body p-0" data-region="grading-card-body"
                             style="max-height: calc(100vh - 300px); overflow-y: auto;">
                            {{#rubriccriteria}}
                                <div class="border-bottom p-3">
                                    <div class="fw-bold small mb-2">{{description}}</div>
                                    <div class="d-flex flex-wrap gap-1">
                                        {{#levels}}
                                            <div class="p-2 border rounded small flex-fill
                                                {{#selected}} bg-primary bg-opacity-10 border-primary {{/selected}}
                                                {{^selected}} bg-light text-muted {{/selected}}"
                                                 style="min-width: 80px;">
                                                <div class="fw-bold {{#selected}}text-primary{{/selected}}">
                                                    {{score}} pts
                                                </div>
                                                <div style="font-size: 0.75rem;">{{definition}}</div>
                                            </div>
                                        {{/levels}}
                                    </div>
                                    {{#hasselection}}
                                        <div class="small text-end mt-1 text-primary fw-bold">
                                            {{selectedscore}} pts
                                        </div>
                                    {{/hasselection}}
                                    {{#hasremark}}
                                        <div class="mt-2 p-2 rounded small"
                                             style="background-color: rgba(13, 202, 240, 0.1); border: 1px solid rgba(13, 202, 240, 0.3);">
                                            <div class="fw-semibold text-info mb-1" style="font-size: 0.7rem;">
                                                <i class="fa fa-comment me-1" aria-hidden="true"></i>
                                                {{#str}} teacher_remark, local_unifiedgrader {{/str}}
                                            </div>
                                            <div>{{{remark}}}</div>
                                        </div>
                                    {{/hasremark}}
                                </div>
                            {{/rubriccriteria}}
                        </div>
                    </div>
                {{/hasrubric}}

                {{! Marking guide display (read-only) }}
                {{#hasguide}}
                    <div class="card {{#hasfeedback}}mt-3{{/hasfeedback}}{{^hasfeedback}}{{#hasrubric}}mt-3{{/hasrubric}}{{/hasfeedback}}"
                         data-region="grading-card">
                        <div class="card-header py-2 d-flex justify-content-between align-items-center">
                            <h6 class="mb-0">
                                <i class="fa fa-list-ol me-1" aria-hidden="true"></i>
                                {{gradingmethodname}}
                            </h6>
                            <div class="d-flex align-items-center gap-2">
                                <span class="badge bg-primary">{{guidetotal}} / {{guidemaxtotal}}</span>
                                <button type="button" class="btn btn-link btn-sm p-0 text-muted"
                                        data-action="expand-grading"
                                        data-bs-toggle="modal"
                                        data-bs-target="#grading-expand-modal"
                                        title="{{#str}} expand, local_unifiedgrader {{/str}}">
                                    <i class="fa fa-expand"></i>
                                </button>
                            </div>
                        </div>
                        <div class="card-body p-0" data-region="grading-card-body"
                             style="max-height: calc(100vh - 300px); overflow-y: auto;">
                            {{#guidecriteria}}
                                <div class="border-bottom p-3">
                                    <div class="d-flex justify-content-between align-items-start mb-1">
                                        <div class="fw-bold small">{{shortname}}</div>
                                        <span class="badge {{#hasscore}}bg-primary{{/hasscore}}{{^hasscore}}bg-secondary{{/hasscore}}">
                                            {{#hasscore}}{{score}}{{/hasscore}}{{^hasscore}}&ndash;{{/hasscore}}
                                            / {{maxscore}}
                                        </span>
                                    </div>
                                    {{#description}}
                                        <div class="small text-muted mb-1">{{{description}}}</div>
                                    {{/description}}
                                    {{#hasremark}}
                                        <div class="mt-2 p-2 rounded small"
                                             style="background-color: rgba(13, 202, 240, 0.1); border: 1px solid rgba(13, 202, 240, 0.3);">
                                            <div class="fw-semibold text-info mb-1" style="font-size: 0.7rem;">
                                                <i class="fa fa-comment me-1" aria-hidden="true"></i>
                                                {{#str}} teacher_remark, local_unifiedgrader {{/str}}
                                            </div>
                                            <div>{{{remark}}}</div>
                                        </div>
                                    {{/hasremark}}
                                </div>
                            {{/guidecriteria}}
                        </div>
                    </div>
                {{/hasguide}}

            </div>
        {{/showrightcolumn}}
    </div>

    </div>

{{! Expand modal for rubric / marking guide — placed outside the main container
    to avoid stacking context / overflow issues with ancestor elements. }}
{{#hasadvancedgrading}}
    <div class="modal fade" id="grading-expand-modal" tabindex="-1"
         aria-labelledby="grading-expand-modal-label" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header py-2">
                    <h5 class="modal-title" id="grading-expand-modal-label">{{gradingmethodname}}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" data-region="grading-modal-body">
                </div>
            </div>
        </div>
    </div>
{{/hasadvancedgrading}}

{{#js}}
    {{#haspdffiles}}
    require(['local_unifiedgrader/feedback_viewer'], function(FeedbackViewer) {
        FeedbackViewer.init();
    });
    {{/haspdffiles}}
    {{#hascommentsfeature}}
    require(['local_unifiedgrader/feedback_comments'], function(FeedbackComments) {
        FeedbackComments.init({{cmid}}, {{userid}});
    });
    {{/hascommentsfeature}}
    {{#hasadvancedgrading}}
    (function() {
        var container = document.querySelector('[data-region="feedback-viewer"]');
        if (!container) return;
        container.querySelectorAll('[data-action="expand-grading"]').forEach(function(btn) {
            btn.addEventListener('click', function() {
                var card = btn.closest('[data-region="grading-card"]');
                if (!card) return;
                var cardBody = card.querySelector('[data-region="grading-card-body"]');
                var modalBody = document.querySelector('[data-region="grading-modal-body"]');
                if (cardBody && modalBody) {
                    modalBody.innerHTML = cardBody.innerHTML;
                }
            });
        });
    })();
    {{/hasadvancedgrading}}
    {{#hasfeedbackfiles}}
    (function() {
        var wrapper = document.querySelector('[data-region="feedback-files-icon"]');
        if (!wrapper) return;
        var toggleBtn = wrapper.querySelector('[data-action="toggle-feedback-files"]');
        var popout = wrapper.querySelector('[data-region="feedback-files-popout"]');
        if (!toggleBtn || !popout) return;

        var files = [];
        try { files = JSON.parse(wrapper.dataset.files || '[]'); } catch(e) { /* noop */ }

        // Build popout content.
        var header = document.createElement('div');
        header.className = 'p-2 border-bottom d-flex justify-content-between align-items-center';
        header.innerHTML = '<strong class="small">{{#str}} feedbackfiles, local_unifiedgrader {{/str}}</strong>'
            + '<button type="button" class="btn-close btn-close-sm" data-action="close-files"></button>';
        popout.appendChild(header);

        var list = document.createElement('div');
        list.className = 'p-2';
        files.forEach(function(f) {
            var row = document.createElement('div');
            row.className = 'd-flex align-items-center gap-2 py-1';
            row.innerHTML = '<i class="fa fa-file-o flex-shrink-0"></i>'
                + '<div class="flex-grow-1 text-truncate">'
                + '<a href="' + f.url + '" class="text-truncate d-block small">' + f.filename + '</a>'
                + '<small class="text-muted">' + f.filesize + '</small>'
                + '</div>'
                + '<a href="' + f.url + '" class="btn btn-sm btn-outline-secondary flex-shrink-0" download>'
                + '<i class="fa fa-download"></i></a>';
            list.appendChild(row);
        });
        popout.appendChild(list);

        var visible = false;
        function show() {
            popout.classList.remove('d-none');
            visible = true;
            setTimeout(function() { document.addEventListener('click', outsideClick); }, 0);
        }
        function hide() {
            popout.classList.add('d-none');
            visible = false;
            document.removeEventListener('click', outsideClick);
        }
        function outsideClick(e) {
            if (!wrapper.contains(e.target)) hide();
        }
        toggleBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            visible ? hide() : show();
        });
        popout.querySelector('[data-action="close-files"]').addEventListener('click', function() { hide(); });
    })();
    {{/hasfeedbackfiles}}
{{/js}}
