// stream.js
// Оверлей /stream (прозрачный). Без таймера.
// Показываем ТОЛЬКО когда p.active === true и p.kind === "bible".
// Во всех остальных случаях — скрываем.

(() => {
  const root = document.getElementById("root");
  root.style.position = "absolute";
  root.style.inset = "0";
  root.style.pointerEvents = "none";
  root.style.fontFamily = "Roboto, Arial, Helvetica, sans-serif";

  const STREAM_STYLE = {
    bottomPx: 120,
    widthPx: 3100,
    radiusPx: 22,
    cardBg: "rgba(20, 18, 35, 0.78)",
    shadow: "0 18px 70px rgba(0,0,0,0.45)",
    accentHeightPx: 8,
    accentGradient:
      "linear-gradient(90deg, rgb(0,90,255), rgb(160,0,255), rgb(255,50,90))",
    padding: "46px 72px 40px 72px",
    textStartPx: 92,
    textMinPx: 48,
    textStepPx: 2,
    textLineHeight: 1.12,
    textWeight: 500,
    textMaxHeightPx: 360,
    refPx: 62,
    refWeight: 500,
    revealMs: 420,
    concealMs: 320,
  };

  root.innerHTML = `
<style>
  html, body { background: transparent; }

  .lt-wrap{
    position:absolute;
    left:0; right:0;
    bottom: ${STREAM_STYLE.bottomPx}px;
    display:flex;
    justify-content:center;
  }
  .lt-card{
    width: ${STREAM_STYLE.widthPx}px;
    border-radius: ${STREAM_STYLE.radiusPx}px;
    overflow:hidden;
    background: ${STREAM_STYLE.cardBg};
    box-shadow: ${STREAM_STYLE.shadow};
    transform-origin: center bottom;
    transform: translateY(40px) scaleY(0.85);
    opacity: 0;
  }
  .lt-accent{
    height: ${STREAM_STYLE.accentHeightPx}px;
    background: ${STREAM_STYLE.accentGradient};
    opacity: 0.95;
  }
  .lt-inner{
    padding: ${STREAM_STYLE.padding};
    color: rgba(255,255,255,0.96);
  }
  .lt-text{
    font-size: ${STREAM_STYLE.textStartPx}px;
    line-height: ${STREAM_STYLE.textLineHeight};
    font-weight: ${STREAM_STYLE.textWeight};
    text-align:center;
    text-shadow: 0 8px 26px rgba(0,0,0,0.55);
    white-space: pre-wrap;
    max-height: ${STREAM_STYLE.textMaxHeightPx}px;
    overflow:hidden;
  }
  .lt-ref{
    margin-top: 28px;
    font-size: ${STREAM_STYLE.refPx}px;
    font-weight: ${STREAM_STYLE.refWeight};
    opacity: 0.86;
    text-align:center;
    text-shadow: 0 6px 18px rgba(0,0,0,0.55);
    white-space: nowrap;
    overflow:hidden;
    text-overflow: ellipsis;
  }

  .show .lt-card{ animation: reveal ${STREAM_STYLE.revealMs}ms ease-out forwards; }
  .hide .lt-card{ animation: conceal ${STREAM_STYLE.concealMs}ms ease-in forwards; }

  @keyframes reveal {
    from { opacity: 0; transform: translateY(40px) scaleY(0.85); }
    to   { opacity: 1; transform: translateY(0px)  scaleY(1.0); }
  }
  @keyframes conceal {
    from { opacity: 1; transform: translateY(0px)  scaleY(1.0); }
    to   { opacity: 0; transform: translateY(30px) scaleY(0.92); }
  }
</style>

<div class="lt-wrap hide" id="wrap">
  <div class="lt-card">
    <div class="lt-inner">
      <div class="lt-text" id="text"></div>
      <div class="lt-ref" id="ref"></div>
    </div>
    <div class="lt-accent"></div>
  </div>
</div>
`;

  const wrap = document.getElementById("wrap");
  const elText = document.getElementById("text");
  const elRef = document.getElementById("ref");

  let lastKey = "";

  function hideNow() {
    wrap.classList.remove("show");
    wrap.classList.add("hide");
  }
  function showNow() {
    wrap.classList.remove("hide");
    wrap.classList.add("show");
  }

  function stripHtmlToPlain(html) {
    if (!html) return "";
    return String(html)
      .replace(/<sup[^>]*>.*?<\/sup>/gi, "")
      .replace(/<br\s*\/?\s*>/gi, "\n")
      .replace(/<[^>]+>/g, "")
      .replace(/&nbsp;/g, " ")
      .replace(/&amp;/g, "&")
      .replace(/&lt;/g, "<")
      .replace(/&gt;/g, ">")
      .trim();
  }

  function extractVerseNumber(p) {
    const h = String(p.html || "");
    const mSup = h.match(/<sup[^>]*>\s*([0-9]{1,3}:[0-9]{1,3})/i);
    if (mSup) return mSup[1];

    const t = String(p.text || "").trim();
    const mTxt = t.match(/^([0-9]{1,3}:[0-9]{1,3})\b/);
    if (mTxt) return mTxt[1];

    const plain = stripHtmlToPlain(p.html || "");
    const mPlain = plain.match(/^([0-9]{1,3}:[0-9]{1,3})\b/);
    if (mPlain) return mPlain[1];

    return "";
  }

  function extractBookName(p) {
    const title = String(p.title || "").trim();
    const footer0 =
      Array.isArray(p.footer) && p.footer[0] ? String(p.footer[0]).trim() : "";
    const src = footer0 || title;

    const m = src.match(/^(.*?)(?=\s+\d)/);
    if (m && m[1]) return m[1].trim();

    const parts = src.split(/\s+/).filter(Boolean);
    return parts.slice(0, 2).join(" ");
  }

  function buildRef(p) {
    const book = extractBookName(p);
    const verse = extractVerseNumber(p);
    if (book && verse) return `${book} ${verse}`;
    return p.footer && p.footer[0] ? String(p.footer[0]) : p.title || "";
  }

  function fitText() {
    const maxH = STREAM_STYLE.textMaxHeightPx;
    const maxW = elText.clientWidth;

    let font = STREAM_STYLE.textStartPx;
    elText.style.fontSize = font + "px";
    elText.style.lineHeight = String(STREAM_STYLE.textLineHeight);

    let guard = 0;
    while (
      (elText.scrollHeight > maxH || elText.scrollWidth > maxW) &&
      font > STREAM_STYLE.textMinPx
    ) {
      font -= STREAM_STYLE.textStepPx;
      elText.style.fontSize = font + "px";
      if (++guard > 300) break;
    }
  }

  const es = new EventSource("/events");

  es.addEventListener("live", (ev) => {
    const p = JSON.parse(ev.data);

    // Нет активного вывода или это не Библия -> скрываем
    if (!p.active || p.kind !== "bible") {
      hideNow();
      return;
    }

    const text = stripHtmlToPlain(p.html) || p.text || "";
    const ref = buildRef(p);

    const key = JSON.stringify([ref, text]);
    if (key === lastKey) return;
    lastKey = key;

    elText.textContent = text;
    elRef.textContent = ref;

    fitText();
    showNow();
  });

  es.onerror = () => hideNow();
})();
