import { createContext, useContext, useCallback, useState, ReactNode } from 'react'

// Forex tickers on Yahoo Finance require the =X suffix; migrate stale plain versions
const FOREX_MIGRATIONS: Record<string, string> = { 'EURUSD': 'EURUSD=X', 'GBPUSD': 'GBPUSD=X', 'USDJPY': 'USDJPY=X', 'USDCHF': 'USDCHF=X' }

function migrateInstrumentId(id: string): string {
  return FOREX_MIGRATIONS[id] ?? id
}

// Apply once at module load so every localStorage read is already corrected
;(function migrateLastInstrument() {
  const stored = localStorage.getItem('last_instrument')
  if (stored && FOREX_MIGRATIONS[stored]) {
    localStorage.setItem('last_instrument', FOREX_MIGRATIONS[stored])
  }
})()

interface TabsCtx {
  kept:            ReadonlySet<string>
  keepRoute:       (r: string) => void
  forgetRoute:     (r: string) => void
  instrumentIds:   string[]
  openInstrument:  (id: string) => void
  closeInstrument: (id: string) => void
}

const Ctx = createContext<TabsCtx>({
  kept: new Set(),
  keepRoute:       () => {},
  forgetRoute:     () => {},
  instrumentIds:   [],
  openInstrument:  () => {},
  closeInstrument: () => {},
})

export function TabsProvider({ children }: { children: ReactNode }) {
  const [kept, setKept] = useState<Set<string>>(new Set())
  const [instrumentIds, setInstrumentIds] = useState<string[]>([])

  const keepRoute = useCallback((r: string) =>
    setKept(p => p.has(r) ? p : new Set([...p, r])), [])

  const forgetRoute = useCallback((r: string) =>
    setKept(p => { const n = new Set(p); n.delete(r); return n }), [])

  const openInstrument = useCallback((id: string) => {
    const safe = migrateInstrumentId(id.toUpperCase())
    localStorage.setItem('last_instrument', safe)
    setInstrumentIds(p => p.includes(safe) ? p : [...p, safe])
  }, [])

  const closeInstrument = useCallback((id: string) =>
    setInstrumentIds(p => p.filter(x => x !== id)), [])

  return (
    <Ctx.Provider value={{ kept, keepRoute, forgetRoute, instrumentIds, openInstrument, closeInstrument }}>
      {children}
    </Ctx.Provider>
  )
}

export const useTabs = () => useContext(Ctx)
