"use client";

import { useEffect, useRef, useState } from "react";

export default function ScormPlayer() {
  const [content, setContent] = useState<{ id: number; title: string; launchPath: string; format: string } | null>(null);
  const [message, setMessage] = useState("Preparing secure SCORM session…");
  const started = useRef(Date.now());
  const values = useRef<Record<string, string>>({});

  useEffect(() => {
    const id = Number(new URLSearchParams(window.location.search).get("id"));
    fetch("/api/content").then((response) => response.json()).then((data) => {
      const item = data.items?.find((candidate: { id: number }) => candidate.id === id);
      if (!item) throw new Error("Package not found");
      setContent({ ...item, launchPath: item.launchPath ?? "" });
      setMessage("Session active — progress saves automatically");
    }).catch(() => setMessage("This SCORM package could not be opened."));

    const save = (status = "incomplete") => fetch("/api/content", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        action: "runtime", id,
        status,
        score: values.current["cmi.core.score.raw"] ?? values.current["cmi.score.raw"] ?? null,
        seconds: Math.round((Date.now() - started.current) / 1000),
      }),
    });
    const setValue = (key: string, value: string) => {
      values.current[key] = String(value);
      const completion = values.current["cmi.core.lesson_status"] ?? values.current["cmi.completion_status"] ?? "incomplete";
      save(completion === "complete" ? "completed" : completion).catch(() => undefined);
      return "true";
    };
    const api12 = { LMSInitialize: () => "true", LMSFinish: () => { save("completed"); return "true"; }, LMSGetValue: (key: string) => values.current[key] ?? "", LMSSetValue: setValue, LMSCommit: () => { save(); return "true"; }, LMSGetLastError: () => "0", LMSGetErrorString: () => "", LMSGetDiagnostic: () => "" };
    const api2004 = { Initialize: () => "true", Terminate: () => { save("completed"); return "true"; }, GetValue: (key: string) => values.current[key] ?? "", SetValue: setValue, Commit: () => { save(); return "true"; }, GetLastError: () => "0", GetErrorString: () => "", GetDiagnostic: () => "" };
    (window as typeof window & { API?: typeof api12; API_1484_11?: typeof api2004 }).API = api12;
    (window as typeof window & { API?: typeof api12; API_1484_11?: typeof api2004 }).API_1484_11 = api2004;
    const interval = window.setInterval(() => save().catch(() => undefined), 30000);
    const finish = () => { save(); };
    window.addEventListener("beforeunload", finish);
    return () => { window.clearInterval(interval); window.removeEventListener("beforeunload", finish); };
  }, []);

  return <main className="scorm-shell">
    <header><img src="/connectpoint-logo.png" alt="ConnectPoint" /><div><strong>{content?.title ?? "SCORM learning activity"}</strong><small>{message}</small></div><a href="/">Exit activity</a></header>
    {content?.launchPath ? <iframe title={content.title} src={`/api/scorm/${content.id}/${content.launchPath}`} allow="fullscreen; autoplay" /> : <div className="scorm-loading">{message}</div>}
  </main>;
}
