{% if environnement == 'recette' or environnement == 'preproduction' or environnement == 'production' and user.is_administrateur or environnement == 'production' and user.is_staff %}
<div id="macaron_retour">
    <img src="https://revolucy.fr/wp-content/uploads/2024/12/icone-retour.png" alt="Besoin d'aide ?">
</div>
<div id="popup_retour" style="display: none;">
    <div>
        <span id="close_popup" style="cursor: pointer;">&times;</span>
        <form id="retour_client_form" method="post" enctype="multipart/form-data" action="{% url 'retour_client:retour_client_form' %}">
            {% csrf_token %}
            <h4>Ajouter un bug</h4>
            {% if environnement == 'production' and jrs_restant_garantie < 0 %}
            <span class="solde_ticket {% if solde_ticket < 1 %}solde_faible{% endif %}">{{ solde_ticket }} h de crédit disponible</span>
            {% if solde_ticket < 1 %}
            <a href="https://app.lucy-crm.fr/sav/souscription-client-ticket/{{ siren_client }}" target="_blank"
               style="background: #0818af;color: #FFF;text-align: center;display: block;width: 100%;padding: 9px 0 6px 0;margin-bottom: 10px;border-radius: 5px;font-weight: bold;">Souscrire à un pack
                de ticket de 10H</a>
            {% endif %}
            {% endif %}
            <div>
                <label for="{{ form_bug.priorite.id_for_label }}">Priorité</label>
                {{ form_bug.priorite }}
                {% if form_bug.priorite.errors %}
                {% for error in form_bug.priorite.errors %}
                <p class="erreur">{{ error|escape }}</p>
                {% endfor %}
                {% endif %}
            </div>
            <div>
                <label for="{{ form_bug.titre.id_for_label }}">Titre</label>
                {{ form_bug.titre }}
                {% if form_bug.titre.errors %}
                {% for error in form_bug.titre.errors %}
                <p class="erreur">{{ error|escape }}</p>
                {% endfor %}
                {% endif %}
            </div>
            <div>
                <label for="{{ form_bug.description.id_for_label }}">Description</label>
                <button type="button" id="btn_aide_ia" class="btn-aide-ia" title="Générer une aide à la rédaction avec l'IA">
                    Générer la description par IA
                </button>
                {{ form_bug.description }}
                {% if form_bug.description.errors %}
                {% for error in form_bug.description.errors %}
                <p class="erreur">{{ error|escape }}</p>
                {% endfor %}
                {% endif %}
                <div id="ia_loading" style="display: none; text-align: center; padding: 10px;">
                    <span class="ia-spinner"></span> Génération en cours...
                </div>
            </div>
            <input type="hidden" id="lien_url" name="lien_url">
            <input type="hidden" id="navigateur" name="navigateur">
            <input type="hidden" id="image" name="image">
            <div id="retour_message" style="display: none; color: green;"></div>
            <button type="submit" class="mt-3 submit-retour">Envoyer</button>
            <a href="{% url 'retour_client:pipeline_retours' %}" target="_blank" class="mt-3 btn-plus-bug">Voir toute la liste</a>
        </form>
    </div>
</div>
<style>

    table.retour_bug_table td {
        border: 1px solid #969696;
        padding: 5px;
    }

    .solde_ticket.solde_faible {
        background: #ff6c6c;
    }

    table.retour_bug_table tr > td:first-child {
        background: #e6e6e6;
    }

    #accordionBug .accordion-header button.collapsed {
        background: #fff;
        border-bottom: 1px solid #e6e6e6;
    }

    #accordionBug .accordion-header button {
        background: #e6e6e6;
        padding: 7px 10px;
        color: #000;
    }

    #accordionBug .accordion-collapse {
        padding-bottom: 5px;
    }

    .solde_ticket {
        background: #1416aa;
        width: 100%;
        display: block;
        padding: 3px;
        text-align: center;
        margin-bottom: 8px;
        border-radius: 6px;
        color: #fff;
    }

    #macaron_retour > img {
        max-width: 60px;
    }

    #macaron_retour {
        position: fixed;
        bottom: 100px;
        right: 0px;
        cursor: pointer;
        z-index: 999;
    }

    span.repondant {
        position: absolute;
        right: 10px;
        font-size: 15px;
    }

    #popup_retour {
        position: fixed;
        bottom: 100px;
        right: -1px;
        width: 450px;
        background: white;
        border: 2px solid #e63363;
        border-radius: 15px 0 0 15px;
        padding: 20px;
        z-index: 9999;
        max-width: 95%;
    }

    #close_popup {
        position: absolute;
        font-size: 1.5em;
        right: 10px;
        top: 5px;
    }

    #retour_client_form select, #retour_client_form textarea, #retour_client_form input {
        width: 100%;
        margin-bottom: 15px;
        border-radius: 5px;
        padding: 5px 10px;
        border: 2px solid #c5c5c5;
    }

    #retour_client_form h4 {
        text-align: center;
        text-transform: uppercase;
        border-bottom: 1px solid;
        margin-bottom: 15px;
        padding-bottom: 15px;
        font-size: 22px;
    }

    #retour_client_form button.submit-retour {
        width: 100%;
        background: #e63363;
        color: #fff;
        border: none;
        padding: 5px;
        border-radius: 10px;
        text-transform: uppercase;
    }

    #retour_client_form button.submit-retour:hover {
        background: #000;
    }

    a.btn-plus-bug {
        width: 100%;
        background: #000;
        color: #fff;
        border: none;
        padding: 5px;
        border-radius: 10px;
        text-transform: uppercase;
    }

    a.btn-plus-bug:hover {
        background: #e63363;
    }

    #liste_retours .accordion-body {
        padding: 10px;
        font-size: 16px;
    }

    #retour_message {
        text-align: center;
        font-size: 14px;
        background: #dcdcdc;
        padding: 5px;
        margin-bottom: 10px;
        border-radius: 10px;
        width: 100%;
    }

    a.btn-plus-bug {
        display: block;
        text-align: center;
        margin-top: 10px;
    }

    span.num_ticket {
        background: #c5c5c5;
        width: 30px;
        height: 30px;
        text-align: center;
        line-height: 30px;
        border-radius: 3px;
        margin-right: 13px;
        font-size: 12px;
        color: #fff;
    }

    /* Bouton Aide IA */
    .btn-aide-ia {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: #fff;
        border: none;
        padding: 3px 12px;
        border-radius: 15px;
        font-size: 12px;
        cursor: pointer;
        transition: all 0.2s ease;
        float: right;
        margin-top: -10px;
    }

    .btn-aide-ia:hover {
        transform: scale(1.05);
        box-shadow: 0 2px 8px rgba(102, 126, 234, 0.4);
    }

    .btn-aide-ia.loading {
      display: none;
    }

    .btn-aide-ia:disabled {
        opacity: 0.6;
        cursor: not-allowed;
        transform: none;
    }

    @keyframes spin {
        from {
            transform: rotate(0deg);
        }
        to {
            transform: rotate(360deg);
        }
    }

    .ia-spinner {
        display: inline-block;
        width: 16px;
        height: 16px;
        border: 2px solid #667eea;
        border-radius: 50%;
        border-top-color: transparent;
        animation: spin 1s linear infinite;
        vertical-align: middle;
        margin-right: 5px;
    }

    #ia_loading {
        color: #667eea;
        font-size: 13px;
    }
</style>

<script src="https://cdn.jsdelivr.net/npm/dom-to-image-more@3/dist/dom-to-image-more.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        var macaron = document.getElementById('macaron_retour');
        var popup = document.getElementById('popup_retour');
        var closePopup = document.getElementById('close_popup');
        var form = document.getElementById('retour_client_form');
        var messageDiv = document.getElementById('retour_message');

        macaron.addEventListener('click', function () {
            popup.style.display = 'block';
            document.getElementById('lien_url').value = window.location.href;
            document.getElementById('navigateur').value = navigator.userAgent;
            takeScreenshot();
        });

        closePopup.addEventListener('click', function () {
            popup.style.display = 'none';
        });

        // Bouton Aide IA
        var btnAideIA = document.getElementById('btn_aide_ia');
        var titreField = document.getElementById('id_titre');
        var descriptionField = document.getElementById('id_description');
        var iaLoading = document.getElementById('ia_loading');

        if (btnAideIA) {
            btnAideIA.addEventListener('click', async function () {
                var titre = titreField ? titreField.value.trim() : '';

                if (!titre) {
                    alert('Veuillez d\'abord saisir un titre pour le bug.');
                    if (titreField) titreField.focus();
                    return;
                }

                // Afficher le loading
                btnAideIA.disabled = true;
                btnAideIA.classList.add('loading');
                if (iaLoading) iaLoading.style.display = 'block';

                try {
                    var response = await fetch("{% url 'retour_client:generation_description_public' %}", {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRFToken': form.querySelector('[name=csrfmiddlewaretoken]').value
                        },
                        body: JSON.stringify({
                            titre: titre,
                            url_page: window.location.href
                        })
                    });

                    var data = await response.json();

                    if (data.success && data.description) {
                        // Insérer la description générée
                        if (descriptionField) {
                            descriptionField.value = data.description;
                            descriptionField.focus();
                        }
                    } else {
                        alert('Erreur: ' + (data.error || 'Impossible de générer la description'));
                    }
                } catch (error) {
                    console.error('Erreur génération IA:', error);
                    alert('Erreur de connexion. Veuillez réessayer.');
                } finally {
                    btnAideIA.disabled = false;
                    btnAideIA.classList.remove('loading');
                    if (iaLoading) iaLoading.style.display = 'none';
                }
            });
        }

        form.addEventListener('submit', function (e) {
            e.preventDefault();
            var formData = new FormData(form);

            fetch(form.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': form.querySelector('[name=csrfmiddlewaretoken]').value,
                },
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        messageDiv.style.display = 'block';
                        messageDiv.textContent = 'Bug n°' + data.id + ' envoyé à Revolucy';
                        form.reset();
                    } else {
                        console.log(data)
                        messageDiv.style.display = 'block';
                        messageDiv.style.color = 'red';
                        messageDiv.textContent = 'Erreur lors de la soumission';
                    }
                })
                .catch(error => {
                    messageDiv.style.display = 'block';
                    messageDiv.style.color = 'red';
                    messageDiv.textContent = 'Erreur lors de la soumission du formulaire';
                    console.error('Erreur:', error);
                });
        });

        var screenshotInProgress = false;

        async function takeScreenshot() {
            if (screenshotInProgress) return;
            screenshotInProgress = true;

            var elementsToHide = ['#popup_retour', '#macaron_retour'];
            elementsToHide.forEach(function(selector) {
                var el = document.querySelector(selector);
                if (el) el.style.visibility = 'hidden';
            });

            // Retirer temporairement les stylesheets cross-origin (Google Fonts, CDN...)
            // pour éviter les erreurs CORS qui cassent dom-to-image-more
            var removedLinks = [];
            document.querySelectorAll('link[rel="stylesheet"]').forEach(function(link) {
                if (!link.sheet) return;
                try {
                    var _ = link.sheet.cssRules; // test d'accès CORS
                } catch (e) {
                    removedLinks.push({ el: link, next: link.nextSibling, parent: link.parentNode });
                    link.remove();
                }
            });

            try {
                var viewportWidth = window.innerWidth;
                var viewportHeight = window.innerHeight;

                var dataUrl = await domtoimage.toPng(document.body, {
                    width: viewportWidth,
                    height: viewportHeight,
                    imagePlaceholder: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
                    filter: function(node) {
                        if (node.id === 'popup_retour' || node.id === 'macaron_retour') return false;
                        if (node.tagName === 'IMG' && node.src && node.src.includes('revolucy.fr')) return false;
                        return true;
                    }
                });

                if (dataUrl && dataUrl.length > 100) {
                    var img = new Image();
                    img.src = dataUrl;
                    await new Promise(function(resolve, reject) {
                        img.onload = resolve;
                        img.onerror = reject;
                    });

                    var maxWidth = 1000;
                    var scale = img.width > maxWidth ? maxWidth / img.width : 1;

                    var canvas = document.createElement('canvas');
                    canvas.width = Math.round(img.width * scale);
                    canvas.height = Math.round(img.height * scale);
                    var ctx = canvas.getContext('2d');
                    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

                    document.getElementById('image').value = canvas.toDataURL('image/png');
                }
            } catch (error) {
                console.warn('Erreur capture écran (ignorée):', error);
            } finally {
                // Restaurer les stylesheets cross-origin
                removedLinks.forEach(function(item) {
                    if (item.next) {
                        item.parent.insertBefore(item.el, item.next);
                    } else {
                        item.parent.appendChild(item.el);
                    }
                });
                elementsToHide.forEach(function(selector) {
                    var el = document.querySelector(selector);
                    if (el) el.style.visibility = 'visible';
                });
                screenshotInProgress = false;
            }
        }

    });
</script>
{% endif %}