/**
 * Standalone admin pages (inventory, purchase-*) use the same RTDB semantics as dashboard.js
 * for staff vs owner. Keep in sync when changing role/permission rules in dashboard.js.
 */

/**
 * @param {unknown} r RTDB `clients/{clientId}/admins/{uid}` value
 * @returns {'owner'|'staff'|'admin'|'unknown'}
 */
export function resolveEffectiveDashboardRoleFromAdminNode(r) {
    if (!r || typeof r !== 'object') return 'unknown';
    const roleStr = String(r.role ?? '').trim().toLowerCase();
    if (roleStr === 'owner') return 'owner';
    if (roleStr === 'staff') return 'staff';
    if (roleStr === 'admin') return 'admin';
    if (roleStr !== '') return roleStr;
    const hasCreatedBy = r.createdBy != null && String(r.createdBy).trim() !== '';
    const perm = r.permissions;
    const hasExplicitPerm =
        perm &&
        typeof perm === 'object' &&
        Object.keys(perm).some((k) => perm[k] === true);
    if (!hasCreatedBy && !hasExplicitPerm) return 'owner';
    return 'staff';
}

/**
 * @param {unknown} r
 * @param {string} panelId e.g. `products`, `purchase-add`
 */
export function staffHasStrictPanelPermission(r, panelId) {
    const pid = String(panelId || '').trim();
    if (pid === 'home') return true;
    const role = resolveEffectiveDashboardRoleFromAdminNode(r);
    if (role === 'owner') return true;
    if (role === 'admin') return true;
    const p = r && typeof r === 'object' ? r.permissions : null;
    if (!p || typeof p !== 'object') return false;
    return p[pid] === true;
}
