/**
 * Document direction (LTR / RTL).
 *
 * v1 is EN-only but every widget and page must render correctly under
 * RTL — the plumbing is always active. Precedence:
 *
 *   1. `?dir=rtl` query param (dev override — test any route in RTL)
 *   2. localStorage `fabric-dir` (user preference across reloads)
 *   3. `document.documentElement.dir`
 *   4. 'ltr' fallback
 *
 * Locale-bound direction (Arabic / Hebrew / Persian → RTL) is post-v1.
 * Shape supports it — call `setDirection('rtl')` when a locale loads.
 */

export type Direction = 'ltr' | 'rtl'

const STORAGE_KEY = 'fabric-dir'

export function readInitialDirection(): Direction {
  if (typeof window === 'undefined') return 'ltr'

  const query = new URLSearchParams(window.location.search).get('dir')
  if (query === 'rtl' || query === 'ltr') return query

  const stored = window.localStorage.getItem(STORAGE_KEY)
  if (stored === 'rtl' || stored === 'ltr') return stored

  const docDir = window.document.documentElement.dir
  if (docDir === 'rtl' || docDir === 'ltr') return docDir

  return 'ltr'
}

export function applyDirection(dir: Direction) {
  if (typeof window !== 'undefined') {
    window.localStorage.setItem(STORAGE_KEY, dir)
    window.document.documentElement.dir = dir
  }
}
