interface SCORM12API {
  LMSInitialize: (s: string) => string
  LMSGetValue: (key: string) => string
  LMSSetValue: (key: string, value: string) => string
  LMSCommit: (s: string) => string
  LMSFinish: (s: string) => string
}

declare global {
  interface Window {
    API?: SCORM12API
  }
}

let sessionStartTime: number | null = null
let scormFinished = false

// ─── API ──────────────────────────────────────────────────────────────────────

function getAPI(): SCORM12API | null {
  if (window.API) return window.API
  if (window.parent?.API) return window.parent.API
  return null
}

function isConnected(): boolean {
  return getAPI() !== null
}

// ─── Get / Set genérico con fallback a sessionStorage ────────────────────────

export function getScormData(key: string): string {
  const api = getAPI()
  if (api) return api.LMSGetValue(key) ?? ''
  return sessionStorage.getItem(key) ?? ''
}

export function setScormData(key: string, value: string): boolean {
  const api = getAPI()
  if (api) {
    const ok = api.LMSSetValue(key, value)
    api.LMSCommit('')
    return ok === 'true'
  }
  sessionStorage.setItem(key, value)
  return true
}

// ─── Inicialización ───────────────────────────────────────────────────────────

export function initSCORM(): void {
  const api = getAPI()
  if (api) {
    api.LMSInitialize('')
    const status = api.LMSGetValue('cmi.core.lesson_status')
    if (status === 'not attempted') {
      api.LMSSetValue('cmi.core.lesson_status', 'incomplete')
      api.LMSCommit('')
    }
  }
  sessionStartTime = Date.now()
}

// ─── Lesson status ────────────────────────────────────────────────────────────

export function getLessonStatus(): string {
  return getScormData('cmi.core.lesson_status')
}

export function setLessonStatus(status: 'passed' | 'failed' | 'completed' | 'incomplete'): boolean {
  return setScormData('cmi.core.lesson_status', status)
}

// ─── Lesson location ──────────────────────────────────────────────────────────

export function getLessonLocation(): string {
  return getScormData('cmi.core.lesson_location')
}

export function setLessonLocation(location: string): boolean {
  return setScormData('cmi.core.lesson_location', location)
}

// ─── Score ────────────────────────────────────────────────────────────────────

export function getScore(): number | null {
  const val = getScormData('cmi.core.score.raw')
  return val !== '' ? Number(val) : null
}

export function setScore(score: number, maxScore = 100, minScore = 0): void {
  setScormData('cmi.core.score.raw', String(score))
  setScormData('cmi.core.score.max', String(maxScore))
  setScormData('cmi.core.score.min', String(minScore))
}

// ─── Suspend data ─────────────────────────────────────────────────────────────

export function getSuspendData<T = unknown>(): T | null {
  const val = getScormData('cmi.suspend_data')
  if (!val) return null
  try {
    return JSON.parse(val) as T
  } catch {
    return null
  }
}

export function setSuspendData(data: unknown): boolean {
  return setScormData('cmi.suspend_data', JSON.stringify(data))
}

// ─── Student name ─────────────────────────────────────────────────────────────

export function getStudentName(): string {
  return getScormData('cmi.core.student_name')
}

// ─── Finish con session_time ──────────────────────────────────────────────────

export function finishSCORM(): void {
  if (scormFinished) return
  const api = getAPI()
  if (!api) return

  if (sessionStartTime) {
    const elapsed = Math.floor((Date.now() - sessionStartTime) / 1000)
    const hh = String(Math.floor(elapsed / 3600)).padStart(2, '0')
    const mm = String(Math.floor((elapsed % 3600) / 60)).padStart(2, '0')
    const ss = String(elapsed % 60).padStart(2, '0')
    api.LMSSetValue('cmi.core.session_time', `${hh}:${mm}:${ss}`)
  }

  api.LMSCommit('')
  api.LMSFinish('')
  scormFinished = true
}

// ─── Helper: completar lección ────────────────────────────────────────────────

export function completeLesson(): void {
  setLessonStatus('completed')
}

export { isConnected }
