import { ref } from 'vue'
import { setNativeFitAddon, forEachNative, getNative } from './termNativeStore'

const K_FONT = 'nexus_term_fontSize'
const K_SCROLL = 'nexus_term_scrollback'

export const scrollbackOptions = [
  { title: '1 千行', value: 1000 },
  { title: '5 千行', value: 5000 },
  { title: '1 万行', value: 10000 },
  { title: '5 万行', value: 50000 },
] as const

export function useTerminalSettings() {
  const fontSize = ref(parseInt(localStorage.getItem(K_FONT) || '14', 10))
  const scrollback = ref(parseInt(localStorage.getItem(K_SCROLL) || '1000', 10))

  function changeFontSize(delta: number) {
    fontSize.value = Math.max(10, Math.min(24, fontSize.value + delta))
    localStorage.setItem(K_FONT, String(fontSize.value))
    forEachNative((_id, native) => {
      if (native.term) {
        native.term.options.fontSize = fontSize.value
        try {
          native.fitAddon?.fit()
        } catch {
          /* container size 0 */
        }
      }
    })
  }

  function changeScrollback(val: number) {
    scrollback.value = val
    localStorage.setItem(K_SCROLL, String(val))
    forEachNative((_id, native) => {
      if (native.term) native.term.options.scrollback = val
    })
  }

  function applyFontToSession(sessionId: string) {
    const term = getNative(sessionId)?.term
    if (term) term.options.fontSize = fontSize.value
  }

  return {
    fontSize,
    scrollback,
    scrollbackOptions,
    changeFontSize,
    changeScrollback,
    applyFontToSession,
  }
}
