/* ===== Mentium interactive hero demo =====
   A faux article you can actually select text in.
   Selecting text raises a Mentium pill → opens an AI answer popover
   that "reads the page" and cites sources. Auto-plays once on load. */

const { useState, useRef, useEffect, useCallback } = React;

// Canned, context-aware answers keyed by phrase fragments found in the article.
const KNOWN = [
  {
    match: ["геомагнитная буря", "геомагнит", "geomagnetic storm", "geomagnetic"],
    answer:
      "Геомагнитная буря — это временное возмущение магнитосферы Земли, вызванное потоками заряженных частиц от Солнца. По контексту страницы это причина северных сияний: чем сильнее буря, тем дальше от полюсов можно увидеть свечение.",
    sources: ["Эта страница", "NOAA · Космическая погода", "ESA"],
  },
  {
    match: ["солнечный ветер", "заряженных частиц", "частицы от солнца", "solar wind", "charged particles", "particles from the sun"],
    answer:
      "Солнечный ветер — это поток заряженных частиц, который постоянно идёт от Солнца. Когда он сталкивается с магнитным полем Земли, частицы направляются к полюсам и заставляют верхние слои атмосферы светиться.",
    sources: ["Эта страница", "NASA · Гелиофизика"],
  },
];

const FALLBACK = (sel, topic) =>
  `Коротко о фрагменте «${sel}»: Mentium смотрит на окружающий контекст статьи про ${topic}, объясняет смысл простыми словами и показывает источники — без перехода в другую вкладку.`;

function pickAnswer(sel) {
  const low = sel.toLowerCase();
  for (const k of KNOWN) {
    if (k.match.some((m) => low.includes(m))) return k;
  }
  return { answer: FALLBACK(sel, "северное сияние"), sources: ["Эта страница", "Поиск в вебе"] };
}

function HeroDemo() {
  const wrapRef = useRef(null);
  const artRef = useRef(null);
  const [pill, setPill] = useState(null); // {x,y,text}
  const [pop, setPop] = useState(null); // {x,y,text,sources}
  const [typed, setTyped] = useState("");
  const [thinking, setThinking] = useState(false);
  const typer = useRef(null);
  const played = useRef(false);
  const sourcesRef = useRef(null);

  useEffect(() => {
    if (!thinking && typed.length > 30) {
      requestAnimationFrame(() => animateDemoSources(sourcesRef.current));
    }
  }, [thinking, typed.length > 30]);

  const clearAll = useCallback(() => {
    setPill(null);
    setPop(null);
    setTyped("");
    setThinking(false);
    if (typer.current) clearInterval(typer.current);
  }, []);

  const streamAnswer = useCallback((text) => {
    setThinking(true);
    setTyped("");
    if (typer.current) clearInterval(typer.current);
    setTimeout(() => {
      setThinking(false);
      let i = 0;
      typer.current = setInterval(() => {
        i += Math.max(1, Math.round(text.length / 90));
        setTyped(text.slice(0, i));
        if (i >= text.length) {
          setTyped(text);
          clearInterval(typer.current);
        }
      }, 18);
    }, 620);
  }, []);

  const openFor = useCallback(
    (text, rect) => {
      const wrap = wrapRef.current.getBoundingClientRect();
      const a = pickAnswer(text);
      const px = Math.min(
        Math.max(rect.left - wrap.left + rect.width / 2 - 168, 12),
        wrap.width - 348
      );
      const py = rect.bottom - wrap.top + 12;
      setPill(null);
      setPop({ x: px, y: py, text, sources: a.sources });
      streamAnswer(a.answer);
    },
    [streamAnswer]
  );

  const onSelect = useCallback(() => {
    const selection = window.getSelection();
    const text = selection ? selection.toString().trim() : "";
    if (!text || text.length < 3) {
      return;
    }
    // ensure selection is inside the article
    if (!artRef.current) return;
    const anchor = selection.anchorNode;
    if (!anchor || !artRef.current.contains(anchor)) return;
    const range = selection.getRangeAt(0);
    const rect = range.getBoundingClientRect();
    const wrap = wrapRef.current.getBoundingClientRect();
    setPop(null);
    setPill({
      x: Math.min(Math.max(rect.left - wrap.left + rect.width / 2 - 70, 8), wrap.width - 148),
      y: rect.top - wrap.top - 52,
      text,
      rect,
    });
  }, []);

  // Auto-play once
  useEffect(() => {
    if (played.current) return;
    played.current = true;
    const t = setTimeout(() => {
      const el = artRef.current && artRef.current.querySelector("[data-auto]");
      if (!el) return;
      const range = document.createRange();
      range.selectNodeContents(el);
      const sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(range);
      const rect = range.getBoundingClientRect();
      const wrap = wrapRef.current.getBoundingClientRect();
      setPill({
        x: Math.min(Math.max(rect.left - wrap.left + rect.width / 2 - 70, 8), wrap.width - 148),
        y: rect.top - wrap.top - 52,
        text: el.textContent.trim(),
        rect,
      });
      // auto-open after a pause
      setTimeout(() => {
        openFor(el.textContent.trim(), range.getBoundingClientRect());
        sel.removeAllRanges();
      }, 1300);
    }, 1100);
    return () => clearTimeout(t);
  }, [openFor]);

  return (
    <div className="demo-frame">
      {/* browser chrome */}
      <div className="chrome">
        <div className="dots"><span></span><span></span><span></span></div>
        <div className="url">
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" aria-hidden="true">
            <path d="M12 2a10 10 0 100 20 10 10 0 000-20zM2 12h20M12 2c2.5 2.7 2.5 17.3 0 20M12 2c-2.5 2.7-2.5 17.3 0 20"
              stroke="currentColor" strokeWidth="1.6" />
          </svg>
          journal.example/severnoe-siyanie
        </div>
        <div className="ext-chip" title="Mentium включён">
          <span className="ext-dot"></span>Mentium
        </div>
      </div>

      <div className="demo-body" ref={wrapRef}>
        <article className="fake-article" ref={artRef} onMouseUp={onSelect}>
          <p className="fa-kicker">НАУКА · КРАТКИЙ ГИД</p>
          <h3 className="fa-title">Почему ночное небо вспыхивает цветом</h3>
          <p className="fa-p">
            Время от времени полярное небо вспыхивает зелёными и алыми
            волнами света. Это явление вызывает{" "}
            <span data-auto className="fa-key">геомагнитная буря</span> — резкое
            возмущение магнитного поля, которое окружает нашу планету.
          </p>
          <p className="fa-p">
            Причина приходит от Солнца. Поток <span className="fa-key">заряженных частиц</span> летит
            через космос, а у Земли магнитное поле направляет его к полюсам.
            Там частицы заставляют верхние слои атмосферы светиться. Во время
            сильных бурь сияние видно намного южнее обычного.
          </p>
          <div className="fa-figure ph" style={{ height: 132 }}>фотография северного сияния</div>
          <p className="fa-hint">
            <kbd>↑</kbd> Попробуйте: выделите любые слова выше
          </p>
        </article>

        {/* selection pill */}
        {pill && (
          <button
            className="m-pill"
            style={{ left: pill.x, top: pill.y }}
            onClick={() => openFor(pill.text, pill.rect)}
          >
            <MarkGlyph size={15} />
            Спросить Mentium
          </button>
        )}

        {/* answer popover */}
        {pop && (
          <div className="m-pop" style={{ left: pop.x, top: pop.y }}>
            <div className="m-pop-head">
              <MarkGlyph size={17} />
              <span className="m-pop-name">Mentium</span>
              <button className="m-pop-x" onClick={clearAll} aria-label="close">×</button>
            </div>
            <div className="m-quote">“{pop.text}”</div>
            <div className="m-answer">
              {thinking ? (
                <span className="m-think">
                  <i></i><i></i><i></i> читаю страницу…
                </span>
              ) : (
                <span>
                  {typed}
                  {typed.length > 0 && <span className="m-caret"></span>}
                </span>
              )}
            </div>
            {!thinking && typed.length > 30 && (
              <div className="m-sources" ref={sourcesRef}>
                {pop.sources.map((s, i) => (
                  <span className="m-src" key={i}>{s}</span>
                ))}
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

function MarkGlyph({ size = 16 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden="true" className="mark-glyph">
      <path d="M5 19.5l1.2-3.6L15.4 6.7a2 2 0 012.8 0l1.1 1.1a2 2 0 010 2.8l-9.2 9.2L7 21" fill="var(--accent)" opacity="0.18" />
      <path d="M5 19.5l1.2-3.6L15.4 6.7a2 2 0 012.8 0l1.1 1.1a2 2 0 010 2.8l-9.2 9.2L7 21l-2-1.5z"
        stroke="var(--accent)" strokeWidth="1.7" strokeLinejoin="round" />
      <path d="M13.6 8.6l3.8 3.8" stroke="var(--accent)" strokeWidth="1.7" />
    </svg>
  );
}

Object.assign(window, { HeroDemo, MarkGlyph });
