/* Honey Scripts — Doc page renderer + right-rail TOC */

const { useState: useStateP, useEffect: useEffectP, useMemo: useMemoP, useRef: useRefP } = React;

function PageBody({ blocks }) {
  // Auto-number "Step N" h2 blocks (those with id starting with "step-")
  let stepCount = 0;
  return (
    <div className="prose page-fade">
      {blocks.map((b, i) => {
        if (b.type === "p")     return <p key={i}><MD>{b.text}</MD></p>;
        if (b.type === "h2") return <h2 key={i} id={b.id}><MD>{b.text}</MD></h2>;
        if (b.type === "h3") {
          if (b.id && b.id.startsWith("step-")) {
            stepCount += 1;
            return (
              <div className="step" key={i}>
                <div className="step-num">{stepCount}</div>
                <div className="step-line"/>
                <div className="step-body">
                  <h3 id={b.id} style={{ marginTop: 4 }}><MD>{b.text}</MD></h3>
                </div>
              </div>
            );
          }
          return <h3 key={i} id={b.id}><MD>{b.text}</MD></h3>;
        }
        if (b.type === "code")  return <CodeBlock key={i} code={b.code} lang={b.lang} title={b.title}/>;
        if (b.type === "callout") return <Callout key={i} kind={b.kind} title={b.title} body={b.body}/>;
        if (b.type === "list")  return <ul key={i}>{b.items.map((it, j) => <li key={j}><MD>{it}</MD></li>)}</ul>;
        if (b.type === "video") return <VideoEmbed key={i} src={b.src} caption={b.caption} title={b.title} href={b.href} thumb={b.thumb}/>;
        if (b.type === "deps")  return (
          <div key={i} className="deps-grid">
            {b.items.map((d, j) => (
              <a key={j} className="dep-link" href={d.href} target="_blank" rel="noreferrer noopener">
                <span className="dep-ico"><Icon.Package/></span>
                <div>
                  <div className="dep-name">{d.name}</div>
                  <div className="dep-desc">{d.desc}</div>
                </div>
                <Icon.External className="dep-arrow"/>
              </a>
            ))}
          </div>
        );
        if (b.type === "errorCard") return <ErrorCard key={i} code={b.code} cause={b.cause} solutions={b.solutions}/>;
        return null;
      })}
    </div>
  );
}

function VideoEmbed({ src, caption, title, href, thumb }) {
  // Derive a YouTube video id from src or href.
  const ytId = useMemoP(() => {
    const candidates = [src, href].filter(Boolean);
    for (const u of candidates) {
      const m = u.match(/(?:youtu\.be\/|youtube\.com\/(?:embed\/|watch\?v=|v\/))([\w-]{6,})/);
      if (m) return m[1];
    }
    return null;
  }, [src, href]);

  // Use the full youtube.com watch URL — youtu.be short links are blocked
  // on some networks/extensions (ERR_BLOCKED_BY_RESPONSE).
  const linkUrl = ytId ? `https://www.youtube.com/watch?v=${ytId}` : href;
  // Embed src — prefer the provided one, fall back to building from the id.
  const embedSrc = src || (ytId ? `https://www.youtube.com/embed/${ytId}` : null);

  if (!embedSrc) {
    // No video set — show the legacy placeholder.
    return (
      <figure className="video-embed">
        <div className="video-placeholder">
          <div className="video-play" aria-hidden="true">
            <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
          </div>
          {caption && <div className="video-caption">{caption}</div>}
        </div>
      </figure>
    );
  }

  return (
    <figure className="video-embed">
      <iframe
        src={embedSrc}
        title={title || "Honey Scripts video"}
        loading="lazy"
        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
        referrerPolicy="strict-origin-when-cross-origin"
        allowFullScreen
      />
      {title && linkUrl && (
        <figcaption className="video-figcap">
          <a href={linkUrl} target="_blank" rel="noreferrer noopener" className="video-title-link">
            {title}
            <Icon.External/>
          </a>
          {caption && <span className="video-caption-inline">· {caption}</span>}
        </figcaption>
      )}
    </figure>
  );
}

function PageView({ pageId, onNavigate }) {
  const lang = window.useLang();
  const t = window.useT();
  const meta = (PAGES.meta[pageId] && (PAGES.meta[pageId][lang] || PAGES.meta[pageId].en)) || { title: pageId, subtitle: "" };
  const blocks = getPageBlocks(pageId, lang);

  // Find the sidebar item that owns this page — used to pick the title icon.
  // Show an icon when the current page is the script's landing page.
  const ownerItem = useMemoP(() => {
    for (const g of SIDEBAR) {
      for (const it of g.items) {
        if (it.landingPage === pageId) return it;
      }
    }
    return null;
  }, [pageId]);
  const isLanding = !!ownerItem;
  // Resolve the icon component for the owner's glyph (capitalised key in Icon).
  const TitleIcon = useMemoP(() => {
    if (!ownerItem || !ownerItem.glyph) return null;
    const k = ownerItem.glyph[0].toUpperCase() + ownerItem.glyph.slice(1);
    return Icon[k] || null;
  }, [ownerItem]);

  // Prev / Next from sidebar order (landing pages count too)
  const allPages = useMemoP(() => {
    const arr = [];
    SIDEBAR.forEach(g => g.items.forEach(it => {
      if (it.landingPage) {
        const meta = PAGES.meta[it.landingPage]?.en || {};
        arr.push({ id: it.landingPage, label: it.label });
      }
      it.pages.forEach(p => arr.push(p));
    }));
    return arr;
  }, []);
  const idx = allPages.findIndex(p => p.id === pageId);
  const prev = idx > 0 ? allPages[idx - 1] : null;
  const next = idx >= 0 && idx < allPages.length - 1 ? allPages[idx + 1] : null;

  return (
    <article style={{ minWidth: 0 }} className="page-fade">
      <section className="hero">
        <div className="hero-sparks" aria-hidden="true">
          <span className="spark s-lg" style={{ top: "16%", left: "7%", animationDelay: "0s" }}></span>
          <span className="spark s-sm" style={{ top: "30%", left: "16%", animationDelay: "1.4s" }}></span>
          <span className="spark s-md" style={{ top: "62%", left: "10%", animationDelay: "0.7s" }}></span>
          <span className="spark s-sm" style={{ bottom: "16%", left: "21%", animationDelay: "2.1s" }}></span>
          <span className="spark s-md" style={{ top: "20%", left: "38%", animationDelay: "1.1s" }}></span>
          <span className="spark s-sm" style={{ bottom: "22%", left: "46%", animationDelay: "2.6s" }}></span>
          <span className="spark s-lg" style={{ top: "24%", right: "12%", animationDelay: "0.4s" }}></span>
          <span className="spark s-sm" style={{ top: "44%", right: "7%", animationDelay: "1.8s" }}></span>
          <span className="spark s-md" style={{ bottom: "20%", right: "16%", animationDelay: "0.9s" }}></span>
          <span className="spark s-sm" style={{ bottom: "32%", right: "28%", animationDelay: "2.3s" }}></span>
          <span className="spark s-sm" style={{ top: "14%", right: "32%", animationDelay: "1.5s" }}></span>
        </div>
        <div className="hero-inner">
          <h1 className="hero-title">
            {isLanding && (
              <span className="title-mark">
                {TitleIcon
                  ? <TitleIcon style={{ width: 60, height: 60 }}/>
                  : <BrandIcon style={{ width: 60, height: 60 }}/>}
              </span>
            )}
            <span className="gold">{(meta.title || "").replace(/Honey\s+/g, "")}</span>
          </h1>
          <p className="hero-sub">{meta.subtitle}</p>
          <div className="hero-meta">
            <span className="chip gold">ESX / QBCore / QBox</span>
          </div>
        </div>
      </section>

      <TOCInline pageId={pageId}/>

      <div style={{ marginTop: 28 }}>
        <PageBody blocks={blocks}/>
      </div>

      <div className="docfoot">
        {prev ? (
          <a href="#" onClick={e => { e.preventDefault(); onNavigate(prev.id); }}>
            <div className="small">{t("previous")}</div>
            <div className="arrow"><Icon.ArrowLeft/> {prev.label}</div>
          </a>
        ) : <span/>}
        {next ? (
          <a href="#" onClick={e => { e.preventDefault(); onNavigate(next.id); }} style={{ textAlign: "right" }}>
            <div className="small">{t("next")}</div>
            <div className="arrow" style={{ justifyContent: "flex-end" }}>{next.label} <Icon.Arrow/></div>
          </a>
        ) : <span/>}
      </div>
    </article>
  );
}

function TOC({ pageId, headings: headingsProp, fastNav }) {
  const t = window.useT();
  const lang = window.useLang ? window.useLang() : "en";
  const headings = useMemoP(() => {
    if (headingsProp) return headingsProp;
    const blocks = getPageBlocks(pageId, window.useLang ? window.useLang() : "en");
    return blocks.filter(b => (b.type === "h2" || b.type === "h3") && b.id)
                 .map(b => ({ id: b.id, level: b.type, text: b.text }));
  }, [pageId, window.__lang, headingsProp]);

  const [activeId, setActiveId] = useStateP(headings[0]?.id);

  useEffectP(() => {
    if (!headings.length) return;
    const obs = new IntersectionObserver((entries) => {
      // Pick the topmost entry that's intersecting; fall back to nearest above
      const visible = entries.filter(e => e.isIntersecting).sort((a,b) => a.target.offsetTop - b.target.offsetTop);
      if (visible[0]) setActiveId(visible[0].target.id);
    }, { rootMargin: "-90px 0px -65% 0px", threshold: [0, 1] });
    headings.forEach(h => { const el = document.getElementById(h.id); if (el) obs.observe(el); });
    return () => obs.disconnect();
  }, [headings]);

  return (
    <aside>
      <div className="toc-h">{t("onThisPage")}</div>
      <nav>
        {headings.length === 0 && <div className="small" style={{ padding: "4px 10px" }}>—</div>}
        {headings.map(h => (
          <a
            key={h.id}
            href={"#" + h.id}
            className={"toc-item " + (h.level === "h3" ? "h3 " : "") + (activeId === h.id ? "active" : "")}
            onClick={(e) => { e.preventDefault(); const el = document.getElementById(h.id); if (el) { window.scrollTo({ top: el.offsetTop - 80, behavior: "smooth" }); } }}
          >
            <MD>{h.text}</MD>
          </a>
        ))}
      </nav>

      {fastNav ? (
        (() => {
          const w = WELCOME[lang] || WELCOME.en;
          return (
            <button
              type="button"
              className="toc-fastnav"
              onClick={() => window.dispatchEvent(new CustomEvent("hs:openSearch"))}
            >
              <div className="toc-fastnav-h">
                <span className="toc-fastnav-ico"><Icon.Search width={13} height={13}/></span>
                {w.searchTitle}
              </div>
              <p>
                {w.searchPre}{" "}
                <span className="kbd">Ctrl <span className="kbd-sep">+</span> K</span>{" "}
                {w.searchPost}
              </p>
            </button>
          );
        })()
      ) : (
        <div className="toc-help">
          <h4>{t("needHelp")}</h4>
          <p>{t("needHelpBody")}</p>
          <a href="https://discord.honey-scripts.com/" target="_blank" rel="noreferrer noopener">
            <Icon.Discord/> {t("askDiscord")} <Icon.External/>
          </a>
        </div>
      )}
    </aside>
  );
}

window.PageView = PageView;
window.TOC = TOC;

/* Mobile-only TOC — collapsed <details> shown when the right rail is hidden. */
function TOCInline({ pageId }) {
  const lang = window.useLang ? window.useLang() : "en";
  const t = window.useT();
  const headings = useMemoP(() => {
    const blocks = getPageBlocks(pageId, lang);
    return blocks.filter(b => (b.type === "h2" || b.type === "h3") && b.id)
                 .map(b => ({ id: b.id, level: b.type, text: b.text }));
  }, [pageId, lang]);
  if (headings.length === 0) return null;
  return (
    <details className="toc-mobile">
      <summary>
        <span>{t("onThisPage")}</span>
        <Icon.ChevronRight className="caret"/>
      </summary>
      <nav>
        {headings.map(h => (
          <a
            key={h.id}
            href={"#" + h.id}
            className={"toc-item " + (h.level === "h3" ? "h3" : "")}
            onClick={(e) => {
              e.preventDefault();
              const el = document.getElementById(h.id);
              if (el) window.scrollTo({ top: el.offsetTop - 80, behavior: "smooth" });
              // Auto-close after tap
              e.currentTarget.closest("details").open = false;
            }}
          >
            <MD>{h.text}</MD>
          </a>
        ))}
      </nav>
    </details>
  );
}
window.TOCInline = TOCInline;

/* ============================================================
   Welcome — bespoke landing page (not block-rendered).
   ============================================================ */

// Build the product-guide cards from the live SIDEBAR (Honey Scripts group),
// skipping any "coming soon" placeholders. Auto-updates as products are added.
function getWelcomeProducts() {
  const group = SIDEBAR.find(g => g.label === "Honey Scripts");
  if (!group) return [];
  return group.items.filter(it => !it.comingSoon && it.landingPage);
}

// Shared headings list, used by both the page and the right-rail TOC.
function welcomeTOC(lang) {
  const w = WELCOME[lang] || WELCOME.en;
  return [
    { id: "product-guides", level: "h2", text: w.guidesTitle },
    { id: "quick-access",   level: "h2", text: w.cardsTitle },
    { id: "support",        level: "h2", text: w.supportTitle },
  ];
}
window.welcomeTOC = welcomeTOC;

// Product cover image (only for products we have real art for); others get a glyph tile.
const WELCOME_COVERS = {
  "honey-radio": "assets/cover-honey-radio.png",
};

function ProductCard({ item, onNavigate }) {
  const lang = window.useLang();
  const w = WELCOME[lang] || WELCOME.en;
  const meta = (w.products && w.products[item.id]) || {};
  const cover = WELCOME_COVERS[item.id];
  const GlyphIcon = item.glyph
    ? (Icon[item.glyph[0].toUpperCase() + item.glyph.slice(1)] || null)
    : null;

  return (
    <a
      className="pcard"
      href={"#/" + item.landingPage}
      onClick={(e) => { e.preventDefault(); onNavigate(item.landingPage); }}
    >
      <div className={"pcard-cover" + (cover ? " has-img" : "")}>
        {cover
          ? <img className="pcard-img" src={cover} alt={item.label} loading="lazy"/>
          : (
            <span className="pcard-glyph">
              {GlyphIcon ? <GlyphIcon style={{ width: 46, height: 46 }}/> : <BrandIcon style={{ width: 46, height: 46 }}/>}
            </span>
          )}
      </div>
      <div className="pcard-body">
        <div className="pcard-head">
          <span className="pcard-name">{item.label}</span>
          {item.version && <span className="chip pcard-ver">{item.version}</span>}
        </div>
        {meta.tagline && <p className="pcard-desc">{meta.tagline}</p>}
        <span className="pcard-foot">{w.viewGuide} <Icon.Arrow/></span>
      </div>
    </a>
  );
}

function WelcomePage({ onNavigate }) {
  const lang = window.useLang();
  const w = WELCOME[lang] || WELCOME.en;
  const STORE = "https://store.honey-scripts.com";
  const DISCORD = "https://discord.honey-scripts.com/";
  const products = getWelcomeProducts();

  return (
    <article className="page-fade" style={{ minWidth: 0 }}>
      <section className="hero welcome-hero">
        <div className="hero-sparks" aria-hidden="true">
          <span className="spark s-lg" style={{ top: "22%", left: "9%", animationDelay: "0s" }}></span>
          <span className="spark s-sm" style={{ top: "40%", left: "18%", animationDelay: "1.4s" }}></span>
          <span className="spark s-md" style={{ top: "66%", left: "13%", animationDelay: "0.7s" }}></span>
          <span className="spark s-sm" style={{ bottom: "20%", left: "26%", animationDelay: "2.1s" }}></span>
          <span className="spark s-md" style={{ top: "26%", left: "44%", animationDelay: "1.1s" }}></span>
          <span className="spark s-lg" style={{ top: "30%", right: "13%", animationDelay: "0.4s" }}></span>
          <span className="spark s-sm" style={{ top: "52%", right: "9%", animationDelay: "1.8s" }}></span>
          <span className="spark s-md" style={{ bottom: "24%", right: "18%", animationDelay: "0.9s" }}></span>
          <span className="spark s-sm" style={{ bottom: "36%", right: "32%", animationDelay: "2.3s" }}></span>
          <span className="spark s-sm" style={{ top: "18%", right: "36%", animationDelay: "1.5s" }}></span>
        </div>
        <div className="welcome-hero-inner">
          <span className="welcome-eyebrow">{w.eyebrow}</span>
          <h1 className="welcome-title">
            <span className="gold">{w.title}</span>
          </h1>
          <p className="welcome-tagline">{w.tagline}</p>
        </div>
      </section>

      <h2 className="welcome-h2" id="product-guides">{w.guidesTitle}</h2>
      <p className="welcome-section-sub">{w.guidesSub}</p>
      <div className="welcome-products">
        {products.map(it => <ProductCard key={it.id} item={it} onNavigate={onNavigate}/>)}
      </div>

      <h2 className="welcome-h2" id="quick-access">{w.cardsTitle}</h2>
      <div className="welcome-quick">
        <a className="qcard" href={STORE} target="_blank" rel="noreferrer noopener">
          <span className="qcard-ico qcard-ico-tebex"><Icon.Cart width={20} height={20}/></span>
          <div className="qcard-text">
            <div className="qcard-label">{w.cards.tebex.label}</div>
            <div className="qcard-desc">{w.cards.tebex.desc}</div>
          </div>
          <span className="qcard-arrow"><Icon.External/></span>
        </a>
        <a className="qcard" href={DISCORD} target="_blank" rel="noreferrer noopener">
          <span className="qcard-ico qcard-ico-discord"><Icon.Discord width={18} height={18}/></span>
          <div className="qcard-text">
            <div className="qcard-label">{w.cards.discord.label}</div>
            <div className="qcard-desc">{w.cards.discord.desc}</div>
          </div>
          <span className="qcard-arrow"><Icon.External/></span>
        </a>
        <a className="qcard" href="#/escrow" onClick={(e) => { e.preventDefault(); onNavigate("escrow"); }}>
          <span className="qcard-ico qcard-ico-escrow"><Icon.Shield width={19} height={19}/></span>
          <div className="qcard-text">
            <div className="qcard-label">{w.cards.escrow.label}</div>
            <div className="qcard-desc">{w.cards.escrow.desc}</div>
          </div>
          <span className="qcard-arrow"><Icon.Arrow/></span>
        </a>
      </div>

      <h2 className="welcome-h2" id="support">{w.supportTitle}</h2>
      <p className="welcome-support-lead">{w.supportLead}</p>
      {(() => {
        const step = w.supportSteps.find(s => s.kind === "docs") || w.supportSteps[0];
        if (!step) return null;
        return (
          <div className="support-banner">
            <span className="support-banner-ico"><Icon.Info width={20} height={20}/></span>
            <div className="support-banner-text">
              <div className="support-banner-h">{step.h}</div>
              <div className="support-banner-b">{step.b}</div>
            </div>
            {step.cta && (
              <button
                className="btn btn-primary support-banner-cta"
                onClick={() => { const el = document.getElementById("product-guides"); if (el) window.scrollTo({ top: el.offsetTop - 80, behavior: "smooth" }); }}
              >
                {step.cta} <Icon.Arrow/>
              </button>
            )}
          </div>
        );
      })()}
    </article>
  );
}
window.WelcomePage = WelcomePage;
