import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';

export default function BookIndex({ title, logoText, pages }) {
  const pageNums = useMemo(() => pages.map(p => p.n), [pages]);
  const total = pageNums.length;

  const [currentIdx, setCurrentIdx] = useState(() => {
    const m = window.location.hash.match(/^#page-(\d+)$/);
    if (m) {
      const idx = pageNums.indexOf(parseInt(m[1], 10));
      if (idx !== -1) return idx;
    }
    return 0;
  });

  const contentRef = useRef(null);

  const goTo = useCallback((n, smooth, push) => {
    const idx = pageNums.indexOf(n);
    if (idx === -1) return;
    const sec = document.getElementById(`page-${n}`);
    if (!sec) return;
    sec.scrollIntoView({ behavior: smooth ? 'smooth' : 'instant', block: 'start' });
    setCurrentIdx(idx);
    if (push) history.pushState(null, '', `#page-${n}`);
    else history.replaceState(null, '', `#page-${n}`);
  }, [pageNums]);

  // Scroll active sidebar item into view when page changes
  useEffect(() => {
    document.querySelector(`#page-list li[data-page="${pageNums[currentIdx]}"]`)
      ?.scrollIntoView({ block: 'nearest' });
  }, [currentIdx, pageNums]);

  // Initial scroll to hash page
  useEffect(() => {
    const n = pageNums[currentIdx];
    goTo(n, false, false);
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  // Scroll tracking — update currentIdx as user scrolls
  useEffect(() => {
    const container = contentRef.current;
    if (!container) return;
    const handleScroll = () => {
      const top = container.getBoundingClientRect().top;
      let found = 0;
      for (let i = 0; i < pageNums.length; i++) {
        const sec = document.getElementById(`page-${pageNums[i]}`);
        if (sec && sec.getBoundingClientRect().top - top <= 40) found = i;
        else break;
      }
      setCurrentIdx(prev => {
        if (found === prev) return prev;
        history.replaceState(null, '', `#page-${pageNums[found]}`);
        return found;
      });
    };
    container.addEventListener('scroll', handleScroll, { passive: true });
    return () => container.removeEventListener('scroll', handleScroll);
  }, [pageNums]);

  // Keyboard navigation
  useEffect(() => {
    const handleKeyDown = e => {
      if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
      setCurrentIdx(prev => {
        if ((e.key === 'ArrowLeft' || e.key === 'ArrowUp') && prev > 0) {
          goTo(pageNums[prev - 1], true, true);
        }
        if ((e.key === 'ArrowRight' || e.key === 'ArrowDown') && prev < total - 1) {
          goTo(pageNums[prev + 1], true, true);
        }
        return prev;
      });
    };
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [goTo, pageNums, total]);

  // Browser back/forward
  useEffect(() => {
    const handlePopState = () => {
      const m = location.hash.match(/^#page-(\d+)$/);
      if (m) {
        const n = parseInt(m[1], 10);
        if (pageNums.includes(n)) goTo(n, false, false);
      }
    };
    window.addEventListener('popstate', handlePopState);
    return () => window.removeEventListener('popstate', handlePopState);
  }, [goTo, pageNums]);

  const currentPage = pageNums[currentIdx];

  return (
    <>
      <header>
        <div className="logo">{logoText}</div>
        <div className="toolbar">
          <span id="page-indicator">{currentIdx + 1} / {total}</span>
        </div>
      </header>

      <div id="layout">
        <nav id="sidebar">
          <div id="sidebar-header">
            <div
              className="section-title"
              style={{ marginBottom: 0, borderBottom: 'none', paddingBottom: 0 }}
            >
              <span className="icon">✦</span> Pages
            </div>
            <p>{pages.length} pages</p>
          </div>
          <ul id="page-list">
            {pages.map(({ n }) => (
              <li key={n} data-page={n} className={n === currentPage ? 'active' : undefined}>
                <button onClick={() => goTo(n, false, true)}>
                  <span className="page-num">{n}</span>
                  <span>Page {n}</span>
                </button>
              </li>
            ))}
          </ul>
        </nav>

        <div id="main">
          <div id="nav">
            <button
              id="btn-prev"
              className="tab"
              disabled={currentIdx === 0}
              onClick={() => goTo(pageNums[currentIdx - 1], true, true)}
            >
              &#8592; Prev
            </button>
            <span id="page-title">Page {currentPage}</span>
            <button
              id="btn-next"
              className="tab"
              disabled={currentIdx === total - 1}
              onClick={() => goTo(pageNums[currentIdx + 1], true, true)}
            >
              Next &#8594;
            </button>
          </div>
          <div id="content" ref={contentRef}>
            {pages.map(({ n, content }) => (
              <section
                key={n}
                id={`page-${n}`}
                className="page-section"
                dangerouslySetInnerHTML={{ __html: content }}
              />
            ))}
          </div>
        </div>
      </div>
    </>
  );
}
