// data.jsx — loads content from content.json (or draft localStorage)
//
// Architecture: all editable content lives in content.json. This file fetches
// it (synchronously, so subsequent Babel scripts can rely on window.WORKS etc
// being populated) and exposes globals.
//
// If the URL has ?draft=1 we read content from localStorage instead — that's
// how editor.html's "Preview" button shows draft state without publishing.

(function loadContent() {
  // Tone palette stays here — it's design-system level, not editable content
  const TONES = {
    fog:   "linear-gradient(170deg, #d8cdb6 0%, #aea089 60%, #756855 100%)",
    amber: "linear-gradient(170deg, #d9b388 0%, #a87750 55%, #5a3a26 100%)",
    ink:   "linear-gradient(170deg, #4a4032 0%, #2c241b 60%, #16110b 100%)",
    rose:  "linear-gradient(170deg, #d8a89a 0%, #a06b5e 55%, #4d2a25 100%)",
    sage:  "linear-gradient(170deg, #c3c6a8 0%, #8c9272 55%, #4b4f38 100%)",
    paper: "linear-gradient(170deg, #efe6d2 0%, #d4c4a5 55%, #9a8a6c 100%)",
    cyan:  "linear-gradient(170deg, #b8c8c7 0%, #7a8f8e 55%, #3d4e4d 100%)",
    dusk:  "linear-gradient(180deg, #d6a684 0%, #8a5a52 50%, #2c1d1f 100%)",
  };

  // Try draft mode first
  const useDraft = new URLSearchParams(location.search).get("draft") === "1";
  let content = null;

  if (useDraft) {
    try {
      const raw = localStorage.getItem("joline_draft_content");
      if (raw) content = JSON.parse(raw);
    } catch (e) {
      console.warn("Failed to load draft:", e);
    }
  }

  if (!content) {
    // Synchronous XHR — content.json must exist beside index.html. This blocks
    // Babel's next script until the JSON is ready, which is what we want so
    // views.jsx / app.jsx can read window.WORKS immediately.
    try {
      const xhr = new XMLHttpRequest();
      xhr.open("GET", "content.json?v=" + Date.now(), false);
      xhr.send(null);
      if (xhr.status >= 200 && xhr.status < 300) {
        content = JSON.parse(xhr.responseText);
      } else {
        throw new Error("content.json HTTP " + xhr.status);
      }
    } catch (e) {
      console.error("Failed to load content.json:", e);
      content = { strings: {}, home_verses: [], about: {}, moods: [], works: [] };
    }
  }

  // Flatten for legacy access
  const STRINGS = Object.assign({}, content.strings, { about: content.about });

  Object.assign(window, {
    TONES,
    MOODS: content.moods || [],
    WORKS: content.works || [],
    STRINGS,
    HOME_VERSES: content.home_verses || [],
    PORTRAIT_SRC: content.about && content.about.portrait_src,
    CONTENT: content, // raw, for the editor + diagnostics
    CONTENT_DRAFT: useDraft,
  });
})();
