// COVIA Pilgrim — Manifesto Typewriter
// Dedicated moment for the philosophical declaration.
// No cards, no CTA — the manifesto itself IS the content.
// Typewriter triggers on IO entry; click anywhere or ↓/Space/Enter to skip.

function CoviaPilgrim() {
  const { lang, t } = useLang();
  const sectionRef = React.useRef(null);
  const [typedCount, setTypedCount] = React.useState(0);
  const [started, setStarted] = React.useState(false);
  const [isComplete, setIsComplete] = React.useState(false);

  const paragraphs = Array.from({ length: 11 }, (_, i) => t('pilgrim.para.' + i));
  const fullText = paragraphs.join('\n');

  // Reset typewriter on language change
  const prevLangRef = React.useRef(lang);
  React.useEffect(() => {
    if (prevLangRef.current !== lang) {
      prevLangRef.current = lang;
      setTypedCount(0);
      setIsComplete(false);
      if (started) setTypedCount(0);
    }
  }, [lang, started]);

  // Start typewriter when section enters view
  React.useEffect(() => {
    const el = sectionRef.current;
    if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {
        setStarted(true);
        io.disconnect();
      }
    }, { threshold: 0.15 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  // Typewriter animation loop — per-char delay with punctuation pauses
  React.useEffect(() => {
    if (!started || isComplete) return;
    let cancelled = false;
    let timer = null;
    let idx = typedCount;

    const tick = () => {
      if (cancelled) return;
      if (idx >= fullText.length) {
        setIsComplete(true);
        return;
      }
      const ch = fullText[idx];
      idx++;
      setTypedCount(idx);

      let delay = 60;
      if ('。？！'.includes(ch)) delay = 520;
      else if ('，、；：'.includes(ch)) delay = 220;
      else if (ch === '\n') delay = 820;

      timer = setTimeout(tick, delay);
    };
    timer = setTimeout(tick, 1100); // lead-in pause before first char
    return () => {
      cancelled = true;
      if (timer) clearTimeout(timer);
    };
  }, [started, isComplete, fullText]);

  // Skip — completes immediately
  const skip = React.useCallback(() => {
    if (isComplete) return;
    setTypedCount(fullText.length);
    setIsComplete(true);
  }, [isComplete, fullText]);

  // Keyboard: ↓ / Space / Enter skips when section is in view
  React.useEffect(() => {
    if (!started || isComplete) return;
    const onKey = (e) => {
      const rect = sectionRef.current?.getBoundingClientRect();
      if (!rect) return;
      const mid = window.innerHeight * 0.5;
      if (rect.top > mid || rect.bottom < mid) return;
      if (e.key === 'ArrowDown' || e.key === ' ' || e.key === 'Enter' || e.key === 'Escape') {
        e.preventDefault();
        skip();
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [started, isComplete, skip]);

  // Render typed portion as paragraphs
  const typedText = fullText.slice(0, typedCount);
  const typedParas = typedText.split('\n');

  return (
    <section
      id="pilgrim"
      ref={sectionRef}
      className="pilgrim"
      style={{ minHeight: '100vh', position: 'relative' }}
      onClick={!isComplete ? skip : undefined}
    >
      {React.createElement('canvas', {
        className: 'pilgrim-pano',
        'aria-hidden': 'true',
        ref: function(el) {
          if (!el || el._panoInit) return;
          el._panoInit = true;
          if (typeof CoviaPanorama !== 'undefined') {
            new CoviaPanorama(el, '/landing/assets/covia-360.png');
          }
        },
      })}
      <div className="pilgrim-pin">
        <div className="pilgrim-chapter">
          <span className="pilgrim-chapter-num">04</span>
          <span className="pilgrim-chapter-label">{t('pilgrim.chapter')}</span>
        </div>

        <div className="pilgrim-manifesto">
          <p className="pilgrim-annotation">
            {t('pilgrim.annotation')}
          </p>

          <div className="pilgrim-open-mark">「</div>

          <div className="pilgrim-body">
            {typedParas.map((para, i) => (
              <p key={i} className="pilgrim-para">
                {para}
                {i === typedParas.length - 1 && !isComplete && <span className="pilgrim-cursor" />}
              </p>
            ))}
          </div>

          <div className={'pilgrim-closing' + (isComplete ? ' is-shown' : '')}>
            <div className="pilgrim-close-mark">」</div>
            <div className="pilgrim-attr">{t('pilgrim.attr')}</div>
          </div>
        </div>

        {isComplete ? (
          <a
            href="/docs/insights/"
            className="pilgrim-hint is-done pilgrim-hint-link"
            onClick={(e) => e.stopPropagation()}
          >
            {t('pilgrim.hint.continue')}
          </a>
        ) : (
          <div className="pilgrim-hint">{t('pilgrim.hint.skip')}</div>
        )}
      </div>
    </section>
  );
}

// Footer (unchanged behavior)
function CoviaFooter() {
  const { t } = useLang();
  return (
    <footer className="pilgrim-footer">
      <div className="pilgrim-footer-inner">
        <div className="pilgrim-footer-brand">
          <div className="pilgrim-footer-mark"><img src="/img/favicon.ico" alt="COVIA" style={{width: 16, height: 16}} /></div>
          <span>COVIA</span>
        </div>
        <div className="pilgrim-footer-line">{t('footer.copyright')}</div>
        <div className="pilgrim-footer-social">
          {[
            { label: 'LINE',     url: 'https://social-plugins.line.me/lineit/share?url=https://covia.io/' },
            { label: 'X',        url: 'https://twitter.com/intent/tweet?url=https://covia.io/' },
            { label: 'Facebook', url: 'https://www.facebook.com/sharer/sharer.php?u=https://covia.io/' },
            { label: 'Telegram', url: 'https://t.me/share/url?url=https://covia.io/' },
            { label: 'Threads',  url: 'https://www.threads.net/intent/post?text=https://covia.io/' },
          ].map(s => (
            <a key={s.label} href={s.url} target="_blank" rel="noopener noreferrer">{s.label}</a>
          ))}
        </div>
      </div>
    </footer>
  );
}

const pilgrimStyle = document.createElement('style');
pilgrimStyle.textContent = `
  .pilgrim {
    position: relative;
    overflow: hidden;
  }

  /* 360 panorama background (Three.js canvas) */
  .pilgrim-pano {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
    opacity: 0.1;
    pointer-events: none;
  }
  .pilgrim { cursor: grab; user-select: none; -webkit-user-select: none; }
  .pilgrim:active { cursor: grabbing; }

  .pilgrim-pin {
    position: relative;
    z-index: 1;
    min-height: 100vh;
    display: grid;
    place-items: center;
    padding: clamp(56px, 8vh, 96px) clamp(24px, 5vw, 80px);
  }
  .pilgrim-chapter {
    position: absolute;
    top: clamp(32px, 5vh, 56px);
    left: clamp(24px, 5vw, 80px);
    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);
  }
  .pilgrim-chapter-num { color: var(--gold); }

  .pilgrim-manifesto {
    max-width: 720px;
    width: 100%;
    position: relative;
  }
  .pilgrim-annotation {
    font-family: var(--font-mono);
    font-size: 10.5px;
    color: var(--text-2);
    opacity: 0.52;
    letter-spacing: 0.04em;
    text-align: center;
    margin: 0 0 28px;
    line-height: 1.5;
    text-wrap: balance;
  }
  .pilgrim-open-mark, .pilgrim-close-mark {
    font-family: var(--font-display);
    font-size: clamp(48px, 5.2vw, 76px);
    color: var(--gold);
    opacity: 0.24;
    line-height: 0.6;
    user-select: none;
    pointer-events: none;
  }
  .pilgrim-open-mark { text-align: left; margin-bottom: -6px; }
  .pilgrim-close-mark { text-align: right; margin-top: -2px; }

  .pilgrim-body { min-height: 30vh; }
  .pilgrim-para {
    font-family: var(--font-body);
    font-size: clamp(15px, 1.35vw, 17px);
    line-height: 1.9;
    color: var(--text-1);
    letter-spacing: 0.02em;
    margin: 0 0 18px;
    text-wrap: pretty;
  }
  .pilgrim-para:last-child { margin-bottom: 0; }
  .pilgrim-cursor {
    display: inline-block;
    width: 2px; height: 1.1em;
    background: var(--gold);
    vertical-align: text-bottom;
    margin-left: 3px;
    animation: pilgrimBlink 900ms steps(2) infinite;
  }
  @keyframes pilgrimBlink { 50% { opacity: 0; } }

  .pilgrim-closing {
    opacity: 0;
    transition: opacity 700ms ease-out 180ms;
    display: flex; flex-direction: column;
    align-items: flex-end; gap: 6px;
    margin-top: 12px;
  }
  .pilgrim-closing.is-shown { opacity: 1; }
  .pilgrim-attr {
    font-family: var(--font-mono); font-size: 11px;
    color: var(--text-2); letter-spacing: 0.12em;
  }

  .pilgrim-hint {
    position: absolute;
    bottom: clamp(20px, 4vh, 40px);
    left: 50%; transform: translateX(-50%);
    font-family: var(--font-mono); font-size: 10.5px;
    color: var(--text-2); letter-spacing: 0.18em; text-transform: uppercase;
    opacity: 0.55;
    transition: opacity 400ms, color 400ms;
    white-space: nowrap;
    pointer-events: none;
  }
  .pilgrim-hint.is-done {
    opacity: 0.85;
    color: var(--gold);
    animation: pilgrimHintBob 1.8s ease-in-out infinite;
  }
  a.pilgrim-hint-link {
    pointer-events: auto;
    text-decoration: none;
    padding: 6px 14px;
    border: 1px solid oklch(0.78 0.16 75 / 0.3);
    border-radius: 100px;
    transition: border-color 200ms, background 200ms, opacity 200ms;
  }
  a.pilgrim-hint-link:hover {
    opacity: 1;
    border-color: var(--gold);
    background: oklch(0.78 0.16 75 / 0.08);
  }
  @keyframes pilgrimHintBob {
    0%, 100% { transform: translate(-50%, 0); }
    50% { transform: translate(-50%, 4px); }
  }

  .pilgrim-footer {
    border-top: 1px solid var(--border-subtle);
    background: var(--surface-0);
  }
  .pilgrim-footer-inner {
    max-width: 1200px;
    margin: 0 auto;
    padding: 36px clamp(20px, 5vw, 80px);
    display: flex; flex-direction: column; align-items: center;
    gap: 16px; text-align: center;
  }
  .pilgrim-footer-brand {
    display: flex; align-items: center; gap: 10px;
    font-family: var(--font-display); font-size: 14px;
    letter-spacing: 0.05em; color: var(--text-1);
  }
  .pilgrim-footer-mark {
    width: 24px; height: 24px; border-radius: 6px;
    background: linear-gradient(135deg, var(--gold), var(--gold-dim));
    display: grid; place-items: center;
    font-size: 12px; font-weight: 700; color: var(--surface-0);
  }
  .pilgrim-footer-line {
    font-size: 12px; color: var(--text-2);
  }
  .pilgrim-footer-social { display: flex; gap: 16px; }
  .pilgrim-footer-social a {
    font-family: var(--font-mono); font-size: 11px;
    color: var(--text-2); letter-spacing: 0.05em;
    text-decoration: none; transition: color 200ms;
  }
  .pilgrim-footer-social a:hover { color: var(--gold); }

  @media (max-width: 768px) {
    .pilgrim-manifesto { max-width: 100%; }
    .pilgrim-chapter {
      top: clamp(20px, 3vh, 32px);
      left: clamp(16px, 4vw, 32px);
    }
  }
`;
document.head.appendChild(pilgrimStyle);

window.CoviaPilgrim = CoviaPilgrim;
window.CoviaFooter = CoviaFooter;
