// data.jsx — auth-aware API store
(function () {
  window.SEED = { TODAY: new Date() };

  // ---- Helpers ----
  window.fmt = (n, decimals) => {
    const neg = n < 0; const v = Math.abs(n);
    const s = v.toLocaleString('en-US', {
      minimumFractionDigits: decimals ? 2 : 0,
      maximumFractionDigits: decimals ? 2 : 0,
    });
    return (neg ? '−' : '') + s;
  };

  window.dayKey = (iso) => iso.slice(0, 10);

  window.relDay = (iso) => {
    const k = iso.slice(0, 10);
    const today = window.SEED.TODAY;
    const t = today.toISOString().slice(0, 10);
    const y = new Date(today); y.setDate(today.getDate() - 1);
    if (k === t) return 'Today';
    if (k === y.toISOString().slice(0, 10)) return 'Yesterday';
    return new Date(iso).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
  };

  window.shortDate = (iso) =>
    new Date(iso).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' });

  window._allCats = [];
  window.catById = (id) =>
    window._allCats.find((c) => c.id === id) ||
    { id, label: id, icon: 'tag', color: '#94A3B8' };

  // ---- Auth token helper ----
  function getToken() { try { return localStorage.getItem('finflow_token'); } catch { return null; } }

  // ---- Authenticated fetch ----
  async function apiFetch(path, opts = {}) {
    const token = getToken();
    const res = await fetch(path, {
      headers: {
        'Content-Type': 'application/json',
        ...(token ? { Authorization: 'Bearer ' + token } : {}),
        ...opts.headers,
      },
      ...opts,
    });
    if (res.status === 401) {
      try { localStorage.removeItem('finflow_token'); } catch {}
      window.location.reload();
      return;
    }
    const text = await res.text();
    if (!res.ok) throw new Error(text || res.statusText);
    return text ? JSON.parse(text) : null;
  }

  // ---- useAuth hook ----
  window.useAuth = function useAuth() {
    const [user, setUser] = React.useState(null);
    const [authLoading, setAuthLoading] = React.useState(true);

    React.useEffect(() => {
      const token = getToken();
      if (!token) { setAuthLoading(false); return; }
      fetch('/api/auth/me', { headers: { Authorization: 'Bearer ' + token } })
        .then(r => r.ok ? r.json() : null)
        .then(data => { if (data) setUser(data.user); else { try { localStorage.removeItem('finflow_token'); } catch {} } })
        .catch(() => {})
        .finally(() => setAuthLoading(false));
    }, []);

    const login = (token, userData) => {
      try { localStorage.setItem('finflow_token', token); } catch {}
      window.location.reload();
    };

    const logout = () => {
      const token = getToken();
      if (token) fetch('/api/auth/logout', { method: 'POST', headers: { Authorization: 'Bearer ' + token } }).catch(() => {});
      try { localStorage.removeItem('finflow_token'); } catch {}
      window.location.reload();
    };

    return { user, authLoading, login, logout };
  };

  // ---- useStore hook ----
  window.useStore = function useStore() {
    const [txns, setTxns]               = React.useState([]);
    const [credits, setCredits]         = React.useState([]);
    const [incomeCats, setIncomeCats]   = React.useState([]);
    const [expenseCats, setExpenseCats] = React.useState([]);
    const [loading, setLoading]         = React.useState(true);
    const [error, setError]             = React.useState(null);

    React.useEffect(() => {
      if (!getToken()) { setLoading(false); return; }
      Promise.all([
        apiFetch('/api/transactions'),
        apiFetch('/api/credits'),
        apiFetch('/api/categories'),
      ])
        .then(([txData, crData, catData]) => {
          setTxns(txData || []);
          setCredits(crData || []);
          const income  = (catData || []).filter((c) => c.type === 'income');
          const expense = (catData || []).filter((c) => c.type === 'expense');
          setIncomeCats(income);
          setExpenseCats(expense);
          window._allCats = catData || [];
          setLoading(false);
        })
        .catch((err) => { setError(err.message); setLoading(false); });
    }, []);

    const addTxn = async (t) => {
      const created = await apiFetch('/api/transactions', { method: 'POST', body: JSON.stringify(t) });
      setTxns((prev) => [created, ...prev]);
      return created;
    };

    const settleCredit = async (id) => {
      const updated = await apiFetch('/api/credits/' + id, { method: 'PUT', body: JSON.stringify({ status: 'settled' }) });
      setCredits((prev) => prev.map((c) => c.id === updated.id ? updated : c));
    };

    const addCategory = async (cat) => {
      const created = await apiFetch('/api/categories', { method: 'POST', body: JSON.stringify(cat) });
      window._allCats = [...window._allCats, created];
      if (created.type === 'income') setIncomeCats((p) => [...p, created]);
      else setExpenseCats((p) => [...p, created]);
      return created;
    };

    return { txns, addTxn, credits, settleCredit, incomeCats, expenseCats, addCategory, loading, error };
  };
})();
