// router.jsx — Hash-based router + global auth state for uri-jib.com

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

// ─── Hash router ─────────────────────────────────────────
function useRoute() {
  const [hash, setHash] = useState(location.hash.slice(1) || '/');
  useEffect(() => {
    const h = () => setHash(location.hash.slice(1) || '/');
    window.addEventListener('hashchange', h);
    return () => window.removeEventListener('hashchange', h);
  }, []);
  return hash;
}

function navigate(path) {
  if (location.hash.slice(1) === path) return;
  location.hash = path;
}

function parseRoute(hash) {
  // /app/detail/eunma → {base:'/app/detail', id:'eunma'}
  const m = hash.match(/^\/app\/detail\/(.+)$/);
  if (m) return { base: '/app/detail', id: m[1] };
  const o = hash.match(/^\/onboarding\/(\d+)$/);
  if (o) return { base: '/onboarding', step: parseInt(o[1], 10) };
  return { base: hash, id: null };
}

// ─── Auth (localStorage-backed) ──────────────────────────
function useAuth() {
  const [user, setUser] = useState(() => window.UJTrack.getUser());
  useEffect(() => {
    const h = () => setUser(window.UJTrack.getUser());
    window.addEventListener('urijib:auth', h);
    return () => window.removeEventListener('urijib:auth', h);
  }, []);
  const login = useCallback((u) => {
    window.UJTrack.setUser(u);
    window.UJTrack.track('login_success', { provider: u.provider, method: u.method });
    window.dispatchEvent(new CustomEvent('urijib:auth'));
  }, []);
  const logout = useCallback(() => {
    window.UJTrack.track('logout', {});
    window.UJTrack.setUser(null);
    window.dispatchEvent(new CustomEvent('urijib:auth'));
  }, []);
  return { user, login, logout };
}

// ─── Watchlist (per-user, localStorage) ──────────────────
function useWatchlist() {
  const KEY = 'urijib_watchlist';
  const [ids, setIds] = useState(() => {
    try { return JSON.parse(localStorage.getItem(KEY) || '[]'); } catch (e) { return []; }
  });
  useEffect(() => {
    localStorage.setItem(KEY, JSON.stringify(ids));
  }, [ids]);
  const toggle = useCallback((id) => {
    setIds((prev) => {
      const has = prev.includes(id);
      window.UJTrack.track(has ? 'watchlist_remove' : 'watchlist_add', { apt_id: id });
      return has ? prev.filter(x => x !== id) : [...prev, id];
    });
  }, []);
  const has = useCallback((id) => ids.includes(id), [ids]);
  return { ids, toggle, has };
}

// ─── Toast ───────────────────────────────────────────────
function useToast() {
  const [msg, setMsg] = useState(null);
  const show = useCallback((text, kind = 'info', ms = 2200) => {
    setMsg({ text, kind, id: Date.now() });
    setTimeout(() => setMsg(null), ms);
  }, []);
  const node = msg && (
    <div style={{
      position: 'fixed', bottom: 24, left: '50%', transform: 'translateX(-50%)',
      background: T.cardHi, border: '1px solid ' + T.line, color: T.fg,
      padding: '10px 18px', borderRadius: 4, fontSize: 13,
      fontFamily: T.font, zIndex: 9999,
      boxShadow: '0 12px 32px rgba(0,0,0,0.5)',
      animation: 'ujfadeup .25s ease',
    }}>
      <span style={{
        display: 'inline-block', width: 6, height: 6, borderRadius: 3,
        marginRight: 8, verticalAlign: 'middle',
        background: msg.kind === 'success' ? T.up : msg.kind === 'error' ? T.down : T.hot,
      }} />
      {msg.text}
    </div>
  );
  return { show, node };
}

Object.assign(window, { useRoute, navigate, parseRoute, useAuth, useWatchlist, useToast });
