// research.jsx
// Entry loader hook. Entries are generated by GitHub Action (research.yml)
// and stored in entries.json. The web app is read-only.

function slugify(s) {
  return String(s).toLowerCase().trim()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '');
}

// Load entries from entries.json (generated by GitHub Action)
async function loadEntriesFromJSON() {
  try {
    const res = await fetch('entries.json?ts=' + Date.now());
    if (!res.ok) return {};
    const data = await res.json();
    return data || {};
  } catch (e) {
    console.error('Failed to load entries.json:', e);
    return {};
  }
}

// useWiki hook — loads entries from entries.json (read-only)
function useWiki() {
  const [entries, setEntries] = React.useState({});
  const [loading, setLoading] = React.useState(true);

  // Load entries on mount
  React.useEffect(() => {
    let alive = true;
    (async () => {
      setLoading(true);
      const data = await loadEntriesFromJSON();
      if (alive) {
        setEntries(data.entries || data);
        setLoading(false);
      }
    })();
    return () => { alive = false; };
  }, []);

  // No-op functions (kept for compatibility with app.jsx)
  const pushTerms = React.useCallback(() => {
    console.log('Web app is read-only. Add terms to queue.txt and push to GitHub.');
    return 0;
  }, []);

  const syncQueue = React.useCallback(async () => {
    // Reload entries from JSON
    const data = await loadEntriesFromJSON();
    const entries = data.entries || data;
    setEntries(entries);
    return Object.keys(entries).length;
  }, []);

  const removeEntry = React.useCallback((slug) => {
    console.log('Web app is read-only. Edit entries.json in the GitHub repo to remove entries.');
  }, []);

  const clearLog = React.useCallback(() => {}, []);

  const resetAll = React.useCallback(() => {
    console.log('Web app is read-only. To clear all entries, delete entries.json and push to GitHub.');
  }, []);

  return {
    entries,
    log: [],
    processing: false,
    pushTerms,
    syncQueue,
    removeEntry,
    resetAll,
    clearLog,
    loading,
  };
}

Object.assign(window, { useWiki, slugify, loadEntriesFromJSON });
