const STORAGE_KEY = 'product-workspace-hints'

interface PerProductHint {
  lastActivePbiId?: string | null
  lastActiveStoryId?: string | null
  lastActiveTaskId?: string | null
}

export interface WorkspaceHints {
  lastActiveProductId: string | null
  perProduct: Record<string, PerProductHint>
}

const EMPTY_HINTS: WorkspaceHints = {
  lastActiveProductId: null,
  perProduct: {},
}

function safeStorage(): Storage | null {
  if (typeof globalThis === 'undefined') return null
  try {
    const ls = (globalThis as { localStorage?: Storage }).localStorage
    return ls ?? null
  } catch {
    return null
  }
}

export function readHints(): WorkspaceHints {
  const storage = safeStorage()
  if (!storage) return { ...EMPTY_HINTS, perProduct: {} }
  try {
    const raw = storage.getItem(STORAGE_KEY)
    if (!raw) return { ...EMPTY_HINTS, perProduct: {} }
    const parsed = JSON.parse(raw) as Partial<WorkspaceHints> | null
    if (!parsed || typeof parsed !== 'object') {
      return { ...EMPTY_HINTS, perProduct: {} }
    }
    return {
      lastActiveProductId: parsed.lastActiveProductId ?? null,
      perProduct:
        parsed.perProduct && typeof parsed.perProduct === 'object'
          ? parsed.perProduct
          : {},
    }
  } catch {
    return { ...EMPTY_HINTS, perProduct: {} }
  }
}

function writeHints(hints: WorkspaceHints): void {
  const storage = safeStorage()
  if (!storage) return
  try {
    storage.setItem(STORAGE_KEY, JSON.stringify(hints))
  } catch {
    // ignore quota or serialization errors
  }
}

export function writeProductHint(productId: string | null): void {
  const hints = readHints()
  hints.lastActiveProductId = productId
  writeHints(hints)
}

function ensurePerProduct(hints: WorkspaceHints, productId: string): PerProductHint {
  if (!hints.perProduct[productId]) {
    hints.perProduct[productId] = {}
  }
  return hints.perProduct[productId]
}

export function writePbiHint(productId: string, pbiId: string | null): void {
  const hints = readHints()
  const entry = ensurePerProduct(hints, productId)
  entry.lastActivePbiId = pbiId
  if (pbiId === null) {
    entry.lastActiveStoryId = null
    entry.lastActiveTaskId = null
  }
  writeHints(hints)
}

export function writeStoryHint(productId: string, storyId: string | null): void {
  const hints = readHints()
  const entry = ensurePerProduct(hints, productId)
  entry.lastActiveStoryId = storyId
  if (storyId === null) {
    entry.lastActiveTaskId = null
  }
  writeHints(hints)
}

export function writeTaskHint(productId: string, taskId: string | null): void {
  const hints = readHints()
  const entry = ensurePerProduct(hints, productId)
  entry.lastActiveTaskId = taskId
  writeHints(hints)
}

export function clearHints(): void {
  const storage = safeStorage()
  if (!storage) return
  try {
    storage.removeItem(STORAGE_KEY)
  } catch {
    // ignore
  }
}
