// Real API data layer for Lighthouse UI.
// Replaces static mock data with live fetch calls.

const { useState, useEffect, useRef, useCallback } = React;

// ---- Static project list ----
const PROJECTS = [
  { id: "00_Workflow_Obsidian_and_Code", short: "Workflow", color: "230" },
  { id: "08_Personal_Finance",           short: "Finance",  color: "145" },
  { id: "15_Claude_Orchestrator",        short: "Orch",     color: "300" },
  { id: "17_Always_On_Agent",            short: "Agent",    color: "70"  },
];

// ---- Fetch helpers ----
async function fetchJSON(url, opts) {
  const token = window.localStorage.getItem("lighthouse.authToken");
  const headers = new Headers(opts?.headers || {});
  if (token) headers.set("Authorization", `Bearer ${token}`);
  const res = await fetch(url, { ...opts, headers });
  if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
  return res.json();
}

window.LHAuth = {
  getToken: () => window.localStorage.getItem("lighthouse.authToken"),
  setToken: (token) => window.localStorage.setItem("lighthouse.authToken", token.trim()),
  clear: () => window.localStorage.removeItem("lighthouse.authToken"),
};

// ---- API functions ----
function fetchIntake(stage) {
  const qs = stage ? `?stage=${encodeURIComponent(stage)}` : "";
  return fetchJSON(`/api/intakes${qs}`);
}

function fetchTasks(stage) {
  const qs = stage ? `?stage=${encodeURIComponent(stage)}` : "";
  return fetchJSON(`/api/tasks${qs}`);
}

function fetchSessions() {
  return fetchJSON("/api/db/sessions");
}

function fetchTmuxSessions() {
  return fetchJSON("/api/sessions");
}

async function fetchQueue(sessionId) {
  return fetchJSON(`/api/sessions/${encodeURIComponent(sessionId)}/queue`);
}

async function fetchAllQueue() {
  const sessions = await fetchSessions();
  const queues = await Promise.all(
    sessions
      .filter(s => s.tmux_name)
      .map(s => fetchQueue(s.id).catch(() => []))
  );
  return queues.flat();
}

function postIntake({ project, raw_text }) {
  return fetchJSON("/api/intakes", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ project, raw_text }),
  });
}

function patchIntake(id, fields) {
  return fetchJSON(`/api/intakes/${encodeURIComponent(id)}`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(fields),
  });
}

function deleteIntake(id) {
  return fetchJSON(`/api/intakes/${encodeURIComponent(id)}`, { method: "DELETE" });
}

function postTask(fields) {
  return fetchJSON("/api/tasks", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(fields),
  });
}

function patchTask(id, fields) {
  return fetchJSON(`/api/tasks/${encodeURIComponent(id)}`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(fields),
  });
}

function patchSession(id, fields) {
  return fetchJSON(`/api/sessions/${encodeURIComponent(id)}`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(fields),
  });
}

function spawnSession(fields) {
  return fetchJSON("/api/sessions/spawn", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(fields),
  });
}

function triggerNextGo(project) {
  const qs = project ? `?project=${encodeURIComponent(project)}` : "";
  return fetchJSON(`/api/dispatch/trigger${qs}`, { method: "POST" });
}

function postQueueItem(sessionId, { text, task_id }) {
  return fetchJSON(`/api/sessions/${encodeURIComponent(sessionId)}/queue`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ text, task_id }),
  });
}

function patchQueueItem(qid, fields) {
  return fetchJSON(`/api/queue/${encodeURIComponent(qid)}`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(fields),
  });
}

function deleteQueueItem(qid) {
  return fetchJSON(`/api/queue/${encodeURIComponent(qid)}`, { method: "DELETE" });
}

// ---- usePolling hook ----
function usePolling(fetchFn, intervalMs = 5000) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const intervalRef = useRef(null);
  const fetchFnRef = useRef(fetchFn);
  fetchFnRef.current = fetchFn;

  const refresh = useCallback(async () => {
    try {
      const result = await fetchFnRef.current();
      setData(result);
    } catch (err) {
      console.warn("usePolling fetch error:", err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    refresh();
    intervalRef.current = setInterval(refresh, intervalMs);
    return () => clearInterval(intervalRef.current);
  }, [refresh, intervalMs]);

  return { data, loading, refresh };
}

// ---- Export to window for cross-file access ----
window.LHData = {
  PROJECTS,
  fetchIntake,
  fetchTasks,
  fetchSessions,
  fetchTmuxSessions,
  fetchQueue,
  fetchAllQueue,
  postIntake,
  patchIntake,
  deleteIntake,
  postTask,
  patchTask,
  patchSession,
  spawnSession,
  triggerNextGo,
  postQueueItem,
  patchQueueItem,
  deleteQueueItem,
  usePolling,
};
