/** @odoo-module **/

import { Component, useState, onMounted } from "@odoo/owl";
import { registry } from "@web/core/registry";

class RcSystrayItem extends Component {
    static template = "fusion_ringcentral.SystrayItem";
    static props = {};

    setup() {
        this.state = useState({
            status: "offline",
            visible: false,
        });

        onMounted(() => {
            this._checkWidgetReady();
            window.addEventListener("rc-presence-changed", (ev) => {
                this._updatePresence(ev.detail);
            });
        });
    }

    _checkWidgetReady() {
        const interval = setInterval(() => {
            if (window.RCAdapter) {
                this.state.visible = true;
                clearInterval(interval);
            }
        }, 2000);
        setTimeout(() => clearInterval(interval), 30000);
    }

    _updatePresence(presence) {
        if (!presence) return;
        this.state.visible = true;
        const userStatus = (presence.userStatus || "").toLowerCase();
        const dndStatus = (presence.dndStatus || "").toLowerCase();

        if (dndStatus === "donotacceptanycalls") {
            this.state.status = "dnd";
        } else if (userStatus === "busy" || presence.telephonyStatus === "Ringing") {
            this.state.status = "busy";
        } else if (userStatus === "available") {
            this.state.status = "available";
        } else {
            this.state.status = "offline";
        }
    }

    get statusColor() {
        const colors = {
            available: "text-success",
            busy: "text-danger",
            dnd: "text-warning",
            offline: "text-muted",
        };
        return colors[this.state.status] || "text-muted";
    }

    get statusTitle() {
        const titles = {
            available: "Available",
            busy: "Busy",
            dnd: "Do Not Disturb",
            offline: "Offline",
        };
        return titles[this.state.status] || "RingCentral";
    }

    onClick() {
        if (window.RCAdapter) {
            const frame = document.querySelector("#rc-widget-adapter-frame");
            if (frame) {
                const isMinimized = frame.style.display === "none" ||
                    frame.closest("[style*='display: none']");
                if (isMinimized) {
                    window.RCAdapter.setMinimized(false);
                } else {
                    window.RCAdapter.setMinimized(true);
                }
            }
        }
    }
}

registry.category("systray").add("fusion_ringcentral.SystrayItem", {
    Component: RcSystrayItem,
}, { sequence: 5 });
