// The Shadow page — Projection Mirror.
//
// Name three traits that drive you up the wall in other people. Press
// the mirror. The widget reflects them back as parts of you that you
// haven't owned. Jung in three text fields. The questions underneath
// each trait are the inner work; nobody else needs to see them.

(function () {
  const root = document.getElementById("shadowmirror");
  if (!root) return;

  const t = (k, fb) => (window.i18n && window.i18n.t) ? window.i18n.t(k, fb) : fb;

  const inputs    = root.querySelectorAll(".sm-input");
  const mirrorBtn = root.querySelector(".sm-mirror");
  const resetBtn  = root.querySelector(".sm-reset");
  const outputEl  = root.querySelector(".sm-output");

  function reflect() {
    const traits = Array.from(inputs)
      .map((i) => i.value.trim())
      .filter(Boolean);
    if (traits.length === 0) {
      outputEl.innerHTML = '<div class="sm-empty">'
        + t("page.shadow.sm_empty", "Name at least one trait above first.") + '</div>';
      outputEl.classList.add("visible");
      return;
    }
    const header = '<div class="sm-mirror-title">'
      + t("page.shadow.sm_mirror_title", "The mirror returns:") + '</div>';
    const cards = traits.map((trait) =>
      '<div class="sm-card">' +
        '<div class="sm-card-quote">"' + escape(trait) + '"</div>' +
        '<div class="sm-card-q1"><span class="sm-q-label">'
          + t("page.shadow.sm_q1", "When in your life have you been this?") + '</span></div>' +
        '<div class="sm-card-q2"><span class="sm-q-label">'
          + t("page.shadow.sm_q2", "Where do you suppress this in yourself, so you only see it in others?") + '</span></div>' +
        '<div class="sm-card-q3"><span class="sm-q-label">'
          + t("page.shadow.sm_q3", "What would change if you owned this part of yourself instead of fighting it in them?") + '</span></div>' +
      '</div>'
    ).join("");
    const footer = '<div class="sm-footer">'
      + t("page.shadow.sm_footer", "You are not them. But the charge — the heat, the certainty, the way it follows you home — is yours. Sit with it.") + '</div>';
    outputEl.innerHTML = header + cards + footer;
    outputEl.classList.add("visible");
  }
  function escape(s) {
    return s.replace(/[<>&"]/g, (c) => ({ "<": "&lt;", ">": "&gt;", "&": "&amp;", '"': "&quot;" }[c]));
  }
  function reset() {
    inputs.forEach((i) => { i.value = ""; });
    outputEl.classList.remove("visible");
    outputEl.innerHTML = "";
  }

  mirrorBtn.addEventListener("click", reflect);
  resetBtn.addEventListener("click", reset);
  inputs.forEach((i) => i.addEventListener("keydown", (e) => {
    if (e.key === "Enter") { e.preventDefault(); reflect(); }
  }));
  window.addEventListener("langchange", () => {
    if (outputEl.classList.contains("visible")) reflect();
  });
})();
