/* Octodus clone — Hero A + animated Telegram thread */

function TelegramThread({ compact = false, autoplay = true }) {
  const d = window.OCTO.thread;
  const beats = d.beats;
  const [shown, setShown] = React.useState(0);
  const [ticks, setTicks] = React.useState(0);
  const ref = React.useRef(null);
  const started = React.useRef(false);
  const bodyRef = React.useRef(null);
  const timelineRef = React.useRef([]);

  const run = React.useCallback(() => {
    if (started.current) return; started.current = true;
    const timeline = [];
    let acc = 400;
    const step = (fn, gap) => { timeline.push(setTimeout(fn, acc)); acc += gap; };
    beats.forEach((b, i) => {
      step(() => setShown(i + 1), b.type === "typing" ? 1300 : (b.type === "bot" ? 600 : 950));
    });
    const botIdx = beats.findIndex((b) => b.type === "bot");
    const bot = beats[botIdx];
    if (bot && bot.checklist) bot.checklist.forEach((_, k) => step(() => setTicks(k + 1), 520));
    timelineRef.current = timeline;
  }, [beats]);

  React.useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver((es) => {
      es.forEach((e) => { if (e.isIntersecting && autoplay) run(); });
    }, { threshold: 0.35 });
    io.observe(el);
    const fb = setTimeout(() => { if (autoplay) run(); }, 2600);
    return () => { io.disconnect(); clearTimeout(fb); timelineRef.current.forEach(clearTimeout); };
  }, [run, autoplay]);

  React.useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [shown, ticks]);

  const replay = () => {
    timelineRef.current.forEach(clearTimeout);
    started.current = false; setShown(0); setTicks(0);
    setTimeout(run, 120);
  };

  const botIdx = beats.findIndex((b) => b.type === "bot");

  return (
    <div className={"tg " + (compact ? "tg-compact" : "")} ref={ref}>
      <div className="tg-head">
        <div className="tg-head-avatar"><OctoGlyph size={28} color="var(--accent)" /></div>
        <div className="tg-head-meta">
          <strong>{d.header}</strong>
          <span>{d.members}</span>
        </div>
        <button type="button" className="tg-replay" title="Replay"
          onMouseDown={(e) => e.preventDefault()} onClick={replay}>
          <Icon name="play" size={13} />
        </button>
      </div>
      <div className="tg-body" ref={bodyRef}>
        {beats.slice(0, shown).map((b, i) => {
          if (b.type === "typing") return (
            <div className="tg-row bot" key={i}>
              <div className="tg-av"><OctoGlyph size={22} color="var(--accent)" /></div>
              <div className="tg-bubble tg-typing"><span/><span/><span/></div>
            </div>
          );
          if (b.type === "bot") return (
            <div className="tg-row bot" key={i}>
              <div className="tg-av"><OctoGlyph size={22} color="var(--accent)" /></div>
              <div className="tg-bubble tg-bot">
                <div className="tg-bot-name">Octodus</div>
                <ul className="tg-check">
                  {b.checklist.map((c, k) => (
                    <li key={k} className={k < ticks ? "on" : ""}>
                      <span className="tg-tick"><Icon name="check" size={12} stroke={2.4} /></span>{c}
                    </li>
                  ))}
                </ul>
                {ticks >= b.checklist.length && b.attach && (
                  <div className="tg-attach">
                    <div className="tg-attach-prev">
                      <div className="bnr">
                        <span className="bnr-eyebrow">LAUNCH · 2026</span>
                        <span className="bnr-title">Big<br/>launch</span>
                        <span className="bnr-cta">Try it →</span>
                      </div>
                    </div>
                    <div className="tg-attach-meta">
                      <strong>{b.attach.name}</strong>
                      <span>{b.attach.meta}</span>
                    </div>
                  </div>
                )}
              </div>
            </div>
          );
          const isCmd = b.type === "cmd";
          return (
            <div className={"tg-row " + (b.type === "user" || isCmd ? "user" : "")} key={i}>
              <div className="tg-av" style={{ background: b.color }}>{b.author[0]}</div>
              <div className={"tg-bubble " + (isCmd ? "tg-cmd" : "")}>
                <div className="tg-name" style={{ color: b.color }}>{b.author} <em>· {b.role}</em></div>
                {isCmd
                  ? <span><span className="tg-mention">@octodus</span>{b.text.replace("@octodus","")}</span>
                  : b.text}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ---- Hero A — Telegram-native split ---- */
function HeroA() {
  const d = window.OCTO.hero;
  return (
    <section className="hero hero-a" id="top">
      <div className="hero-orbs" aria-hidden="true">
        <div className="glow-orb" style={{ width:520, height:520, background:"var(--glow)", top:-160, right:-120, animation:"drift1 20s ease-in-out infinite" }}/>
        <div className="glow-orb" style={{ width:380, height:380, background:"var(--glow-2)", bottom:-120, left:-100, animation:"drift2 24s ease-in-out infinite" }}/>
      </div>
      <div className="wrap wrap-wide hero-a-grid">
        <div className="hero-a-copy">
          <span className="hero-badge reveal"><span className="pill-dot live"/>{d.badge}</span>
          <h1 className="display hero-title reveal" data-d="1">
            {d.title1}<br/>{d.title2}<br/><span className="hero-accent">{d.title3}</span>
          </h1>
          <p className="lead hero-sub reveal" data-d="2">{d.sub}</p>
          <div className="hero-cta-row reveal" data-d="3">
            <a href={window.OCTO.tg} className="btn btn-primary btn-lg" target="_blank" rel="noopener">
              <Icon name="tg" size={18} />{d.cta}
            </a>
            <a href="#how" className="btn btn-ghost btn-lg">{d.ctaSec}</a>
          </div>
          <p className="hero-micro muted reveal" data-d="4">{d.micro}</p>
          <p className="hero-sec reveal" data-d="4"><Icon name="shield" size={14} />{d.sec}</p>
          <ChannelChips className="reveal" />
        </div>
        <div className="hero-a-demo reveal" data-d="2">
          <TelegramThread />
        </div>
      </div>
    </section>
  );
}

function HeroStats() {
  const s = window.OCTO.hero.stats;
  return (
    <div className="wrap wrap-wide">
      <div className="hero-stats reveal" data-d="3">
        {s.map((x, i) => (
          <div className="hero-stat" key={i}>
            <div className="hero-stat-val">{x.value}</div>
            <div className="hero-stat-lbl">{x.label}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { TelegramThread, HeroA, HeroStats });
