{{!
    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 theme_boost_magnific/settings/colors

    Example context (json):
    {
        "background": "#f0ff0f",
        "startcolor": true,
        "brandcolor": false,
        "footercolor": false,
        "coursecolor": false
    }
}}

<div class="mb-3">
    <div id="{{{uniqid}}}" class="boost_magnific-theme-select-itens">
        {{#colors}}
            <div class="boost_magnific-theme-select-item">
                <div class="preview" style="background:{{{.}}}"
                     data-color="{{{.}}}">
                    <span>{{{.}}}</span>
                </div>
            </div>
        {{/colors}}
    </div>
</div>

<div class="boost_magnific-colors-preview colors-body" id="colors-body-{{{uniqid}}}">
    <section class="card">
        <header class="card__header {{#navbar_layout_is_institutional}} card__header__institutional {{/navbar_layout_is_institutional}}">
            {{#str}}pluginname, theme_boost_magnific{{/str}} Preview
            <div class="card__header-menu">
                <span>menu</span>
                <span class="menu-active" style="--secondary_color:{{{secondary_color}}}">menu</span>
                <span>menu</span>
            </div>
        </header>
        <div class="card__body">
            <!-- Left -->
            <div class="left">
                <!-- 3 selectable rows -->
                <div class="row">
                    <div class="dash"></div>
                    <span class="dot"></span>
                    <div class="pill" role="button" aria-pressed="false">
                        <span class="line"></span>
                    </div>
                    <div class="chev">▾</div>
                </div>
                <div class="row">
                    <div class="dash"></div>
                    <span class="dot"></span>
                    <div class="pill"><span class="line"></span></div>
                    <div class="chev">▾</div>
                </div>
                <!-- section -->
                <div class="line-lg"></div>
                <div class="line-lg"></div>
                <div class="line-sm"></div>
                <!-- CTA -->
                <button class="cta" type="button">
                    <span class="slot"></span>
                </button>
            </div>
            <!-- Right -->
            <aside class="panel">
                <div class="bar"></div>
                <div class="bar"></div>
                <div class="bar"></div>
            </aside>
        </div>
        {{#footercolor}}
            <footer class="card__footer">© 2025 {{#str}}
                pluginname, theme_boost_magnific{{/str}} Preview. All rights reserved.
            </footer>
        {{/footercolor}}
    </section>
</div>

{{#js}}
    /*<script>*/
    require(["jquery"], function ($) {
        $("#{{{uniqid}}} .preview").click(function () {
            let color = $(this).attr("data-color");
            {{#startcolor}}
                $(`input[id^="id_"][id$="_startcolor"]`)
                        .val(color)
                        .minicolors("settings", {value: color});
                updateMainColor(color);

                $(`input[id^="id_"][id$="_startcolor"]`).change(function () {
                    updateMainColor($(this).val());
                });
            {{/startcolor}}

            {{#brandcolor}}
                $(`input[id^="id_"][id$="_brandcolor"]`)
                        .val(color)
                        .minicolors("settings", {value: color});
                updateMainColor(color);

                $(`input[id^="id_"][id$="_brandcolor"]`).change(function () {
                    updateMainColor($(this).val());
                });
            {{/brandcolor}}

            {{#footercolor}}
                $(`input[id^="id_"][id$="_footer_background_color"]`)
                        .val(color)
                        .minicolors("settings", {value: color});
                updateMainColor(null, color);

                $(`input[id^="id_"][id$="footer_background_color"]`).change(function () {
                    updateMainColor(null, $(this).val());
                });
            {{/footercolor}}

            {{#coursecolor}}
                console.trace("course color 1");
                $(`input#override_course_primarycolor`)
                        .val(color)
                        .minicolors("settings", {value: color});
                updateMainColor(color);
            {{/coursecolor}}
        });

        {{#startcolor}}
            $(`input[id^="id_"][id$="_startcolor"]`).change(function () {
                updateMainColor($(this).val());
            });
        {{/startcolor}}
        {{#brandcolor}}
            $(`input[id^="id_"][id$="_brandcolor"]`).change(function () {
                updateMainColor($(this).val());
            });
        {{/brandcolor}}
        {{#footercolor}}
            $(`input[id^="id_"][id$="footer_background_color"]`).change(function () {
                updateMainColor(null, $(this).val());
            });
        {{/footercolor}}
        {{#coursecolor}}
            $(`input#override_course_primarycolor`).change(function () {
                updateMainColor($(this).val());
            });
        {{/coursecolor}}

        updateMainColor("{{{defaultcolor}}}", "{{{defaultcolorfooter}}}");

        $('input[id^="id_s_"][id$="brandcolor_background_menu"]').change(function () {
            updateMainColor();
        });

        $('select[id^="id_s_"][id$="navbarlayout"]').change(function () {
            let $navbarlayout = $(this);
            if ($navbarlayout.val() == "institutional") {
                $("#colors-body-{{{uniqid}}} .card__header").addClass("card__header__institutional");
            } else {
                $("#colors-body-{{{uniqid}}} .card__header").removeClass("card__header__institutional");
            }
        });

        $('input[id^="id_s_"][id$="secondary"],#override_course_secondarycolor').change(function () {
            const root = document.querySelector("#colors-body-{{{uniqid}}} .menu-active");
            root.style.setProperty("--secondary_color", $(this).val());
        });

        // Troca a cor principal e recalcula as demais
        function updateMainColor(newPrimaryColor, newFooterColor) {
            const root = document.querySelector("#colors-body-{{{uniqid}}}");
            if (!root) {
                return;
            }

            if ($('input[id^="id_s_"][id$="brandcolor_background_menu"]').is(':checked') || "{{{brandcolor_background_menu}}}") {
                $("#colors-body-{{{uniqid}}} .card__header").addClass("card__header-dark");
            } else {
                $("#colors-body-{{{uniqid}}} .card__header").removeClass("card__header-dark");
            }

            // Cores derivadas.
            if (newPrimaryColor && newPrimaryColor[3]) {
                root.style.setProperty("--preview-primary", newPrimaryColor);
                root.style.setProperty("--preview-bg", lighten(newPrimaryColor, 90));
                root.style.setProperty("--preview-app-bg", lighten(newPrimaryColor, 80));
                root.style.setProperty("--preview-primary-shadow", darken(newPrimaryColor, 25) + "3F");
                root.style.setProperty("--preview-text", darken(newPrimaryColor, 60));

                const textFooterColor = luminance(newPrimaryColor) > 0.6 ? "#333333" : "#FFFFFF";
                root.style.setProperty("--preview-footer-bg", newPrimaryColor);
                root.style.setProperty("--preview-footer-text", textFooterColor);
            }
            if (newFooterColor && newFooterColor[3]) {
                const textNewFooterColor = luminance(newFooterColor) > 0.6 ? "#333333" : "#fff";
                root.style.setProperty("--preview-footer-bg", newFooterColor);
                root.style.setProperty("--preview-footer-text", textNewFooterColor);
            }
        }

        // Funções auxiliares para manipulação de cores
        function hexToRgb(hex) {
            hex = hex.replace(/^#/, "");
            if (hex.length === 3) {
                hex = hex.split("").map(c => c + c).join("");
            }
            const num = parseInt(hex, 16);
            return [(num >> 16) & 255, (num >> 8) & 255, num & 255];
        }
        function rgbToHex(r, g, b) {
            return "#" + [r, g, b]
                    .map(x => x.toString(16).padStart(2, "0"))
                    .join("");
        }
        function darken(hex, percent) {
            const [r, g, b] = hexToRgb(hex);
            return rgbToHex(
                    Math.max(0, Math.floor(r * (1 - percent / 100))),
                    Math.max(0, Math.floor(g * (1 - percent / 100))),
                    Math.max(0, Math.floor(b * (1 - percent / 100)))
            );
        }
        function lighten(hex, percent) {
            const [r, g, b] = hexToRgb(hex);
            return rgbToHex(
                    Math.min(255, Math.floor(r + (255 - r) * percent / 100)),
                    Math.min(255, Math.floor(g + (255 - g) * percent / 100)),
                    Math.min(255, Math.floor(b + (255 - b) * percent / 100))
            );
        }
        function luminance(bgColor) {
            // Remove o # e converte para números
            const r = parseInt(bgColor.substr(1, 2), 16);
            const g = parseInt(bgColor.substr(3, 2), 16);
            const b = parseInt(bgColor.substr(5, 2), 16);

            // Calcula a luminância percebida (fórmula de acessibilidade W3C).
            return (0.299 * r + 0.587 * g + 0.114 * b) / 255;
        }
    });
{{/js}}
