/**
 * Storage-Helfer für ComplianceCheckTab.
 *
 * Extrahiert aus ComplianceCheckTab.tsx (P11-Tech-Debt-Sprint) damit
 * die zentrale UI unter der 500-LOC-Hard-Cap bleibt.
 */

import { DOCUMENT_TYPES, type DocTypeId } from './_document_types'

export const STORAGE_KEY_STATE = 'compliance-check-state'
export const STORAGE_KEY_RESULTS = 'compliance-check-results'
export const STORAGE_KEY_HISTORY = 'compliance-check-history'
export const STORAGE_KEY_CHECK_ID = 'compliance-check-active-id'

export interface DocState {
  url: string
  text: string
  loading: boolean
  error: string | null
}

export type DocsState = Record<DocTypeId, DocState>

export interface HistoryEntry {
  date: string
  docCount: number
  findings: number
  resultKey: string
  checkId?: string
}

export function emptyDocState(): DocState {
  return { url: '', text: '', loading: false, error: null }
}

export function initState(): DocsState {
  if (typeof window === 'undefined') {
    return Object.fromEntries(
      DOCUMENT_TYPES.map(d => [d.id, emptyDocState()]),
    ) as DocsState
  }
  try {
    const saved = localStorage.getItem(STORAGE_KEY_STATE)
    if (saved) {
      const parsed = JSON.parse(saved) as Record<
        string, { url?: string; text?: string }
      >
      return Object.fromEntries(
        DOCUMENT_TYPES.map(d => [d.id, {
          url: parsed[d.id]?.url || '',
          text: parsed[d.id]?.text || '',
          loading: false,
          error: null,
        }]),
      ) as DocsState
    }
  } catch { /* ignore */ }
  return Object.fromEntries(
    DOCUMENT_TYPES.map(d => [d.id, emptyDocState()]),
  ) as DocsState
}

export function readResultsFromStorage(): unknown | null {
  if (typeof window === 'undefined') return null
  try {
    const s = localStorage.getItem(STORAGE_KEY_RESULTS)
    return s ? JSON.parse(s) : null
  } catch { return null }
}

export function readHistoryFromStorage(): HistoryEntry[] {
  if (typeof window === 'undefined') return []
  try {
    return JSON.parse(localStorage.getItem(STORAGE_KEY_HISTORY) || '[]')
  } catch { return [] }
}

export function readActiveCheckId(): string {
  if (typeof window === 'undefined') return ''
  return localStorage.getItem(STORAGE_KEY_CHECK_ID) || ''
}

export function countWords(text: string): number {
  if (!text.trim()) return 0
  return text.trim().split(/\s+/).length
}
