// COVIA Knowledge — Living Archive
// Sticky chapter pin + cascading category rows that reveal as you scroll.

function CoviaKnowledge({ categories = window.COVIA_KNOWLEDGE, meta = window.COVIA_META }) {
  const { lang, t } = useLang();
  const sectionRef = React.useRef(null);
  const counterRef = React.useRef(null);
  const rowsRef = React.useRef(null);

  const totalDocs = categories.reduce((s, c) => s + c.count, 0) + (meta.pilgrimCount || 0) + (meta.introCount || 0);
  const maxCount = Math.max(...categories.map(c => c.count));

  // Counter: one-shot ramp from 0 → totalDocs when counter enters view.
  const [displayCount, setDisplayCount] = React.useState(0);
  React.useEffect(() => {
    const el = counterRef.current;
    if (!el) return;
    let raf = null;
    const io = new IntersectionObserver((entries) => {
      if (!entries[0].isIntersecting) return;
      io.disconnect();
      const duration = 1200;
      const start = performance.now();
      const tick = (now) => {
        const t = Math.min(1, (now - start) / duration);
        const eased = 1 - Math.pow(1 - t, 3);
        setDisplayCount(Math.round(eased * totalDocs));
        if (t < 1) raf = requestAnimationFrame(tick);
      };
      raf = requestAnimationFrame(tick);
    }, { threshold: 0.3 });
    io.observe(el);
    return () => {
      io.disconnect();
      if (raf) cancelAnimationFrame(raf);
    };
  }, [totalDocs]);

  // Rows: one-shot stagger fade-in when rows container enters view.
  // CSS handles stagger via --row-i custom prop + animation-play-state.
  const [rowsVisible, setRowsVisible] = React.useState(false);
  React.useEffect(() => {
    const el = rowsRef.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) {
        setRowsVisible(true);
        io.disconnect();
      }
    }, { threshold: 0.35 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  return (
    <section
      id="knowledge"
      ref={sectionRef}
      className="kb-archive"
      style={{ minHeight: '140vh', position: 'relative' }}
    >
      <div className="kb-pin">
        {/* Left: chapter title + animated counter */}
        <aside className="kb-side">
          <div className="kb-chapter">
            <span className="kb-chapter-num">02</span>
            <span className="kb-chapter-label">Knowledge Base</span>
          </div>

          <h2 className="kb-title">{t('kb.title')}</h2>

          <div className="kb-counter" ref={counterRef}>
            <span className="kb-counter-num">{displayCount}</span>
            <span className="kb-counter-suffix">articles</span>
          </div>

          <p className="kb-blurb">
            {t('kb.blurb.1')}<br />
            {t('kb.blurb.2')}
          </p>

          <a className="kb-cta" href="/docs">
            <span>{t('kb.cta')}</span>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
              <path d="M5 12h14M13 6l6 6-6 6" />
            </svg>
          </a>
        </aside>

        {/* Right: cascading rows — stagger fade-in on enter view */}
        <div
          className={`kb-rows${rowsVisible ? ' is-visible' : ''}`}
          ref={rowsRef}
        >
          {categories.map((c, i) => {
            const widthPct = (c.count / maxCount) * 100;
            return (
              <a
                key={c.id}
                href={`/docs/${c.id}/`}
                className="kb-row"
                style={{ '--row-i': i }}
              >
                <div className="kb-row-idx">{String(i + 1).padStart(2, '0')}</div>
                <div className="kb-row-main">
                  <div className="kb-row-label">{t('kb.label.' + c.id) !== 'kb.label.' + c.id ? t('kb.label.' + c.id) : c.label}</div>
                  <div className="kb-row-sub">{t('kb.sub.' + c.id)}</div>
                </div>
                <div className="kb-row-bar">
                  <div
                    className="kb-row-bar-fill"
                    style={{ '--bar-target': `${widthPct}%` }}
                  />
                </div>
                <div className="kb-row-count">{c.count}</div>
                <div className="kb-row-arrow">→</div>
              </a>
            );
          })}
        </div>
      </div>
    </section>
  );
}

const kbStyle = document.createElement('style');
kbStyle.textContent = `
  /* .kb-archive background removed — global body::before grid shows through */
  .kb-pin {
    position: sticky; top: 0;
    height: 100vh; min-height: 700px;
    display: grid;
    grid-template-columns: minmax(320px, 1fr) 2fr;
    gap: clamp(40px, 6vw, 100px);
    padding: clamp(50px, 8vh, 90px) clamp(24px, 5vw, 80px);
    align-items: center;
    overflow: hidden;
  }
  .kb-side {
    display: flex; flex-direction: column; gap: 24px;
    align-self: center;
  }
  .kb-chapter {
    display: flex; align-items: baseline; gap: 12px;
    font-family: var(--font-mono); font-size: 11px;
    letter-spacing: 0.18em; text-transform: uppercase;
    color: var(--text-2);
  }
  .kb-chapter-num { color: var(--gold); }
  .kb-title {
    font-family: var(--font-display);
    font-size: clamp(48px, 6vw, 84px);
    font-weight: 400;
    letter-spacing: -0.02em;
    line-height: 1;
    color: var(--text-0);
    margin: 0;
  }
  .kb-counter {
    display: flex; align-items: baseline; gap: 12px;
    margin-top: 8px;
  }
  .kb-counter-num {
    font-family: var(--font-display);
    font-size: clamp(64px, 8vw, 120px);
    font-weight: 300;
    letter-spacing: -0.04em;
    line-height: 1;
    color: var(--gold);
    font-variant-numeric: tabular-nums;
  }
  .kb-counter-suffix {
    font-family: var(--font-mono);
    font-size: 13px;
    letter-spacing: 0.15em;
    text-transform: uppercase;
    color: var(--text-2);
  }
  .kb-blurb {
    font-size: 15px; line-height: 1.7;
    color: var(--text-1);
    margin: 0;
  }
  .kb-cta {
    display: inline-flex; align-items: center; gap: 8px;
    padding: 10px 22px; border-radius: 100px;
    border: 1px solid var(--border);
    color: var(--text-1);
    text-decoration: none;
    font-size: 13px; letter-spacing: 0.02em;
    width: fit-content;
    transition: all 200ms;
  }
  .kb-cta:hover {
    border-color: var(--gold-dim);
    color: var(--gold);
  }

  .kb-rows {
    display: flex; flex-direction: column;
    border-top: 1px solid var(--border-subtle);
  }
  .kb-row {
    display: grid;
    grid-template-columns: 40px 1fr minmax(80px, 200px) 36px 20px;
    gap: 20px;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid var(--border-subtle);
    text-decoration: none;
    color: var(--text-1);
    transition: padding 240ms, color 240ms;
    will-change: opacity, transform;
    animation: kbRowReveal 800ms cubic-bezier(0.22, 1, 0.36, 1) both;
    animation-delay: calc(var(--row-i, 0) * 100ms);
    animation-play-state: paused;
  }
  .kb-rows.is-visible .kb-row {
    animation-play-state: running;
  }
  @keyframes kbRowReveal {
    from { opacity: 0; transform: translateY(18px); }
    to   { opacity: 1; transform: translateY(0); }
  }
  .kb-row:hover {
    color: var(--text-0);
    padding-left: 12px;
  }
  .kb-row:hover .kb-row-arrow { color: var(--gold); transform: translateX(4px); }
  .kb-row:hover .kb-row-bar-fill { background: var(--gold); }
  .kb-row-idx {
    font-family: var(--font-mono); font-size: 11px;
    color: var(--text-2); letter-spacing: 0.08em;
  }
  .kb-row-main { display: flex; flex-direction: column; gap: 2px; }
  .kb-row-label {
    font-size: 15px;
    line-height: 1.2;
    color: var(--text-0);
    letter-spacing: -0.005em;
  }
  .kb-row-sub {
    font-size: 12px;
    line-height: 1.25;
    color: var(--text-2);
  }
  .kb-row-bar {
    height: 1px;
    background: var(--border-subtle);
    overflow: hidden;
  }
  .kb-row-bar-fill {
    height: 100%;
    width: 0;
    background: var(--text-2);
    transition: background 200ms;
    animation: kbBarReveal 900ms cubic-bezier(0.22, 1, 0.36, 1) both;
    animation-delay: calc(var(--row-i, 0) * 100ms + 350ms);
    animation-play-state: paused;
  }
  .kb-rows.is-visible .kb-row-bar-fill {
    animation-play-state: running;
  }
  @keyframes kbBarReveal {
    from { width: 0%; }
    to   { width: var(--bar-target, 0%); }
  }
  .kb-row-count {
    font-family: var(--font-mono); font-size: 13px;
    color: var(--text-1); text-align: right;
    font-variant-numeric: tabular-nums;
  }
  .kb-row-arrow {
    color: var(--text-2);
    font-size: 14px;
    transition: color 200ms, transform 200ms;
  }

  @media (max-width: 880px) {
    .kb-pin {
      grid-template-columns: 1fr;
      height: auto;
      position: static;
      gap: 48px;
    }
    .kb-archive { min-height: auto !important; }
    .kb-row { grid-template-columns: 32px 1fr 36px 20px; }
    .kb-row-bar { display: none; }
  }
`;
document.head.appendChild(kbStyle);

window.CoviaKnowledge = CoviaKnowledge;
