  // Reset local do card: reseta apenas o card clicado
  document.addEventListener('click', e => {
    const btn = e.target.closest('.pill.reset');
    if (btn) {
      const card = btn.closest('.card');
      if (card && window.resetCardLocal) {
        window.resetCardLocal(card);
      }
      // Não recarrega a página!
    }
  });
// ==========================================================
// ui.js — Camada de interface (renderização e contadores)
// Projeto: HEP Flashcards
// Descrição: Responsável por renderizar cards, atualizar contadores e interface.
// ==========================================================

(function () {

  // Objeto principal da UI exposto globalmente
  const UI = {};
  window.UI = UI;

  // Helpers rápidos
  const qs  = (sel) => document.querySelector(sel);
  const qsa = (sel) => Array.from(document.querySelectorAll(sel));

  // ----------------------------------------------------------
  // NOVO: Marca manualmente o card como “atual”
  // Necessário para o comando OK funcionar corretamente
  // ----------------------------------------------------------
  UI.setManualCurrent = (card) => {
    if (!card) return;
    qsa(".autoplay-current").forEach(c => c.classList.remove("autoplay-current"));
    card.classList.add("autoplay-current");
  };

  // ----------------------------------------------------------
  // TOAST — mensagem temporária no rodapé
  // ----------------------------------------------------------
  UI.toast = (msg, ms = 2000) => {
    const el = qs("#toast");
    if (!el) return;
    el.textContent = msg;
    // Reset all possible inline styles that could break centralization
    el.style.display = "block";
    el.style.position = "fixed";
    // Centralização vertical original:
    // el.style.top = "50%";
    // el.style.transform = "translate(-50%, -50%)";
    // Nova posição: 150px do topo, centralizado horizontalmente
    el.style.top = "150px";
    el.style.left = "50%";
    el.style.transform = "translateX(-50%)";
    el.style.zIndex = "9999";
    el.style.opacity = "1";
    setTimeout(() => {
      el.style.display = "none";
    }, ms);
  };

  // ----------------------------------------------------------
  // HEARDBAR — mostra idioma e texto ouvido pelo STT
  // ----------------------------------------------------------
  UI.updateHeardFooter = (langName, text) => {
    const l = qs("#heardLang");
    const t = qs("#heardText");
    if (l) l.textContent = langName || "—";
    if (t) {
      t.textContent = "";
      void t.offsetWidth;
      t.textContent = text || "—";
    }
  };

  // ----------------------------------------------------------
  // COMBOS DE IDIOMA (DE / PARA)
  // ----------------------------------------------------------
  UI.renderLangCombos = (fromKey, toKey) => {
    const fromSel = qs("#selLangFrom");
    const toSel   = qs("#selLangTo");
    if (!fromSel || !toSel || !window.LANGS) return;

    fromSel.innerHTML = "";
    toSel.innerHTML   = "";

    Object.entries(window.LANGS).forEach(([key, name]) => {
      const o1 = document.createElement("option");
      o1.value = key;
      o1.textContent = name;
      if (key === fromKey) o1.selected = true;
      fromSel.appendChild(o1);

      const o2 = document.createElement("option");
      o2.value = key;
      o2.textContent = name;
      if (key === toKey) o2.selected = true;
      toSel.appendChild(o2);
    });
  };

  // ----------------------------------------------------------
  // RENDERIZAÇÃO DOS CARDS
  // ----------------------------------------------------------
  UI.renderCards = (cards, { fromKey, toKey }) => {
    const container = qs("#cardsContainer");
    if (!container) return;
    container.innerHTML = "";
    const html = (cards || []).map((c, i) => {
      let fromText = c[fromKey] || "";
      let toText   = c[toKey]   || "";
      if (fromKey === "ptpt" && !fromText && c.ptbr) fromText = c.ptbr;
      if (fromKey === "ptbr" && !fromText && c.pt)   fromText = c.pt;
      if (toKey   === "ptpt" && !toText   && c.ptbr) toText   = c.ptbr;
      if (toKey   === "ptbr" && !toText   && c.pt)   toText   = c.pt;
      const id = `card-${i}`;
      const langKey = toKey;
      let infoVal = c["info_" + langKey];
      if (!infoVal || infoVal === "NA") infoVal = c.info_ptbr;
      const infoLine = (infoVal && infoVal !== "NA")
        ? `<div class="card-info">${infoVal}</div>`
        : "";
      // Bolinha azul para ímpares, laranja para pares
      const dot = `<div class='card-dot ${(i%2===0)?'laranja':'azul'}'></div>`;
      return `
        <article class="card"
          id="${id}"
          data-from="${(fromText || "").replace(/"/g, "&quot;")}"
          data-to="${(toText   || "").replace(/"/g, "&quot;")}"
          style="position:relative;"
        >
          ${dot}
          <div class="card-counter"></div>
          <span class="badge">Acertou!</span>
          <div class="card-icon-wrapper">
            <div class="card-icon-circle-bg"></div>
            <img class="card-icon"
                data-role="speak"
                data-card="${id}"
                src="${c.icon1 || ""}"
                onerror="this.onerror=null;this.src='${c.icon2 || ""}'"
                alt="${toText || fromText}">
          </div>
          ${c.showIconLabel ? `<div class="icon-label">${c.iconLabel || ""}</div>` : ""}
          <div class="card-texts">
            <div class="card-word">${toText}</div>
            <div class="card-pt">${fromText}</div>
            ${infoLine}
            <div class="card-recognized" id="rec-${id}"></div>
          </div>
          <div class="card-actions">
            <button class="pill mic"       data-role="mic"       data-card="${id}">🎙️</button>
            <button class="pill speak"     data-role="speak"     data-card="${id}">🔊</button>
            <button class="pill ignore"    data-role="ignore"    data-card="${id}">🚫</button>
            <button class="pill pt-toggle" data-role="pt-toggle" data-card="${id}">TX</button>
            <button class="pill reset"     data-role="reset"     data-card="${id}">♻️</button>
          </div>
        </article>
      `;
    }).join("");
    container.innerHTML = html;
    // CSS para a bolinha (margem de 6px das bordas)
    if (!document.getElementById('card-dot-style')) {
      const style = document.createElement('style');
      style.id = 'card-dot-style';
      style.textContent = `
        .card-dot {
          position: absolute;
          top: 6px;
          left: 6px;
          width: 7px;
          height: 7px;
          border-radius: 50%;
          z-index: 20;
          box-shadow: 0 0 2px #222;
        }
        .card-dot.azul { background: #2196f3; }
        .card-dot.laranja { background: orange; }
      `;
      document.head.appendChild(style);
    }
    // --- INÍCIO: Espelhamento do card 1 ---
    try {
      if (window.BroadcastChannel) {
        if (!window._espelho_channel) {
          window._espelho_channel = new BroadcastChannel('card1_espelho');
        }
        const card1 = document.getElementById('card-0');
        if (card1) {
          function sendCard1ToEspelho() {
            const cs = window.getComputedStyle(card1);
            const computedStyle = {};
            for (let i = 0; i < cs.length; i++) {
              const prop = cs[i];
              computedStyle[prop] = cs.getPropertyValue(prop);
            }
            window._espelho_channel.postMessage({ html: card1.outerHTML, computedStyle });
          }
          sendCard1ToEspelho();
          // Observa mudanças no card1 (texto, cor, atributos, etc)
          if (!window._espelho_card1_observer) {
            window._espelho_card1_observer = new MutationObserver(sendCard1ToEspelho);
            window._espelho_card1_observer.observe(card1, {
              attributes: true,
              childList: true,
              subtree: true,
              characterData: true
            });
          }
        }
        // Responde a pedidos do espelho.html
        window._espelho_channel.onmessage = (ev) => {
          if (ev.data && ev.data.type === 'espelho_ready') {
            const card1 = document.getElementById('card-0');
            if (card1) {
              function sendCard1ToEspelho() {
                const cs = window.getComputedStyle(card1);
                const computedStyle = {};
                for (let i = 0; i < cs.length; i++) {
                  const prop = cs[i];
                  computedStyle[prop] = cs.getPropertyValue(prop);
                }
                window._espelho_channel.postMessage({ html: card1.outerHTML, computedStyle });
              }
              sendCard1ToEspelho();
              if (!window._espelho_card1_observer) {
                window._espelho_card1_observer = new MutationObserver(sendCard1ToEspelho);
                window._espelho_card1_observer.observe(card1, {
                  attributes: true,
                  childList: true,
                  subtree: true,
                  characterData: true
                });
              }
            }
          }
          if (ev.data && ev.data.type === 'card1_click') {
            // Simula clique no card-0
            const card1 = document.getElementById('card-0');
            if (card1) card1.click();
          }
        };
        // Detecta 3 cliques rápidos no card-0 para abrir espelho.html
        if (card1) {
          let clickCount = 0;
          let lastClick = 0;
          let espelhoWin = null;
          card1.addEventListener('click', function openEspelhoOnTripleClick(e) {
            const now = Date.now();
            if (now - lastClick < 600) {
              clickCount++;
            } else {
              clickCount = 1;
            }
            lastClick = now;
            if (clickCount === 3) {
              clickCount = 0;
              // Só abre se não estiver aberto
              if (!espelhoWin || espelhoWin.closed) {
                espelhoWin = window.open('espelho.html', 'espelho_card1', 'width=600,height=400');
              } else {
                espelhoWin.focus();
              }
            }
          });
        }
      }
    } catch(e) { /* ignora se não suportado */ }
    // --- FIM: Espelhamento do card 1 ---
    UI.refreshCounters();
  };

  // ----------------------------------------------------------
  // LISTAS DE CARDS
  // ----------------------------------------------------------
  UI.getAllCards = () => qsa(".card");

  UI.getVisibleCards = () =>
    qsa(".card:not(.ignored)");

  // ----------------------------------------------------------
  // Mostrar / esconder texto PT
  // ----------------------------------------------------------
  UI.updateShowPT = (show) => {
    UI.getAllCards().forEach(c => {
      const pt = c.querySelector(".card-pt");
      if (pt) pt.classList.toggle("hidden", !show);
    });
  };

  // ----------------------------------------------------------
  // Mostrar / esconder texto da língua destino
  // ----------------------------------------------------------
  UI.updateShowLang = (show) => {
    UI.getAllCards().forEach(c => {
      const el = c.querySelector(".card-word");
      if (el) el.classList.toggle("hidden", !show);
    });
  };

  // ----------------------------------------------------------
  // CONTADORES (HIT TARGET)
  // ----------------------------------------------------------
  UI.refreshCounters = () => {

    const rawTarget = window.HIT_TARGET;
    const targetNum = parseInt(rawTarget, 10);

    const hasTarget = !isNaN(targetNum) && targetNum > 0;

    const cards = UI.getAllCards();
    if (!window.CARDS_DATA) return;

    cards.forEach((c, idx) => {
      const obj = window.CARDS_DATA[idx];
      if (!obj) return;

      let box = c.querySelector(".card-counter");
      if (!box) {
        box = document.createElement("div");
        box.className = "card-counter";
        c.appendChild(box);
      }

      if (!hasTarget) {
        box.textContent = "";
        box.style.display = "none";
        return;
      }

      box.textContent = obj._count || 0;
      box.style.display = "flex";
    });
  };

  // ----------------------------------------------------------
  // Marcação de estados visuais
  // ----------------------------------------------------------
  UI.markCardState = (card, { hit, blue, spoken, ignored }) => {
    if (!card) return;
    const cls = card.classList;
    if (hit     !== undefined) cls.toggle("hit",     hit);
    if (blue    !== undefined) cls.toggle("blue",    blue);
    if (spoken  !== undefined) cls.toggle("spoken",  spoken);
    if (ignored !== undefined) cls.toggle("ignored", ignored);
  };

  // ----------------------------------------------------------
  // Destacar card atual do autoplay
  // ----------------------------------------------------------
  UI.setAutoplayCurrent = (card) => {
    UI.getAllCards().forEach(c => c.classList.remove("autoplay-current"));
    if (card) {
      card.classList.add("autoplay-current");
      card.scrollIntoView({ behavior: "smooth", block: "center" });
    }
  };

  // ----------------------------------------------------------
  // Estatísticas gerais
  // ----------------------------------------------------------
  UI.updateStats = () => {
    const stats = qs("#stats");
    if (!stats) return;

    const cards = UI.getVisibleCards();

    const hits = cards.filter(c =>
      c.classList.contains("hit") || c.classList.contains("blue")
    ).length;

    const total = cards.length;
    const pct   = total ? Math.round((hits * 100) / total) : 0;

    stats.textContent = `TT: ${total} • Acertos: ${hits} • ${pct}%`;
  };

  UI.init = () => {};

})();
