/** @odoo-module **/

import { discussSidebarItemsRegistry } from "@mail/core/public_web/discuss_sidebar";
import { Component, useState, onWillStart } from "@odoo/owl";
import { useService } from "@web/core/utils/hooks";
import { markEventHandled } from "@web/core/utils/misc";

/**
 * Renders each tier.mailbox as a collapsible section with conversation list.
 *
 * Under each mailbox header — list of authors (grouped conversations).
 * Clicking an author opens a DM (discuss.channel chat) with that partner.
 */
export class TierDiscussSidebarMailboxes extends Component {
    static template = "tier_communications.DiscussSidebarMailboxes";
    static props = {};

    setup() {
        this.store = useService("mail.store");
        this.orm = useService("orm");
        this.state = useState({
            openIds: {},
            conversationsByMailbox: {},  // { mailbox_id: [{partner_id, partner_name, ...}] }
        });
        onWillStart(async () => {
            await this._loadConversations();
        });
    }

    get mailboxThreads() {
        return this.store.tierMailboxThreads || [];
    }

    isOpen(threadId) {
        return this.state.openIds[threadId] !== false;
    }

    toggle(threadId) {
        this.state.openIds[threadId] = !this.isOpen(threadId);
    }

    getConversations(mailboxId) {
        return this.state.conversationsByMailbox[mailboxId] || [];
    }

    async _loadConversations() {
        try {
            const mailboxes = await this.orm.call(
                "tier.mailbox", "get_accessible_mailboxes", [], {}
            );
            for (const mailbox of (mailboxes || [])) {
                const conversations = await this.orm.call(
                    "tier.mailbox", "get_mailbox_conversations", [mailbox.id], {}
                );
                this.state.conversationsByMailbox[mailbox.id] = conversations || [];
            }
        } catch (error) {
            console.warn("[tier_communications] _loadConversations error:", error);
        }
    }

    /**
     * Open a DM (personal chat) with the given partner.
     * Uses store.getChat() which finds or creates the DM channel.
     */
    async openConversation(ev, partnerId) {
        markEventHandled(ev, "sidebar.openThread");
        if (!partnerId) {
            return;
        }
        const chat = await this.store.getChat({ partnerId });
        if (chat) {
            chat.setAsDiscussThread();
        }
    }
}

discussSidebarItemsRegistry.add(
    "tier_mailboxes",
    TierDiscussSidebarMailboxes,
    { sequence: 40 }
);
