const STORAGE_KEY = 'x-financial.documents.viewed'
const SCOPE_STORAGE_KEY = 'x-financial.documents.scope'
export const DOCUMENT_VIEWED_KEYS_CHANGE_EVENT = 'x-financial.documents.viewed-change'

function getStorage() {
  return typeof window === 'undefined' ? null : window.localStorage
}

export function resolveDocumentNewKey(row) {
  const source = String(row?.source || 'document').trim()
  const id = String(row?.claimId || row?.documentNo || row?.documentKey || row?.id || '').trim()
  return id ? `${source}:${id}` : ''
}

export function readViewedDocumentKeys(storage = getStorage()) {
  if (!storage) {
    return new Set()
  }

  try {
    const parsed = JSON.parse(storage.getItem(STORAGE_KEY) || '[]')
    return new Set(Array.isArray(parsed) ? parsed.map((item) => String(item || '').trim()).filter(Boolean) : [])
  } catch {
    return new Set()
  }
}

export function writeViewedDocumentKeys(keys, storage = getStorage()) {
  if (!storage) {
    return
  }

  storage.setItem(STORAGE_KEY, JSON.stringify(Array.from(keys).filter(Boolean)))

  if (typeof window !== 'undefined' && storage === window.localStorage) {
    window.dispatchEvent(new CustomEvent(DOCUMENT_VIEWED_KEYS_CHANGE_EVENT))
  }
}

export function readDocumentScope(fallback, allowedScopes = [], storage = getStorage()) {
  if (!storage) {
    return fallback
  }

  const storedScope = String(storage.getItem(SCOPE_STORAGE_KEY) || '').trim()
  return allowedScopes.includes(storedScope) ? storedScope : fallback
}

export function writeDocumentScope(scope, allowedScopes = [], storage = getStorage()) {
  if (!storage || !allowedScopes.includes(scope)) {
    return
  }

  storage.setItem(SCOPE_STORAGE_KEY, scope)
}

export function isNewDocument(row, viewedKeys) {
  const key = resolveDocumentNewKey(row)
  return Boolean(key) && !viewedKeys.has(key)
}

export function countNewDocuments(rows, viewedKeys) {
  return rows.filter((row) => isNewDocument(row, viewedKeys)).length
}

export function markDocumentViewed(row, viewedKeys, storage = getStorage()) {
  const key = resolveDocumentNewKey(row)
  if (!key) {
    return viewedKeys
  }

  const nextKeys = new Set(viewedKeys)
  nextKeys.add(key)
  writeViewedDocumentKeys(nextKeys, storage)
  return nextKeys
}
