// All page sections — Header, Hero, Chapters, Cases, Process, Pain, FAQ, Final CTA, Footer.

const { AgentGraph, Pipeline, Vault, TelegramMock, MiniAppScreens } = window.ChapterIllustrations;

// ─────────────────────────────────────────────────────────────
// Reveal-on-scroll hook
// ─────────────────────────────────────────────────────────────
function useReveal(opts = {}) {
  const ref = React.useRef(null);
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (shown) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) { setShown(true); io.disconnect(); }
      });
    }, { threshold: opts.threshold ?? 0.15, rootMargin: opts.rootMargin ?? '0px 0px -80px 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, [shown]);
  return [ref, shown];
}

// ─────────────────────────────────────────────────────────────
// Header
// ─────────────────────────────────────────────────────────────
function HeroChatInput({ t, onSend }) {
  const [value, setValue] = React.useState('');
  const submit = (e) => {
    e.preventDefault();
    const v = value.trim();
    if (!v) return;
    onSend(v);
    setValue('');
  };
  return (
    <form className="hero-chat-input" onSubmit={submit}>
      <input
        value={value}
        onChange={(e) => setValue(e.target.value)}
        placeholder={t.chat.placeholder}
      />
      <button type="submit" className={value ? 'gradient' : ''} aria-label="send">
        <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
          <path d="M3 8 L13 8 M8 3 L13 8 L8 13" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </button>
    </form>
  );
}

function Header({ lang, setLang, openChat, t }) {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 30);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <header className={'header' + (scrolled ? ' scrolled' : '')} data-screen-label="Header">
      <a href="#top" className="brand">
        <span className="mono-mark">T/</span>
        <span>{t.brand}</span>
      </a>
      <nav className="nav">
        <a href="#services">{t.nav.services}</a>
        <a href="#cases">{t.nav.cases}</a>
        <a href="#process">{t.nav.process}</a>
        <a href="#faq">{t.nav.faq}</a>
      </nav>
      <div className="header-right">
        <div className="lang-toggle" role="tablist">
          <button className={lang === 'ru' ? 'active' : ''} onClick={() => setLang('ru')}>RU</button>
          <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
        </div>
        <button className="btn-cta gradient" onClick={() => openChat()}>
          <span className="pulse"/>
          <span className="long">{t.cta_open_chat_long}</span>
        </button>
      </div>
    </header>
  );
}

// ─────────────────────────────────────────────────────────────
// Hero — wordmark carved by canvas, small tagline below
// ─────────────────────────────────────────────────────────────
function Hero({ t, brand, brandDisplay, openChat, heroIntensity }) {
  const HeroASCII = window.HeroASCII;
  return (
    <section id="top" className="hero" data-screen-label="Hero">
      <div className="hero-canvas">
        <HeroASCII logoText={brandDisplay} intensity={heroIntensity} />
      </div>
      <div className="hero-vignette"/>

      {/* Corner stamps */}
      <div style={{
        position: 'absolute', top: 100, left: 'var(--pad-x)', zIndex: 2,
        fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em',
        textTransform: 'uppercase', color: 'var(--fg-dim)',
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--fg)' }}/>
        {t.hero.eyebrow}
      </div>
      <div style={{
        position: 'absolute', top: 100, right: 'var(--pad-x)', zIndex: 2,
        fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em',
        textTransform: 'uppercase', color: 'var(--fg-dim)',
        textAlign: 'right',
      }}>
        v.2026.05 · build {(window.location.hostname || 'local').slice(0, 12)}
      </div>

      <div className="hero-overlay">
        <div className="hero-center"/>
        <div className="hero-bottom">
          <div className="hero-tagline">
            <div className="hero-eyebrow">
              <span style={{ fontFamily: 'var(--font-mono)', opacity: 0.7 }}>{'// slogan'}</span>
            </div>
            <p className="hero-slogan">
              {t.hero.slogan_pre}{' '}
              <b>{t.hero.slogan_em}</b>{' '}
              {t.hero.slogan_post}
            </p>
            <div className="hero-chat-row">
              <HeroChatInput t={t} onSend={(text) => openChat({ prefill: text })} />
              <div className="hero-chat-quick">
                {(t.chat.quickreplies_default || []).map((q) => (
                  <button key={q} onClick={() => openChat({ prefill: q })}>{q}</button>
                ))}
              </div>
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6, color: 'var(--muted)', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
            <div>scroll ↓</div>
            <div style={{ width: 1, height: 40, background: 'var(--fg-dim)', animation: 'scroll-hint 2.4s ease-in-out infinite' }}/>
          </div>
        </div>
        <div className="stack-strip">
          <div className="stack-strip-track">
            {[...t.hero.stack, ...t.hero.stack].map((s, i) => <span key={i}>{s}</span>)}
          </div>
        </div>
      </div>
      <style>{`
        @keyframes scroll-hint {
          0%, 100% { transform: scaleY(0.3); transform-origin: top; opacity: 0.4; }
          50% { transform: scaleY(1); transform-origin: top; opacity: 1; }
        }
      `}</style>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────
// Chapters
// ─────────────────────────────────────────────────────────────
function Chapter({ chapter, index, illustration, t, openChat }) {
  const [ref, shown] = useReveal();
  return (
    <div ref={ref} className={'chapter ' + (shown ? 'fade-up in' : 'fade-up')}>
      <div className="chapter-left">
        <div className="chapter-num">chapter {chapter.num} / 05</div>
        <h2>{chapter.title}</h2>
        <div className="chapter-text">
          <p>{chapter.text1}</p>
          <p>{chapter.text2}</p>
        </div>
        <ul className="chapter-bullets">
          {chapter.bullets.map((b, i) => <li key={i}>{b}</li>)}
        </ul>
        <div className="chapter-meta">
          <div className="price"><span>цена </span>{chapter.price}</div>
          <div className="price"><span>срок </span>{chapter.timeline}</div>
          <button className="btn-link" style={{ marginLeft: 'auto' }} onClick={() => openChat({ scenarioHint: chapter.num })}>
            {t.chapter_cta} →
          </button>
        </div>
      </div>
      <div className="chapter-right">
        {illustration}
      </div>
    </div>
  );
}

function ServicesSection({ t, openChat }) {
  const [ref, shown] = useReveal();
  const illustrations = [
    <AgentGraph key="01" />,
    <Pipeline key="02" />,
    <Vault key="03" />,
    <TelegramMock key="04" />,
    <MiniAppScreens key="05" />,
  ];
  return (
    <section id="services" className="section" data-screen-label="Services">
      <div ref={ref} className={shown ? 'fade-up in' : 'fade-up'} style={{ marginBottom: 'clamp(64px, 10vh, 120px)' }}>
        <div className="eyebrow">{t.chaptersHeader.eyebrow}</div>
        <h2 className="h-mono" style={{
          fontWeight: 600,
          fontSize: 'clamp(34px, 4.8vw, 80px)',
          lineHeight: 0.98,
          letterSpacing: '-0.03em',
          margin: '0 0 24px',
          maxWidth: 1100,
          textWrap: 'balance',
        }}>
          {t.chaptersHeader.title}
        </h2>
        <p style={{ fontSize: 17, color: 'var(--fg-dim)', maxWidth: 580, lineHeight: 1.55, margin: 0 }}>
          {t.chaptersHeader.sub}
        </p>
      </div>
      {t.chapters.map((ch, i) => (
        <Chapter key={ch.num} chapter={ch} index={i} illustration={illustrations[i]} t={t} openChat={openChat} />
      ))}
    </section>
  );
}

// ─────────────────────────────────────────────────────────────
// Cases
// ─────────────────────────────────────────────────────────────
function CasesSection({ t }) {
  const [headRef, headShown] = useReveal();
  return (
    <section id="cases" className="cases" data-screen-label="Cases">
      <div ref={headRef} className={'cases-head ' + (headShown ? 'fade-up in' : 'fade-up')}>
        <div>
          <div className="eyebrow">{t.cases.eyebrow}</div>
          <h2>{t.cases.title}</h2>
        </div>
        <div style={{ maxWidth: 380, color: 'var(--fg-dim)', fontSize: 14, lineHeight: 1.5 }}>{t.cases.sub}</div>
      </div>
      <div className="cases-rail">
        {t.cases.list.map((c, i) => (
          <article className="case-card" key={c.id}>
            <div className="case-id">CASE / {String(i+1).padStart(2,'0')} · {c.id}</div>
            <div>
              <div className="case-metric">{c.metric}</div>
              <div className="case-metric-label">{c.metricLabel}</div>
              <div className="case-desc">{c.desc}</div>
            </div>
            <div>
              <div className="case-tags">
                {c.tags.map((tag) => <span className="tag" key={tag}>{tag}</span>)}
              </div>
              <div className="case-timeline">
                <div className="step"><span>{t.cases.step_before}</span>Ручная работа · ошибки</div>
                <div className="step"><span>{t.cases.step_during}</span>2–4 недели</div>
                <div className="step now"><span>{t.cases.step_after}</span>{c.metric}</div>
              </div>
              <div style={{ marginTop: 24, fontSize: 12, color: 'var(--fg-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.04em' }}>
                {c.client}
              </div>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────
// Process
// ─────────────────────────────────────────────────────────────
function ProcessSection({ t }) {
  const [ref, shown] = useReveal();
  const [activeStep, setActiveStep] = React.useState(0);
  const stepRefs = React.useRef([]);
  React.useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          const idx = stepRefs.current.indexOf(e.target);
          if (idx >= 0) setActiveStep(idx);
        }
      });
    }, { threshold: 0.5 });
    stepRefs.current.forEach(el => el && io.observe(el));
    return () => io.disconnect();
  }, []);
  return (
    <section id="process" className="section process" data-screen-label="Process">
      <div className="process-grid">
        <div className="process-head">
          <div className="eyebrow">{t.process.eyebrow}</div>
          <h2 ref={ref} className={shown ? 'fade-up in' : 'fade-up'}>{t.process.title}</h2>
          <p>{t.process.sub}</p>
        </div>
        <div className="process-steps">
          {t.process.steps.map((s, i) => (
            <div key={s.num}
                 ref={el => stepRefs.current[i] = el}
                 className="process-step">
              <div className={'step-num ' + (i === activeStep ? 'active' : '')}>{s.num}</div>
              <div className="step-body">
                <h3>{s.title}</h3>
                <p>{s.text}</p>
                <div className="step-tags">
                  {s.tags.map((tag) => <span className="tag" key={tag}>{tag}</span>)}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────
// Pain
// ─────────────────────────────────────────────────────────────
function PainSection({ t, openChat }) {
  const [ref, shown] = useReveal();
  return (
    <section className="section pain" data-screen-label="Pain points">
      <div ref={ref} className={shown ? 'fade-up in' : 'fade-up'}>
        <div className="eyebrow">{t.pain.eyebrow}</div>
        <h2>{t.pain.title}</h2>
        <p className="pain-sub">{t.pain.sub}</p>
      </div>
      <div className="pain-grid">
        {t.pain.phrases.map((p, i) => (
          <button key={i} onClick={() => openChat({ prefill: p })}>
            <span style={{ position: 'relative' }}>«{p}»</span>
            <span className="arrow">Открыть в чате <span aria-hidden>→</span></span>
          </button>
        ))}
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────
// FAQ
// ─────────────────────────────────────────────────────────────
function FAQSection({ t }) {
  const [open, setOpen] = React.useState(0);
  const [ref, shown] = useReveal();
  return (
    <section id="faq" className="section faq" data-screen-label="FAQ">
      <div ref={ref} className={shown ? 'fade-up in' : 'fade-up'}>
        <div className="eyebrow">{t.faq.eyebrow}</div>
        <h2>{t.faq.title}</h2>
      </div>
      <div className="faq-list">
        {t.faq.items.map((item, i) => (
          <div key={i} className={'faq-item ' + (open === i ? 'open' : '')}>
            <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
              <span><span style={{ fontFamily: 'var(--font-mono)', fontSize: '0.6em', letterSpacing: '0.08em', color: 'var(--muted)', marginRight: 16 }}>{String(i+1).padStart(2,'0')}</span>{item.q}</span>
              <span className="marker">+</span>
            </button>
            <div className="faq-a"><div className="faq-a-inner">{item.a}</div></div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────
// Final CTA
// ─────────────────────────────────────────────────────────────
function FinalCTA({ t, ChatEmbed }) {
  const [ref, shown] = useReveal();
  return (
    <section className="section cta-final" data-screen-label="Final CTA">
      <div className="cta-final-inner">
        <div ref={ref} className={shown ? 'fade-up in' : 'fade-up'}>
          <div className="eyebrow">{t.cta.eyebrow}</div>
          <h2>
            {t.cta.title_pre}{' '}
            <b>{t.cta.title_em}</b>{' '}
            {t.cta.title_post}
          </h2>
          <p>{t.cta.sub}</p>
          <div className="cta-final-meta">
            {t.cta.meta.map((m, i) => (
              <div key={i}><span className="dot"/> {m.label}</div>
            ))}
          </div>
        </div>
        <div>
          <ChatEmbed inline />
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────
// Footer
// ─────────────────────────────────────────────────────────────
function Footer({ t }) {
  return (
    <footer className="footer" data-screen-label="Footer">
      <div className="brand-block">
        <div className="brand"><span className="mono-mark">T/</span><span>{t.brand}</span></div>
        <p>{t.footer.tag}</p>
      </div>
      {t.footer.cols.map((col) => (
        <div key={col.title}>
          <h4>{col.title}</h4>
          <ul>
            {col.items.map((it) => <li key={it}><a href="#">{it}</a></li>)}
          </ul>
        </div>
      ))}
      <div className="footer-bottom">
        <span>{t.footer.copyright}</span>
        <span style={{ display: 'inline-flex', gap: 18 }}>
          <span>BUILT WITH CLAUDE · 2026</span>
          <span>GMT+3</span>
        </span>
      </div>
    </footer>
  );
}

window.Sections = { Header, Hero, ServicesSection, CasesSection, ProcessSection, PainSection, FAQSection, FinalCTA, Footer };
