// Main app shell — handles routing between Library, Detail, Stats, plus modal

// ── Admin auth ───────────────────────────────────────────────────────────────
const _adminAuth = {
  getToken: () => sessionStorage.getItem('admin_token'),
  setToken: (t) => sessionStorage.setItem('admin_token', t),
  clearToken: () => sessionStorage.removeItem('admin_token'),
  _resolve: null,
};

// Returns a Promise<token>. If token already in sessionStorage, resolves immediately.
// Otherwise opens the password modal and resolves when the user submits.
function adminRequestToken(errorMsg) {
  const existing = _adminAuth.getToken();
  if (existing && !errorMsg) return Promise.resolve(existing);
  return new Promise((resolve) => {
    _adminAuth._resolve = resolve;
    window.dispatchEvent(new CustomEvent('__admin_auth_request', { detail: { errorMsg: errorMsg || null } }));
  });
}

// Drop-in replacement for fetch() that injects the admin token and retries once on 401.
// Assigned to window so components loaded before app.jsx can call it at runtime.
window.authedFetch = async function authedFetch(url, opts = {}) {
  let token = await adminRequestToken();
  const makeOpts = (t) => ({
    ...opts,
    headers: { ...(opts.headers || {}), Authorization: `Bearer ${t}` },
  });
  let res = await fetch(url, makeOpts(token));
  if (res.status === 401) {
    _adminAuth.clearToken();
    token = await adminRequestToken('Sai mật khẩu');
    res = await fetch(url, makeOpts(token));
  }
  return res;
};
function authedFetch(url, opts) { return window.authedFetch(url, opts); }

function AdminAuthModal() {
  const [open, setOpen] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [value, setValue] = React.useState('');
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    const handler = (e) => {
      setError(e.detail.errorMsg);
      setValue('');
      setOpen(true);
    };
    window.addEventListener('__admin_auth_request', handler);
    return () => window.removeEventListener('__admin_auth_request', handler);
  }, []);

  React.useEffect(() => {
    if (open) setTimeout(() => inputRef.current?.focus(), 50);
  }, [open]);

  function submit(e) {
    e.preventDefault();
    if (!value.trim()) return;
    _adminAuth.setToken(value.trim());
    setOpen(false);
    if (_adminAuth._resolve) {
      _adminAuth._resolve(value.trim());
      _adminAuth._resolve = null;
    }
    setValue('');
  }

  if (!open) return null;
  return (
    <div className="auth-backdrop">
      <form onSubmit={submit} className="auth-form">
        <div className="auth-title">Xác thực</div>
        {error && <div className="auth-error lbl">{error}</div>}
        <input
          ref={inputRef}
          type="password"
          placeholder="Mật khẩu"
          value={value}
          onChange={(e) => setValue(e.target.value)}
        />
        <button type="submit">Xác nhận</button>
      </form>
    </div>
  );
}

function useLocalState(key, initial) {
  const [val, setVal] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem(key)) ?? initial; } catch { return initial; }
  });
  const set = React.useCallback((v) => {
    setVal(v);
    try { localStorage.setItem(key, JSON.stringify(v)); } catch {}
  }, [key]);
  return [val, set];
}

function slugify(title) {
  return title
    .toLowerCase()
    .replace(/đ/g, "d")
    .normalize("NFD")
    .replace(/[̀-ͯ]/g, "")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

function parseHash() {
  const h = window.location.hash;
  if (h.startsWith("#/book/")) return { view: "detail", slug: h.slice(7) };
  if (h === "#/admin") return { view: "admin", slug: null };
  return { view: "library", slug: null };
}

const BOOKS_CACHE_KEY = "books_v1";
const BOOKS_CACHE_TTL = 5 * 60 * 1000;

function readBooksCache() {
  try {
    const raw = localStorage.getItem(BOOKS_CACHE_KEY);
    if (!raw) return null;
    const { data, ts } = JSON.parse(raw);
    return { data, stale: Date.now() - ts > BOOKS_CACHE_TTL };
  } catch { return null; }
}

function writeBooksCache(data) {
  try { localStorage.setItem(BOOKS_CACHE_KEY, JSON.stringify({ data, ts: Date.now() })); } catch {}
}

function App() {
  const cached = React.useMemo(() => readBooksCache(), []);
  const [books, setBooks] = React.useState(cached?.data || window.BOOKS || []);
  const [booksLoading, setBooksLoading] = React.useState(!cached);
  const [view, setView] = React.useState(() => parseHash().view);
  const [activeSlug, setActiveSlug] = React.useState(() => parseHash().slug);

  React.useEffect(() => {
    if (cached && !cached.stale) return;
    fetch("/api/books")
      .then((r) => r.ok ? r.json() : Promise.reject(r.status))
      .then((data) => { setBooks(data); writeBooksCache(data); setBooksLoading(false); })
      .catch(() => { setBooksLoading(false); });
  }, []);

  React.useEffect(() => {
    document.documentElement.setAttribute("data-density", "cozy");
  }, []);

  React.useEffect(() => {
    document.documentElement.setAttribute("data-view", view);
  }, [view]);

  React.useEffect(() => {
    function onHashChange() {
      const { view: v, slug } = parseHash();
      setView(v);
      setActiveSlug(slug);
      window.scrollTo({ top: 0, behavior: "instant" });
    }
    window.addEventListener("hashchange", onHashChange);
    return () => window.removeEventListener("hashchange", onHashChange);
  }, []);

  const opening = React.useRef(false);
  function openBook(id, rect) {
    const book = books.find((b) => b.id === id);
    if (!book || opening.current) return;
    const go = () => { window.location.hash = "/book/" + slugify(book.title); };
    if (!rect) { go(); return; }
    // paper sheet grows out of the cover (tilted like the cover) until it fills the screen
    opening.current = true;
    const rm = matchMedia("(prefers-reduced-motion: reduce)").matches;
    const W = document.documentElement.clientWidth, H = innerHeight;
    const el = document.createElement("div");
    el.className = "sheet-grow";
    el.style.transformOrigin = `${(rect.left + rect.right) / 2}px ${(rect.top + rect.bottom) / 2}px`;
    document.body.appendChild(el);
    const a = el.animate([
      { clipPath: `inset(${rect.top}px ${W - rect.right}px ${H - rect.bottom}px ${rect.left}px round 3px)`, transform: "rotate(-4.5deg)" },
      { clipPath: "inset(0px 0px 0px 0px round 0px)", transform: "rotate(0deg)" },
    ], { duration: rm ? 1 : 1050, easing: "cubic-bezier(.76,0,.18,1)", fill: "both" });
    a.onfinish = () => {
      window.__sheetOpened = true;
      opening.current = false;
      go();
      setTimeout(() => el.remove(), 1500); // fallback; BookDetail removes it after first paint
    };
  }

  function backToLibrary() {
    window.location.hash = "";
  }

  const activeBook = activeSlug ? books.find((b) => slugify(b.title) === activeSlug) : null;

  return (
    <React.Fragment>
      <div className="app">
        {view === "library" && (
          <Library
            books={books}
            loading={booksLoading}
            density="cozy"
            onOpenBook={openBook}
            onNav={(v) => { window.location.hash = v === "stats" ? "/stats" : ""; }}
          />
        )}
        {view === "detail" && activeBook && (
          <BookDetail
            book={activeBook}
            onBack={backToLibrary}
            density="cozy"
          />
        )}
{view === "admin" && (
          <Admin />
        )}
      </div>

      <Cursor />
      <AdminAuthModal />
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
