<style>
/* Editor Redesign Styles */
.editor-section {
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
    overflow: hidden;
    margin-bottom: 20px;
    border: 1px solid #e2e8f0;
}

.editor-header {
    background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
    padding: 15px 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 10px;
}

.editor-header h4 {
    margin: 0;
    font-size: 16px;
    font-weight: 700;
    color: #fff;
    display: flex;
    align-items: center;
    gap: 10px;
}

.editor-header h4 i {
    color: #10b981;
}

.editor-body {
    display: grid;
    grid-template-columns: 1fr 1fr;
    min-height: 70vh;
}

@media (max-width: 992px) {
    .editor-body {
        grid-template-columns: 1fr;
    }
}

.editor-panel {
    border-right: 1px solid #e2e8f0;
}

.editor-panel:last-child {
    border-right: none;
}

.panel-header {
    background: #f8fafc;
    padding: 12px 20px;
    border-bottom: 1px solid #e2e8f0;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.panel-header h5 {
    margin: 0;
    font-size: 14px;
    font-weight: 600;
    color: #1e293b;
    display: flex;
    align-items: center;
    gap: 8px;
}

.panel-header h5 i {
    color: #10b981;
}

.editor-container {
    height: calc(70vh - 50px);
    width: 100%;
    position: relative;
    background: #f6e8ea;
}

#conatiner {
    height: 100% !important;
    width: 100% !important;
}

/* Carousel Panel */
.carousel-panel .panel-body {
    padding: 15px;
}

.carousel-tabs {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
    margin-bottom: 15px;
}

.carousel-tab {
    padding: 6px 14px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    background: #e2e8f0;
    color: #64748b;
    border: none;
    cursor: pointer;
    transition: all 0.2s ease;
}

.carousel-tab:hover,
.carousel-tab.active {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: #fff;
}

.carousel-nav {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 15px;
}

.carousel-btn {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: #fff;
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    font-weight: bold;
    transition: all 0.2s ease;
}

.carousel-btn:hover {
    transform: scale(1.1);
    box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}

.carousel-container {
    border-radius: 12px;
    overflow: hidden;
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    max-height: calc(70vh - 150px);
    overflow-y: auto;
}

.mySlides {
    display: none;
}

.mySlides.active,
.mySlides:first-child {
    display: block;
}

.mySlides img {
    width: 100%;
    height: auto;
    object-fit: contain;
}

/* Hide default prev/next in new design */
.prev, .next {
    display: none;
}
</style>

<div class="editor-section">
    <div class="editor-header">
        <h4><i class="uil uil-edit"></i> Éditeur de Documents</h4>
    </div>
    <div class="editor-body">
        <!-- Editor Panel -->
        <div class="editor-panel">
            <div class="panel-header">
                <h5><i class="uil uil-image-edit"></i> Zone d'édition</h5>
            </div>
            <input type="hidden" id="src" value="{{ Storage::disk('s3')->temporaryUrl($document->path, now()->addMinutes(30)) ?? null }}">
            <div class="editor-container">
                <div id="conatiner"></div>
            </div>
        </div>

        <!-- Carousel Panel -->
        <div class="editor-panel">
            <div class="panel-header">
                <h5><i class="uil uil-images"></i> Documents</h5>
            </div>
            <div class="panel-body" style="padding: 15px;">
                <!-- Document Type Tabs -->
                <div class="carousel-tabs">
                    <input type="hidden" id="dossier" value="{{ $dossier->id }}">
                    <button type="button" data-filter="ALL" class="carousel-tab filter active" onclick="get(this)">ALL</button>
                    @foreach ($typedocuments as $type)
                        <button type="button" data-filter="{{ $type->id }}" class="carousel-tab filter" onclick="get(this)">{{ $type->type }}</button>
                    @endforeach
                </div>

                <!-- Navigation Buttons -->
                <div class="carousel-nav">
                    <button type="button" class="carousel-btn" onclick="plusSlides(-1)">
                        <i class="uil uil-angle-left"></i>
                    </button>
                    <button type="button" class="carousel-btn" onclick="plusSlides(1)">
                        <i class="uil uil-angle-right"></i>
                    </button>
                    <span style="color: #64748b; font-size: 13px; margin-left: 10px;">
                        Utilisez les flèches pour naviguer
                    </span>
                </div>

                <!-- Carousel -->
                <div id="carrousel" class="carousel-container">
                    @foreach ($dossier->document as $index => $doc)
                        <div class="mySlides media1 {{ $doc->typedocument->type ?? null }} {{ $index === 0 ? 'active' : '' }}">
                            <img src="{{ Storage::disk('s3')->temporaryUrl($doc->path, now()->addMinutes(30)) }}" alt="Document">
                        </div>
                    @endforeach
                </div>
            </div>
        </div>
    </div>
    
    <!-- Hidden Form -->
    <form id="myForm" action="{{ route('Document.update', $document->id) }}" method="post">
        @csrf
        @method('PUT')
        <input type="hidden" name="img" value="" id="edited">
    </form>
</div>

@section('script')
    <script src="{{ asset('js/Painterro/painterro.min.js') }}"></script>
    <script src="{{ asset('js/tinymce/tinymce.min.js') }}"></script>
    <script src="{{ asset('js/tinymce/init-tinymce.js') }}"></script>
    <script src="{{ asset('js/viewer.js') }}"></script>
    
    <script>
        window.addEventListener('load', function() {
            console.log('DOM fully loaded and parsed');
            var galley = document.getElementById('galley');
            if (galley) {
                var maxOffsetPercentage = 0.9;
                var viewer = new Viewer(galley, {
                    url: 'data-original',
                    backdrop: 'static',
                    move: function(event) {
                        var viewerData = viewer.viewerData;
                        var imageData = viewer.imageData;
                        var maxOffsetHorizontal = viewerData.width * maxOffsetPercentage;
                        var maxOffsetVertical = viewerData.height * maxOffsetPercentage;
                        var detail = event.detail;
                        var left = detail.x;
                        var top = detail.y;
                        var right = viewerData.width - (left + imageData.width);
                        var bottom = viewerData.height - (top + imageData.height);
                        if (
                            (detail.x < detail.oldX && right > 0 && right > maxOffsetHorizontal) ||
                            (detail.x > detail.oldX && left > 0 && left > maxOffsetHorizontal) ||
                            (detail.y < detail.oldY && bottom > 0 && bottom > maxOffsetVertical) ||
                            (detail.y > detail.oldY && top > 0 && top > maxOffsetVertical)
                        ) {
                            event.preventDefault();
                        }
                    },
                    zoomed: function(event) {
                        var detail = event.detail;
                        if (detail.ratio < detail.oldRatio) {
                            var viewerData = viewer.viewerData;
                            var imageData = viewer.imageData;
                            var maxOffsetHorizontal = viewerData.width * maxOffsetPercentage;
                            var maxOffsetVertical = viewerData.height * maxOffsetPercentage;
                            var left = imageData.x;
                            var top = imageData.y;
                            var right = viewerData.width - (left + imageData.width);
                            var bottom = viewerData.height - (top + imageData.height);
                            var x = 0;
                            var y = 0;
                            if (right > 0 && right > maxOffsetHorizontal) x = maxOffsetHorizontal - right;
                            if (left > 0 && left > maxOffsetHorizontal) x = maxOffsetHorizontal - left;
                            if (bottom > 0 && bottom > maxOffsetVertical) y = bottom - maxOffsetVertical;
                            if (top > 0 && top > maxOffsetVertical) y = top - maxOffsetVertical;
                            if (x !== 0 || y !== 0) viewer.move(x, y);
                        }
                    },
                });
            }
        });
    </script>
    
    <script>
        window.onload = function() {
            var image = document.getElementById('src').value;
            if (image) showDevis(image);
        };

        let slideIndex = 1;
        showSlides(slideIndex);

        function plusSlides(n) {
            showSlides(slideIndex += n);
        }

        function currentSlide(n) {
            showSlides(slideIndex = n);
        }

        function showSlides(n) {
            let slides = document.getElementsByClassName("mySlides");
            if (slides.length === 0) return;
            
            if (n > slides.length) slideIndex = 1;
            if (n < 1) slideIndex = slides.length;
            
            for (let i = 0; i < slides.length; i++) {
                slides[i].style.display = "none";
                slides[i].classList.remove('active');
            }
            
            slides[slideIndex - 1].style.display = "block";
            slides[slideIndex - 1].classList.add('active');
        }

        function showDevis(path) {
            document.querySelector('#conatiner').innerHTML = '';
            let P = Painterro({
                activeColor: '#FFF',
                id: 'conatiner',
                language: 'fr',
                defaultTool: 'brush',
                initTextStyle: "18px 'Open Sans', sans-serif",
                hiddenTools: ['close', 'settings', 'resize', 'open'],
                activeColor: '#FF0000',
                initTextColor: '#FF0000',
                setColor: '#FF0000',
                colorScheme: {
                    activeColor: '#FFF',
                    main: '#F6E8EA',
                    control: '#FFF',
                    inputBackground: '#FFF',
                    backgroundColor: '#F6E8EA',
                    inputText: '#000000',
                },
                saveHandler: function(image, done) {
                    let imageData = image.asDataURL('image/jpeg');
                    document.getElementById('edited').value = imageData;
                    document.getElementById("myForm").submit();
                }
            });
            P.show(path);
        }
    </script>
    
    <script>
        var $Elements = $('.media1');

        $('.link').click(function(e) {
            e.preventDefault();
            var filterVal = $(this).data('filter');
            if (filterVal === 'ALL') {
                $Elements.removeClass('hidden');
            } else {
                $Elements.addClass('hidden').filter('.' + filterVal).removeClass('hidden');
            }
        });

        function get(e) {
            const type = e.getAttribute('data-filter');
            const id = document.getElementById('dossier').value;
            const carrousel = document.getElementById('carrousel');

            // Update active tab
            document.querySelectorAll('.carousel-tab').forEach(tab => tab.classList.remove('active'));
            e.classList.add('active');

            $.ajax({
                url: '/Document/' + id + '/Type/' + type,
                type: 'get',
                success: function(response) {
                    carrousel.innerHTML = '';
                    var html = '';
                    $.each(response, function(k, v) {
                        html += "<div class='mySlides media1' style='" + (k === 0 ? "display:block" : "display:none") + "'>";
                        html += "<img src='" + v.image + "' style='width:100%'>";
                        html += "</div>";
                    });
                    carrousel.innerHTML = html;
                    slideIndex = 1;
                },
                error: function(error) {
                    console.log(error);
                },
            });
        }
    </script>

    <script>
        $(document).ready(function() {
            $(".savedevis").click(function(event) {
                event.preventDefault();

                var checkedRowIndices = [];
                var piecetypes = [];
                var pieces = [];
                var types = [];
                var operations = [];
                var qtes = [];
                var vetustes = [];
                var remises = [];
                var prices = [];
                var gravities = [];
                var etats = [];

                $('input[type=checkbox]').each(function() {
                    if ($(this)[0].checked) {
                        var id = $(this)[0].value;
                        checkedRowIndices.push(id);
                        piecetypes.push($("#pt" + id).val());
                        pieces.push($("#pc" + id).val());
                        types.push($("#t" + id).val());
                        operations.push($("#o" + id).val());
                        qtes.push($("#id" + id).val());
                        vetustes.push($("#v" + id).val());
                        remises.push($("#r" + id).val());
                        prices.push($("#p" + id).val());
                        gravities.push($("#g" + id).val());
                        etats.push($("#e" + id).val());
                    }
                });

                let devis_id = $("input[name=devis_id]").val();
                let _token = $('meta[name="csrf-token"]').attr('content');

                $.ajax({
                    url: "/Devis/attach",
                    type: "POST",
                    data: {
                        piecetype: piecetypes,
                        libelle: pieces,
                        type: types,
                        operation: operations,
                        piece: checkedRowIndices,
                        devis_id: devis_id,
                        qte: qtes,
                        vetuste: vetustes,
                        remise: remises,
                        prix_unitaire: prices,
                        etat: etats,
                        gravite: gravities,
                        _token: _token
                    },
                    success: function(response) {
                        if (response) {
                            $('.success').text(response.success);
                            alert('Pièces enregistrées avec succès!');
                        }
                    },
                });
            });
        });
    </script>
@endsection