import { watch, type Ref } from 'vue'
import type { StandardScreenState } from '../ui/contracts/screenContract'
import { useWorkspaceStore } from '../shell/workspaceStore'

/**
 * Bridge per-screen dirty state to workspace tab tracking.
 * Call from a screen component when it manages form/edit state.
 *
 * Example:
 *   const state = ref<StandardScreenState>('READY')
 *   const route = useRoute()
 *   useWorkspaceDirtyBridge(route.name as string, route.path, state)
 *
 * When state changes to 'DIRTY', the workspace tab is marked dirty.
 * When state changes away from 'DIRTY', the tab is marked clean.
 * This enables the workspace tabs component to show a "변경 버리기?" confirm dialog.
 *
 * Note: One feature at a time. Do not force every screen to adopt this at once.
 *       Feature screens that don't manage persistent state can skip this.
 */
export function useWorkspaceDirtyBridge(
  screenId: string,
  path: string,
  state: Ref<StandardScreenState>
): void {
  const workspace = useWorkspaceStore()

  watch(
    () => state.value,
    (newState) => {
      workspace.setDirty(screenId, path, newState === 'DIRTY')
    }
  )
}
