import { useEffect } from 'react';
import { useStore } from 'react-redux';
import { hasPermission } from './ui/permissions';

/**
 * HostBridge — exposes a stable runtime API to the addons (lazytasks-timetracker,
 * lazytasks-performance, lazytasks-whiteboard) at `window.lazytasksHost`.
 *
 * Addons have their own Redux stores and can't directly read the main plugin's
 * `state.auth`. The bridge gives them live, accurate user + permission data
 * via lightweight functions that read from the main plugin's store on demand.
 *
 * Mount this once inside the main plugin's <Provider> so it has store access,
 * then fire `lazytasksHostReady` so addons that loaded earlier can pick up the
 * bridge via the event listener fallback.
 *
 * Versioning: `version` field on the bridge bumps when the contract changes.
 * Addons should check `window.lazytasksHost?.version >= 1` before relying on
 * any method. Additive changes (new methods) don't bump the version; signature
 * changes do.
 *
 * @since 1.6.23 (TimeTracker addon Phase 4)
 */
const HostBridge = () => {
    const store = useStore();

    useEffect(() => {
        if (typeof window === 'undefined') return;

        const getLoggedInUser = () => {
            try {
                return store.getState().auth?.session?.loggedInUser ?? null;
            } catch (e) {
                return null;
            }
        };

        const getProjectPermissions = (projectId) => {
            try {
                const id = String(projectId);
                return store.getState().auth?.permissions?.projects?.[id]?.permissions ?? [];
            } catch (e) {
                return [];
            }
        };

        const getGlobalPermissions = () => {
            const user = getLoggedInUser();
            return user?.llc_permissions ?? [];
        };

        const allProjectPermissions = () => {
            try {
                const projects = store.getState().auth?.permissions?.projects ?? {};
                return projects;
            } catch (e) {
                return {};
            }
        };

        // Live wrapper around the existing hasPermission utility.
        // Signature: (perms, projectId | null, scope = 'project')
        // - scope === 'global': checks user.llc_permissions
        // - scope === 'project': checks projectPermissions for the given projectId
        const hostHasPermission = (perms, projectId = null, scope = 'project') => {
            const user = getLoggedInUser();
            if (!user) return false;
            const projPerms = scope === 'project' && projectId != null
                ? getProjectPermissions(projectId)
                : null;
            return hasPermission(user, Array.isArray(perms) ? perms : [perms], projPerms, scope);
        };

        // True if the user has the perm on at least one project (or is superadmin).
        const hasAnyProjectPermission = (perm) => {
            const user = getLoggedInUser();
            if (!user) return false;
            if (user.is_superadmin) return true;
            const projects = allProjectPermissions();
            for (const id in projects) {
                const list = projects[id]?.permissions;
                if (Array.isArray(list) && list.includes(perm)) return true;
            }
            return false;
        };

        window.lazytasksHost = {
            version: 1,
            getLoggedInUser,
            getProjectPermissions,
            getGlobalPermissions,
            hasPermission: hostHasPermission,
            hasAnyProjectPermission,
        };

        window.dispatchEvent(new Event('lazytasksHostReady'));
    }, [store]);

    return null;
};

export default HostBridge;
