// annotator.js – dépend de Fabric.js (inclus dans header)
let annotatorCanvas = null;
let currentImageId = null;
let currentModal = null;

function openAnnotator(imageId, imageUrl, onSaveCallback) {
    currentImageId = imageId;
    // Créer le modal s'il n'existe pas
    let modal = document.getElementById('annotateModal');
    if (!modal) {
        const modalHtml = `
        <div class="modal fade" id="annotateModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-xl">
                <div class="modal-content">
                    <div class="modal-header bg-primary text-white">
                        <h5 class="modal-title"><i class="fas fa-draw-polygon"></i> Annotation de l'image</h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-9">
                                <canvas id="annotationCanvas" width="800" height="600" style="border:1px solid #ccc; background:#f0f0f0;"></canvas>
                            </div>
                            <div class="col-md-3">
                                <div class="card">
                                    <div class="card-header">Outils</div>
                                    <div class="card-body">
                                        <button class="btn btn-sm btn-primary w-100 mb-2" id="drawCircleBtn"><i class="fas fa-circle"></i> Cercle</button>
                                        <button class="btn btn-sm btn-primary w-100 mb-2" id="drawArrowBtn"><i class="fas fa-arrow-right"></i> Flèche</button>
                                        <button class="btn btn-sm btn-danger w-100 mb-2" id="clearBtn">Effacer tout</button>
                                        <hr>
                                        <button class="btn btn-sm btn-success w-100" id="saveAnnotationsBtn">Enregistrer</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fermer</button>
                    </div>
                </div>
            </div>
        </div>`;
        document.body.insertAdjacentHTML('beforeend', modalHtml);
        modal = document.getElementById('annotateModal');
    }

    // Initialiser Fabric
    if (annotatorCanvas) annotatorCanvas.dispose();
    annotatorCanvas = new fabric.Canvas('annotationCanvas');

    // Charger l'image
    fabric.Image.fromURL(imageUrl, function(img) {
        let scale = Math.min(800 / img.width, 600 / img.height);
        img.scale(scale);
        annotatorCanvas.setWidth(img.width * scale);
        annotatorCanvas.setHeight(img.height * scale);
        annotatorCanvas.setBackgroundImage(img, annotatorCanvas.renderAll.bind(annotatorCanvas));
        annotatorCanvas.renderAll();

        // Charger les annotations existantes
        fetch(BASE_URL + 'ajax_load_annotations.php?image_id=' + imageId)
            .then(response => response.json())
            .then(data => {
                if (data.annotations && data.annotations.objects) {
                    fabric.util.enlivenObjects(data.annotations.objects, function(objs) {
                        objs.forEach(obj => annotatorCanvas.add(obj));
                        annotatorCanvas.renderAll();
                    });
                }
            });
    });

    let currentMode = 'circle';
    document.getElementById('drawCircleBtn').onclick = () => {
        currentMode = 'circle';
        annotatorCanvas.isDrawingMode = false;
        annotatorCanvas.selection = true;
    };
    document.getElementById('drawArrowBtn').onclick = () => {
        currentMode = 'arrow';
        annotatorCanvas.isDrawingMode = false;
        annotatorCanvas.selection = true;
    };
    // Ajouter un cercle au clic
    annotatorCanvas.on('mouse:down', function(e) {
        if (currentMode === 'circle' && e.target === null) {
            const pointer = annotatorCanvas.getPointer(e.e);
            const circle = new fabric.Circle({
                left: pointer.x - 20,
                top: pointer.y - 20,
                radius: 20,
                fill: 'rgba(255,0,0,0.2)',
                stroke: 'red',
                strokeWidth: 2,
                hasControls: true,
                hasBorders: true
            });
            annotatorCanvas.add(circle);
            annotatorCanvas.renderAll();
        }
    });
    // Dessiner une flèche (ligne + triangle)
    let line, isDrawing = false;
    annotatorCanvas.on('mouse:down', function(e) {
        if (currentMode !== 'arrow') return;
        const pointer = annotatorCanvas.getPointer(e.e);
        line = new fabric.Line([pointer.x, pointer.y, pointer.x, pointer.y], {
            stroke: 'red',
            strokeWidth: 3,
            selectable: true
        });
        annotatorCanvas.add(line);
        isDrawing = true;
    });
    annotatorCanvas.on('mouse:move', function(e) {
        if (!isDrawing) return;
        const pointer = annotatorCanvas.getPointer(e.e);
        line.set({ x2: pointer.x, y2: pointer.y });
        annotatorCanvas.renderAll();
    });
    annotatorCanvas.on('mouse:up', function() {
        if (!isDrawing) return;
        isDrawing = false;
        const x1 = line.x1, y1 = line.y1, x2 = line.x2, y2 = line.y2;
        const angle = Math.atan2(y2 - y1, x2 - x1);
        const arrowSize = 15;
        const triangle = new fabric.Triangle({
            left: x2,
            top: y2,
            angle: angle * 180 / Math.PI + 90,
            width: arrowSize,
            height: arrowSize,
            fill: 'red',
            originX: 'center',
            originY: 'center'
        });
        annotatorCanvas.add(triangle);
        annotatorCanvas.renderAll();
    });

    document.getElementById('clearBtn').onclick = () => {
        const objects = annotatorCanvas.getObjects().filter(obj => obj !== annotatorCanvas.backgroundImage);
        objects.forEach(obj => annotatorCanvas.remove(obj));
        annotatorCanvas.renderAll();
    };
    document.getElementById('saveAnnotationsBtn').onclick = () => {
        const objects = annotatorCanvas.getObjects().filter(obj => obj !== annotatorCanvas.backgroundImage);
        const annotations = { objects: objects.map(obj => obj.toJSON()) };
        fetch(BASE_URL + 'ajax_save_annotations.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'image_id=' + currentImageId + '&annotations=' + encodeURIComponent(JSON.stringify(annotations))
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Annotations sauvegardées');
                const modalEl = document.getElementById('annotateModal');
                bootstrap.Modal.getInstance(modalEl).hide();
                if (onSaveCallback) onSaveCallback();
            } else {
                alert('Erreur : ' + data.error);
            }
        });
    };

    currentModal = new bootstrap.Modal(modal);
    currentModal.show();
}