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

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

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

<div class="degrade-colors-preview colors-body" id="colors-body-{{{uniqid}}}">
    <section class="card">
        <header class="card__header">{{#str}}pluginname, theme_degrade{{/str}} Preview</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_degrade{{/str}} Preview. All rights reserved.</footer>
        {{/footercolor}}
    </section>
</div>

{{#js}}
    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);
            {{/startcolor}}
            {{#brandcolor}}
                $(`input[id^="id_"][id$="_brandcolor"]`)
                        .val(color)
                        .minicolors("settings", {value: color});
                updateMainColor(color);
            {{/brandcolor}}
            {{#footercolor}}
                $(`input[id^="id_"][id$="_footer_background_color"]`)
                        .val(color)
                        .minicolors("settings", {value: color});
                updateMainColor(null, color);
            {{/footercolor}}
        });

        {{#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}}

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

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

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

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

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

                const textFooterColor = luminance(newColor) > 0.6 ? "#333333" : "#FFFFFF";
                root.style.setProperty("--preview-footer-bg", newColor);
                root.style.setProperty("--preview-footer-text", textFooterColor);
            }
            if (newFooterColor && newFooterColor[5]) {
                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}}
