const DAILY_LIMIT = 3
const STORAGE_KEY = "writing-check-usage"

interface UsageRecord {
  date: string
  count: number
}

export function canUseWritingCheck(): boolean {
  const record = getUsageRecord()
  const today = getToday()
  if (record.date !== today) return true
  return record.count < DAILY_LIMIT
}

export function recordWritingCheckUsage(): void {
  const today = getToday()
  const record = getUsageRecord()
  if (record.date !== today) {
    setUsageRecord({ date: today, count: 1 })
  } else {
    setUsageRecord({ date: today, count: record.count + 1 })
  }
}

export function getRemainingChecks(): number {
  const record = getUsageRecord()
  const today = getToday()
  if (record.date !== today) return DAILY_LIMIT
  return Math.max(0, DAILY_LIMIT - record.count)
}

function getToday(): string {
  return new Date().toISOString().split("T")[0]
}

function getUsageRecord(): UsageRecord {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    if (!raw) return { date: "", count: 0 }
    return JSON.parse(raw) as UsageRecord
  } catch {
    return { date: "", count: 0 }
  }
}

function setUsageRecord(record: UsageRecord): void {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(record))
}
