// Main app shell — routes between home / chat / quizzes

// localStorage helpers — keyed per student email (normalized: trim + lowercase)
function normEmail(e) { return (e || "").trim().toLowerCase(); }
function loadStudentData(email) {
  const key = `glenwood_hub_${email}`;
  try {
    const direct = localStorage.getItem(key);
    if (direct) return JSON.parse(direct) || {};
    // One-time migration: if an older entry exists under a non-normalized
    // form of the same email, move it onto the normalized key.
    const prefix = "glenwood_hub_";
    for (let i = 0; i < localStorage.length; i++) {
      const k = localStorage.key(i);
      if (!k || !k.startsWith(prefix) || k === key) continue;
      if (k.slice(prefix.length).trim().toLowerCase() === email) {
        const data = JSON.parse(localStorage.getItem(k)) || {};
        localStorage.setItem(key, JSON.stringify(data));
        localStorage.removeItem(k);
        return data;
      }
    }
    return {};
  } catch { return {}; }
}
function saveStudentData(email, data) {
  try { localStorage.setItem(`glenwood_hub_${email}`, JSON.stringify(data)); } catch {}
}

// Server-side completions: source of truth that survives a localStorage wipe.
// Tolerant of failure — we never block sign-in if the API is unreachable.
async function fetchServerProgress(email) {
  try {
    const res = await fetch(`/api/completions?email=${encodeURIComponent(email)}`);
    if (!res.ok) return {};
    const data = await res.json();
    return data.progress || {};
  } catch { return {}; }
}

function App() {
  const [route, setRoute]             = useState("home");
  const [studentEmail, setStudentEmail] = useState(null);
  const [studentName,  setStudentName]  = useState(null);
  const [quizProgress, setQuizProgress] = useState({});

  // Called by EmailEntryForm on both home and quizzes screens
  function onIdentify({ name, email }) {
    const normalized = normEmail(email);
    const stored = loadStudentData(normalized);
    const localProgress = stored.progress || {};

    setStudentEmail(normalized);
    setStudentName(name);
    setQuizProgress(localProgress);
    saveStudentData(normalized, { ...stored, name, progress: localProgress });

    // Merge in server-side completions (server wins on conflicts; local-only
    // entries are preserved in case a form POST didn't reach the sheet).
    fetchServerProgress(normalized).then(serverProgress => {
      if (!Object.keys(serverProgress).length) return;
      const merged = { ...localProgress, ...serverProgress };
      setQuizProgress(merged);
      saveStudentData(normalized, { ...stored, name, progress: merged });
    });
  }

  // Called by QuizRunner when a quiz finishes
  function onQuizComplete(lessonId, result) {
    const stored = loadStudentData(studentEmail);
    const updatedProgress = { ...(stored.progress || {}), [lessonId]: result };
    setQuizProgress(updatedProgress);
    saveStudentData(studentEmail, { ...stored, progress: updatedProgress });
  }

  function onSignOut() {
    setStudentEmail(null);
    setStudentName(null);
    setQuizProgress({});
    setRoute("home");
  }

  let screen;
  if (route === "home") {
    screen = (
      <HomeScreen
        setRoute={setRoute}
        studentEmail={studentEmail}
        studentName={studentName}
        onIdentify={onIdentify}
        quizProgress={quizProgress}
      />
    );
  } else if (route === "chat") {
    screen = <ChatScreen goBack={() => setRoute("home")} studentName={studentName} />;
  } else if (route === "quizzes") {
    screen = (
      <QuizzesIndex
        setRoute={setRoute}
        studentEmail={studentEmail}
        studentName={studentName}
        onIdentify={onIdentify}
        quizProgress={quizProgress}
      />
    );
  } else if (route.startsWith("quiz:")) {
    const id = route.slice(5);
    screen = (
      <QuizRunner
        quizId={id}
        setRoute={setRoute}
        studentEmail={studentEmail}
        studentName={studentName}
        onComplete={onQuizComplete}
        quizProgress={quizProgress}
      />
    );
  }

  return (
    <div>
      <HubHeader
        route={route.startsWith("quiz:") ? "quizzes" : route}
        setRoute={setRoute}
        studentName={studentName}
        onSignOut={onSignOut}
      />
      {screen}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
