/* Octomatica — Hero (two variants) + animated Telegram thread */

/* ====== Animated Telegram thread (reused in hero A + demo) ====== */
function TelegramThread({ compact = false, autoplay = true }) {
  const d = window.OCTO.thread;
  const beats = d.beats;
  const [shown, setShown] = React.useState(0);   // how many beats revealed
  const [ticks, setTicks] = React.useState(0);   // checklist ticks in bot beat
  const ref = React.useRef(null);
  const started = React.useRef(false);
  const bodyRef = React.useRef(null);

  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));
    });
    // checklist ticks
    const botIdx = beats.findIndex((b) => b.type === "bot");
    const bot = beats[botIdx];
    if (bot) bot.checklist.forEach((_, k) => step(() => setTicks(k + 1), 520));
    timelineRef.current = timeline;
  }, [beats]);
  const timelineRef = React.useRef([]);

  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);
    // Fallback: start even if intersection events never fire (background iframe).
    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);
  };

  return (
    <div className={"tg " + (compact ? "tg-compact" : "")} ref={ref}>
      <div className="tg-head">
        <div className="tg-head-avatar"><Octo kind="center" size={40} /></div>
        <div className="tg-head-meta">
          <strong>{d.header}</strong>
          <span>{d.members}</span>
        </div>
        <button className="tg-replay" onClick={replay} title="Повторить">
          <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"><Octo kind="center" size={26} /></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"><Octo kind="center" size={26} /></div>
              <div className="tg-bubble tg-bot">
                <div className="tg-bot-name">Octomatica</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 && (
                  <div className="tg-attach">
                    <div className="tg-attach-prev">
                      <div className="bnr">
                        <span className="bnr-eyebrow">LAUNCH · 2026</span>
                        <span className="bnr-title">Большой<br/>лонч</span>
                        <span className="bnr-cta">Попробовать →</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">@octomatica</span>{b.text.replace("@octomatica","")}</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"><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 />
          <Octo kind="laptop" size={86} className="hero-float-octo o1 float" />
          <Octo kind="brush" size={70} className="hero-float-octo o2 float" style={{ animationDelay:"-2.4s" }} />
        </div>
      </div>
    </section>
  );
}

/* ====== HERO B — Mascot-forward centered ====== */
function HeroB() {
  const d = window.OCTO.hero;
  const orbit = [
    { kind:"laptop", a:-90, r:230, s:78 },
    { kind:"brush", a:-30, r:255, s:70 },
    { kind:"calendar", a:35, r:235, s:72 },
    { kind:"magnifier", a:120, r:250, s:66 },
    { kind:"gear", a:175, r:230, s:70 },
    { kind:"suit", a:230, r:255, s:72 },
  ];
  return (
    <section className="hero hero-b" id="top">
      <div className="hero-orbs" aria-hidden="true">
        <div className="glow-orb" style={{ width:600, height:600, background:"var(--glow)", top:"6%", left:"50%", transform:"translateX(-50%)", animation:"float 9s ease-in-out infinite" }}/>
      </div>
      <div className="wrap hero-b-inner">
        <span className="hero-badge reveal"><span className="pill-dot live"/>{d.badge}</span>
        <div className="hero-b-stage reveal" data-d="1">
          <div className="hero-b-rings" aria-hidden="true"><span/><span/><span/></div>
          <Octo kind="center" size={172} className="hero-b-center float" />
          {orbit.map((o, i) => {
            const rad = (o.a * Math.PI) / 180;
            const x = Math.cos(rad) * o.r, y = Math.sin(rad) * o.r * 0.62;
            return <Octo key={i} kind={o.kind} size={o.s} className="hero-b-orbit float"
              style={{ left:`calc(50% + ${x}px)`, top:`calc(50% + ${y}px)`, animationDelay:`${-i*0.7}s` }} />;
          })}
        </div>
        <h1 className="display hero-b-title reveal" data-d="2">
          {d.title1} {d.title2} <span className="hero-accent">{d.title3}</span>
        </h1>
        <p className="lead hero-b-sub reveal" data-d="3">{d.sub}</p>
        <div className="hero-cta-row center reveal" data-d="4">
          <a href={window.OCTO.tg} className="btn btn-primary btn-lg"><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="5">{d.micro}</p>
        <ChannelChips className="reveal center" />
      </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, HeroB, HeroStats });
