import type { Tab } from './types'
import { PREVIEW_LINE_KEY, LEGACY_READ_KEY, VIEW_KEY } from './constants'
import type { ViewMode } from './appearance'
import { randomId } from './randomId'

export function clamp(n: number, min: number, max: number): number {
  return Math.min(max, Math.max(min, n))
}

export function normalizePathKey(p: string): string {
  return p.replace(/\\/g, '/').toLowerCase()
}

export function newTab(): Tab {
  const id = randomId()
  return { id, filePath: null, content: '', savedContent: '' }
}

export function tabLabel(t: Tab): string {
  if (t.filePath) {
    const parts = t.filePath.split(/[/\\]/)
    return parts[parts.length - 1] || t.filePath
  }
  return '未命名'
}

export function isDirty(t: Tab): boolean {
  return t.content !== t.savedContent
}

export function loadViewMode(): ViewMode {
  const v = localStorage.getItem(VIEW_KEY) as ViewMode | null
  if (v === 'edit' || v === 'read' || v === 'hybrid') return v
  if (localStorage.getItem(LEGACY_READ_KEY) === '1') return 'read'
  if (localStorage.getItem(LEGACY_READ_KEY) === '0') return 'edit'
  return 'read'
}

export function viewModeLabel(m: ViewMode): string {
  if (m === 'edit') return '编辑'
  if (m === 'read') return '阅读'
  return '分栏'
}

export function loadPreviewLineHeight(): string {
  const raw = localStorage.getItem(PREVIEW_LINE_KEY)
  if (!raw) return '1.5'
  const n = Number.parseFloat(raw)
  if (!Number.isFinite(n)) return '1.5'
  return String(Math.min(3, Math.max(1, n)))
}