// Book Reader — migrated from the Vite/TypeScript app
// Renders markdown chapters fetched from /book-content/*.json
const { useState: useSt, useEffect: useEf, useMemo } = React;

// ── Configure marked renderer (runs once at script load) ─────────────────────
(function configureMarked() {
  if (!window.marked) return;
  window.marked.use({
    renderer: {
      // marked v4 API: (code, language, isEscaped)
      code(code, lang) {
        if (lang === 'mermaid') {
          return `<div class="mermaid">${code}</div>`;
        }
        const esc = String(code)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;');
        if (lang) {
          return `<div class="code-block"><div class="code-label">${lang}</div><pre><code>${esc}</code></pre></div>`;
        }
        return `<pre><code>${esc}</code></pre>`;
      },
    },
    breaks: false,
    gfm: true,
  });
})();

// ── Admonition preprocessing ──────────────────────────────────────────────────
const ADM = {
  note:    { bg: '#eff6ff', border: '#3b82f6', label: 'Note' },
  tip:     { bg: '#f0fdf4', border: '#22c55e', label: 'Tip' },
  warning: { bg: '#fffbeb', border: '#f59e0b', label: 'Warning' },
  danger:  { bg: '#fef2f2', border: '#ef4444', label: 'Danger' },
  info:    { bg: '#eff6ff', border: '#3b82f6', label: 'Info' },
};

function preprocessAdmonitions(md) {
  return md.replace(
    /^:::(\w+)(?:[ \t]+(.+?))?\s*\n([\s\S]*?)^:::/gm,
    (_, type, title, body) => {
      const c = ADM[type] || ADM.note;
      const label = (title || c.label).trim();
      const bodyHtml = window.marked
        ? window.marked.parse(body.trim())
        : `<p>${body.trim().replace(/\n/g, '<br>')}</p>`;
      return (
        `\n<div style="background:${c.bg};border-left:4px solid ${c.border};` +
        `border-radius:8px;padding:16px 20px;margin:20px 0">` +
        `<p style="font-weight:700;font-size:11px;color:${c.border};margin:0 0 8px;` +
        `text-transform:uppercase;letter-spacing:0.08em">${label}</p>` +
        `<div>${bodyHtml}</div></div>\n`
      );
    }
  );
}

function renderMarkdown(content) {
  if (!window.marked) return `<pre style="white-space:pre-wrap">${content}</pre>`;
  const processed = preprocessAdmonitions(content);
  return window.marked.parse(processed);
}

// ── Sidebar ───────────────────────────────────────────────────────────────────
function BookSidebar({ manifest, currentSlug, readChapters, onNavigate, open, isMobile, onClose }) {
  const [collapsed, setCollapsed] = useSt({});

  // Auto-expand the module containing the current chapter
  useEf(() => {
    if (!manifest) return;
    setCollapsed(prev => {
      const next = { ...prev };
      manifest.modules.forEach(mod => {
        if (mod.chapters.some(ch => ch.slug === currentSlug)) {
          next[mod.slug] = false;
        }
      });
      return next;
    });
  }, [manifest, currentSlug]);

  if (!open) return null;

  const sidebarContent = (
    <aside style={{
      width: isMobile ? '80vw' : 272, maxWidth: 320, flexShrink: 0,
      background: '#fff', borderRight: '1px solid var(--border)',
      position: isMobile ? 'fixed' : 'sticky', top: 0, left: 0, height: '100vh', overflowY: 'auto',
      display: 'flex', flexDirection: 'column',
      zIndex: isMobile ? 200 : 'auto',
      boxShadow: isMobile ? '4px 0 24px rgba(0,0,0,0.15)' : 'none',
    }}>
      {/* Title + close */}
      <div style={{ padding: '18px 16px 14px', borderBottom: '1px solid var(--border)', flexShrink: 0, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--brand-primary)', lineHeight: 1.3 }}>
            Physical AI &amp; Humanoid Robotics
          </div>
          <div style={{ fontSize: 11, color: 'var(--fg-4)', marginTop: 3 }}>Open Source Book</div>
        </div>
        {isMobile && (
          <button onClick={onClose} style={{
            background: 'none', border: '1px solid var(--border)', borderRadius: 7,
            padding: '4px 10px', cursor: 'pointer', fontSize: 18, lineHeight: 1,
            color: 'var(--fg-3)', fontFamily: 'inherit',
          }}>✕</button>
        )}
      </div>

      {/* Modules & chapters */}
      <div style={{ flex: 1 }}>
        {manifest ? manifest.modules.map(mod => {
          const isCollapsed = collapsed[mod.slug];
          return (
            <div key={mod.slug}>
              <button
                onClick={() => setCollapsed(p => ({ ...p, [mod.slug]: !p[mod.slug] }))}
                style={{
                  width: '100%', textAlign: 'left', padding: '9px 16px',
                  background: 'none', border: 'none', borderBottom: '1px solid var(--border)',
                  cursor: 'pointer', fontFamily: 'inherit',
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                  fontSize: 10, fontWeight: 700, color: 'var(--fg-4)',
                  letterSpacing: '0.07em', textTransform: 'uppercase',
                }}
              >
                <span>{mod.label}</span>
                <span style={{ fontSize: 9, color: 'var(--fg-4)' }}>{isCollapsed ? '▶' : '▼'}</span>
              </button>

              {!isCollapsed && mod.chapters.map(ch => {
                const isActive = ch.slug === currentSlug;
                const isRead = readChapters.includes(ch.slug);
                return (
                  <button
                    key={ch.slug}
                    onClick={() => onNavigate(ch.slug)}
                    style={{
                      width: '100%', textAlign: 'left',
                      padding: '7px 16px 7px 20px',
                      background: isActive ? 'rgba(22,59,107,0.07)' : 'none',
                      border: 'none',
                      borderLeft: isActive ? '3px solid var(--brand-primary)' : '3px solid transparent',
                      cursor: 'pointer', fontFamily: 'inherit',
                      display: 'flex', alignItems: 'flex-start', gap: 8,
                      fontSize: 12.5,
                      color: isActive ? 'var(--brand-primary)' : 'var(--fg-2)',
                      fontWeight: isActive ? 500 : 400,
                      lineHeight: 1.4,
                    }}
                  >
                    <span style={{
                      width: 7, height: 7, borderRadius: '50%', flexShrink: 0, marginTop: 4,
                      background: isRead && !isActive ? '#22c55e' : 'transparent',
                      border: isRead && !isActive ? 'none' : '1px solid transparent',
                    }}/>
                    <span>{ch.title}</span>
                  </button>
                );
              })}
            </div>
          );
        }) : (
          <div style={{ padding: '20px 16px', color: 'var(--fg-4)', fontSize: 13 }}>Loading...</div>
        )}
      </div>
    </aside>
  );

  // On mobile, wrap in an overlay backdrop
  if (isMobile) {
    return (
      <div
        onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
        style={{
          position: 'fixed', inset: 0, zIndex: 199,
          background: 'rgba(0,0,0,0.4)',
        }}
      >
        {sidebarContent}
      </div>
    );
  }

  return sidebarContent;
}

// ── Header ────────────────────────────────────────────────────────────────────
function BookReaderHeader({ chapterTitle, prev, next, onBack, onNavigate, onToggleSidebar, isMobile }) {
  return (
    <header style={{
      position: 'sticky', top: isMobile ? 56 : 0, zIndex: 40,
      background: 'rgba(255,255,255,0.96)', backdropFilter: 'blur(8px)',
      borderBottom: '1px solid var(--border)', flexShrink: 0,
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        height: 54, padding: '0 20px', gap: 12,
      }}>
        {/* Left: toggle + breadcrumb */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0, flex: 1 }}>
          <button
            onClick={onToggleSidebar}
            title="Toggle sidebar"
            style={{
              background: 'none', border: '1px solid var(--border)', borderRadius: 7,
              padding: '5px 9px', cursor: 'pointer', fontSize: 14, lineHeight: 1,
              color: 'var(--fg-3)', fontFamily: 'inherit', flexShrink: 0,
            }}
          >☰</button>
          <button
            onClick={onBack}
            style={{
              background: 'none', border: 'none', cursor: 'pointer',
              fontSize: 13, color: 'var(--fg-3)', display: 'flex', alignItems: 'center',
              gap: 4, fontFamily: 'inherit', padding: '4px 6px', borderRadius: 6, flexShrink: 0,
            }}
          >← Book</button>
          <span style={{ color: 'var(--border)', flexShrink: 0 }}>/</span>
          <span style={{
            fontSize: 13, fontWeight: 500, color: 'var(--brand-primary)',
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>{chapterTitle || '…'}</span>
        </div>

        {/* Right: prev / next */}
        <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
          {prev && (
            <button
              onClick={() => onNavigate(prev.slug)}
              style={{
                background: 'none', border: '1px solid var(--border)', borderRadius: 8,
                padding: isMobile ? '6px 10px' : '4px 12px', cursor: 'pointer', fontSize: 12,
                color: 'var(--fg-3)', fontFamily: 'inherit',
                display: 'flex', alignItems: 'center', gap: 4,
                maxWidth: isMobile ? 'none' : 160, overflow: 'hidden',
              }}
            >
              <span>←</span>
              {!isMobile && <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {prev.title}
              </span>}
            </button>
          )}
          {next && (
            <button
              onClick={() => onNavigate(next.slug)}
              style={{
                background: 'none', border: '1px solid var(--border)', borderRadius: 8,
                padding: isMobile ? '6px 10px' : '4px 12px', cursor: 'pointer', fontSize: 12,
                color: 'var(--fg-3)', fontFamily: 'inherit',
                display: 'flex', alignItems: 'center', gap: 4,
                maxWidth: isMobile ? 'none' : 160, overflow: 'hidden',
              }}
            >
              {!isMobile && <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {next.title}
              </span>}
              <span>→</span>
            </button>
          )}
        </div>
      </div>
    </header>
  );
}

// ── Main surface ──────────────────────────────────────────────────────────────
function BookReaderSurface({ goto, bookSlug }) {
  const slug = bookSlug || 'intro';
  const isMobile = window.useIsMobile();

  const [manifest, setManifest] = useSt(null);
  const [chapter, setChapter] = useSt(null);
  const [loading, setLoading] = useSt(true);
  const [sidebarOpen, setSidebarOpen] = useSt(!isMobile);
  const [readChapters, setReadChapters] = useSt(() => {
    try { return JSON.parse(localStorage.getItem('book-read-chapters') || '[]'); } catch { return []; }
  });

  // Auto-close sidebar on mobile when entering reader
  useEf(() => {
    setSidebarOpen(!isMobile);
  }, [isMobile]);

  // Load manifest once
  useEf(() => {
    fetch('../../book-content/manifest.json')
      .then(r => r.json())
      .then(setManifest)
      .catch(console.error);
  }, []);

  // Load chapter when slug changes
  useEf(() => {
    setLoading(true);
    setChapter(null);
    fetch(`../../book-content/${slug}.json`)
      .then(r => r.json())
      .then(data => {
        setChapter(data);
        setLoading(false);
        setReadChapters(prev => {
          if (prev.includes(slug)) return prev;
          const next = [...prev, slug];
          try { localStorage.setItem('book-read-chapters', JSON.stringify(next)); } catch {}
          return next;
        });
      })
      .catch(() => setLoading(false));
  }, [slug]);

  // Run mermaid diagrams after chapter renders
  useEf(() => {
    if (chapter && window.mermaid) {
      setTimeout(() => { try { window.mermaid.run(); } catch {} }, 80);
    }
  }, [chapter]);

  // Flat chapter list for prev/next
  const allChapters = manifest ? manifest.modules.flatMap(m => m.chapters) : [];
  const currentIdx = allChapters.findIndex(c => c.slug === slug);
  const prevChapter = currentIdx > 0 ? allChapters[currentIdx - 1] : null;
  const nextChapter = currentIdx < allChapters.length - 1 ? allChapters[currentIdx + 1] : null;

  const renderedHtml = useMemo(
    () => chapter ? renderMarkdown(chapter.content) : '',
    [chapter]
  );

  function onNavigate(newSlug) {
    goto('book-reader', newSlug);
    window.scrollTo({ top: 0, behavior: 'instant' });
    if (isMobile) setSidebarOpen(false);
  }

  // Intercept internal /docs/ and /book/ links inside content
  function handleContentClick(e) {
    const a = e.target.closest('a[href]');
    if (!a) return;
    const href = a.getAttribute('href');
    if (href && (href.startsWith('/docs/') || href.startsWith('/book/'))) {
      e.preventDefault();
      const parts = href.split('/').filter(Boolean);
      const targetSlug = parts[parts.length - 1];
      if (targetSlug) onNavigate(targetSlug);
    }
  }

  return (
    <div style={{ display: 'flex', minHeight: '100vh', background: '#fff' }}>
      <BookSidebar
        manifest={manifest}
        currentSlug={slug}
        readChapters={readChapters}
        onNavigate={onNavigate}
        open={sidebarOpen}
        isMobile={isMobile}
        onClose={() => setSidebarOpen(false)}
      />

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
        <BookReaderHeader
          chapterTitle={chapter ? chapter.title : null}
          prev={prevChapter}
          next={nextChapter}
          onBack={() => goto('book')}
          onNavigate={onNavigate}
          onToggleSidebar={() => setSidebarOpen(o => !o)}
          isMobile={isMobile}
        />

        {/* Content */}
        <div style={{ flex: 1 }}>
          <div style={{ maxWidth: 800, margin: '0 auto', padding: isMobile ? '24px 16px 64px' : '48px 48px 96px' }}>
            {loading && (
              <p style={{ color: 'var(--fg-4)', fontSize: 14 }}>Loading chapter…</p>
            )}
            {chapter && (
              <div
                className="book-prose"
                onClick={handleContentClick}
                dangerouslySetInnerHTML={{ __html: renderedHtml }}
              />
            )}

            {/* Bottom prev / next cards */}
            {chapter && (prevChapter || nextChapter) && (
              <div style={{
                marginTop: 64, paddingTop: 32, borderTop: '1px solid var(--border)',
                display: 'flex', justifyContent: 'space-between', gap: 16,
              }}>
                {prevChapter ? (
                  <button
                    onClick={() => onNavigate(prevChapter.slug)}
                    style={{
                      flex: 1, maxWidth: '47%', textAlign: 'left',
                      background: '#fff', border: '1px solid var(--border)',
                      borderRadius: 12, padding: '16px 20px',
                      cursor: 'pointer', fontFamily: 'inherit',
                      display: 'flex', flexDirection: 'column', gap: 5,
                    }}
                  >
                    <span style={{ fontSize: 11, color: 'var(--fg-4)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>← Previous</span>
                    <span style={{ fontSize: 14, fontWeight: 500, color: 'var(--brand-primary)', lineHeight: 1.4 }}>{prevChapter.title}</span>
                  </button>
                ) : <div style={{ flex: 1 }}/>}

                {nextChapter ? (
                  <button
                    onClick={() => onNavigate(nextChapter.slug)}
                    style={{
                      flex: 1, maxWidth: '47%', textAlign: 'right',
                      background: '#fff', border: '1px solid var(--border)',
                      borderRadius: 12, padding: '16px 20px',
                      cursor: 'pointer', fontFamily: 'inherit',
                      display: 'flex', flexDirection: 'column', gap: 5, alignItems: 'flex-end',
                    }}
                  >
                    <span style={{ fontSize: 11, color: 'var(--fg-4)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Next →</span>
                    <span style={{ fontSize: 14, fontWeight: 500, color: 'var(--brand-primary)', lineHeight: 1.4 }}>{nextChapter.title}</span>
                  </button>
                ) : <div style={{ flex: 1 }}/>}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.BookReaderSurface = BookReaderSurface;
