/**
 * Composable: useKbxRegistry
 * Access screen registry, permissions, and density from components
 */

import { computed, inject, ref } from 'vue'
import type {
  KbxScreenDefinition,
  KbxPermissionDefinition,
  KbxDensity,
} from '@shared/contracts/kbx-types'

// Reactive state
const currentDensity = ref<KbxDensity>('compact')
const userPermissions = ref<Set<string>>(new Set())

export function useKbxRegistry() {
  // Get injected registries
  const screenRegistry = inject<Map<string, KbxScreenDefinition>>(
    'kbx-screens',
    new Map(),
  )

  const permissionRegistry = inject<Map<string, KbxPermissionDefinition>>(
    'kbx-permissions',
    new Map(),
  )

  // Screen methods
  const getScreen = (screenId: string) => screenRegistry.get(screenId)

  const getAllScreens = () => Array.from(screenRegistry.values())

  const getScreenByModule = (module: string) =>
    getAllScreens().filter(s => s.module === module)

  // Permission methods
  const hasPermission = (permissionId: string) => {
    return userPermissions.value.has(permissionId)
  }

  const hasAllPermissions = (permissionIds: string[]) => {
    return permissionIds.every(id => userPermissions.value.has(id))
  }

  const hasAnyPermission = (permissionIds: string[]) => {
    return permissionIds.some(id => userPermissions.value.has(id))
  }

  const canAccessScreen = (screenId: string) => {
    const screen = getScreen(screenId)
    if (!screen) return false
    return hasAllPermissions(screen.permissions)
  }

  // Density methods
  const setDensity = (density: KbxDensity) => {
    currentDensity.value = density
    document.documentElement.style.setProperty('--kbx-density', density)

    const tokens = {
      compact: {
        inputHeight: '34px',
        gridRowHeight: '34px',
        touchTarget: '44px',
        fontSize: '12px',
        controlHeight: '34px',
      },
      comfortable: {
        inputHeight: '36px',
        gridRowHeight: '36px',
        touchTarget: '48px',
        fontSize: '14px',
        controlHeight: '36px',
      },
      touch: {
        inputHeight: '48px',
        gridRowHeight: '48px',
        touchTarget: '52px',
        fontSize: '16px',
        controlHeight: '48px',
      },
    }

    Object.entries(tokens[density]).forEach(([key, value]) => {
      document.documentElement.style.setProperty(`--kbx-${key}`, value)
    })
  }

  const getDensity = computed(() => currentDensity.value)

  // Update user permissions
  const setPermissions = (permissions: string[]) => {
    userPermissions.value.clear()
    permissions.forEach(p => userPermissions.value.add(p))
  }

  return {
    // Screen access
    getScreen,
    getAllScreens,
    getScreenByModule,
    canAccessScreen,

    // Permission access
    hasPermission,
    hasAllPermissions,
    hasAnyPermission,
    setPermissions,

    // Density
    setDensity,
    getDensity,

    // Registries
    screenRegistry,
    permissionRegistry,
  }
}
