/** @odoo-module **/
// Fusion Claims - Gallery Preview
// Uses Odoo's native FileViewer (same as chatter)
// Copyright 2024-2025 Nexa Systems Inc.
// License OPL-1

import { patch } from "@web/core/utils/patch";
import { Many2ManyBinaryField } from "@web/views/fields/many2many_binary/many2many_binary_field";
import { useFileViewer } from "@web/core/file_viewer/file_viewer_hook";
import { onMounted, onWillUnmount } from "@odoo/owl";

/**
 * Patch Many2ManyBinaryField to use Odoo's native FileViewer
 * when inside our gallery section (fc-gallery-content class)
 */
patch(Many2ManyBinaryField.prototype, {
    setup() {
        super.setup();
        
        // Use Odoo's native file viewer hook (same as chatter)
        this.fileViewer = useFileViewer();
        
        // Bind the click handler
        this._onGalleryClick = this._onGalleryClick.bind(this);
        
        onMounted(() => {
            // Find if we're inside a gallery section
            const el = this.__owl__.bdom?.el;
            if (el) {
                const gallery = el.closest('.fc-gallery-content');
                if (gallery) {
                    // Add click listener to intercept downloads
                    el.addEventListener('click', this._onGalleryClick, true);
                    this._galleryElement = el;
                }
            }
        });
        
        onWillUnmount(() => {
            if (this._galleryElement) {
                this._galleryElement.removeEventListener('click', this._onGalleryClick, true);
            }
        });
    },
    
    /**
     * Handle clicks on attachments in gallery - intercept and use FileViewer
     */
    _onGalleryClick(ev) {
        // Check if click is anywhere inside an attachment box
        const attachmentBox = ev.target.closest('.o_attachment');
        
        if (!attachmentBox) {
            return; // Not an attachment click
        }
        
        // Skip if clicking on the delete button
        if (ev.target.closest('.o_attachment_delete')) {
            return;
        }
        
        // Get file ID from any link or image within the attachment box
        let fileId = null;
        
        // Try to get from link href
        const link = attachmentBox.querySelector('a[href*="/web/content/"], a[href*="/web/image/"]');
        if (link) {
            const href = link.getAttribute('href') || '';
            const match = href.match(/\/web\/(?:content|image)\/(\d+)/);
            if (match) {
                fileId = parseInt(match[1], 10);
            }
        }
        
        // Try to get from image src
        if (!fileId) {
            const imgEl = attachmentBox.querySelector('img[src*="/web/image/"]');
            if (imgEl) {
                const src = imgEl.getAttribute('src') || '';
                const match = src.match(/\/web\/image\/(\d+)/);
                if (match) {
                    fileId = parseInt(match[1], 10);
                }
            }
        }
        
        if (!fileId) {
            return; // Couldn't determine file ID
        }
        
        // Prevent download
        ev.preventDefault();
        ev.stopPropagation();
        
        // Get all files and transform to FileViewer format
        const files = this.files.map(file => {
            const mimetype = file.mimetype || 'image/png';
            const isImage = mimetype.startsWith('image/');
            const isPdf = mimetype === 'application/pdf';
            
            return {
                id: file.id,
                name: file.name || 'File',
                mimetype: mimetype,
                isImage: isImage,
                isPdf: isPdf,
                isViewable: isImage || isPdf,
                defaultSource: isImage ? `/web/image/${file.id}` : `/web/content/${file.id}`,
                downloadUrl: `/web/content/${file.id}?download=true`,
            };
        });
        
        // Find the clicked file and open FileViewer
        const clickedFile = files.find(f => f.id === fileId);
        
        if (clickedFile && this.fileViewer) {
            this.fileViewer.open(clickedFile, files);
        }
    }
});
