"use client"

import { useEffect, useState } from "react"

const STORAGE_KEY = "ui:selectedCompanyId"

export function usePersistentCompanyFilter(initial: string = "all") {
  const [companyId, setCompanyId] = useState<string>(initial)

  useEffect(() => {
    try {
      const saved = window.localStorage.getItem(STORAGE_KEY)
      if (saved) setCompanyId(saved)
    } catch {
      // ignore
    }
  }, [])

  const update = (value: string) => {
    setCompanyId(value)
    try {
      window.localStorage.setItem(STORAGE_KEY, value)
    } catch {
      // ignore
    }
  }

  return [companyId, update] as const
}
