/* =========================================================
   HOUSEATOR — Login page logic + slide-to-verify
   ========================================================= */

HOUSEATOR.setupTheme();

/* Back-to-top floating button — same behavior as the public site. */
(function setupBackToTop() {
  const btn = document.getElementById("backToTop");
  if (!btn) return;
  const onScroll = () => {
    btn.classList.toggle("visible", window.scrollY > 300);
  };
  window.addEventListener("scroll", onScroll, { passive: true });
  btn.addEventListener("click", () => {
    window.scrollTo({ top: 0, behavior: "smooth" });
  });
  onScroll();
})();

/* Mobile hamburger — drives the same full-viewport .mobile-menu overlay
   used on index.html so the dropdown looks and behaves identically here.
   Mirrors script.js's setupMobileMenu (pointer-tracked reveal + explicit
   navigation so tapping a link cleanly closes the overlay before the
   page change). */
(function setupMobileMenu() {
  const header   = document.querySelector(".site-header");
  const burger   = document.getElementById("navHamburger");
  const navLinks = document.getElementById("primaryNav");
  const overlay  = document.getElementById("mobileMenu");
  if (!header || !burger || !navLinks) return;
  const setOpen = (open) => {
    header.classList.toggle("mobile-open", open);
    if (overlay) {
      overlay.classList.toggle("is-open", open);
      overlay.setAttribute("aria-hidden", open ? "false" : "true");
    }
    document.body.classList.toggle("mobile-menu-open", open);
    burger.setAttribute("aria-expanded", open ? "true" : "false");
    burger.setAttribute("aria-label", open ? "Close menu" : "Open menu");
  };
  burger.addEventListener("click", (e) => {
    e.stopPropagation();
    setOpen(!header.classList.contains("mobile-open"));
  });
  navLinks.addEventListener("click", (e) => {
    if (e.target.closest("a")) setOpen(false);
  });
  if (overlay) {
    /* Random optimized reveal image per load — mirrors index.html so the
       login-page dropdown behaves identically. route-67.jpg is bundled
       (~185KB); the Unsplash URLs are CDN-optimized (auto=format, w=1280,
       q=70) to stay well under 200KB. */
    const REVEAL_IMAGES = [
      "images/route-67.jpg",
      "https://images.unsplash.com/photo-1568605114967-8130f3a36994?auto=format&fit=crop&w=1280&q=70",
      "https://images.unsplash.com/photo-1505691938895-1758d7feb511?auto=format&fit=crop&w=1280&q=70",
      "https://images.unsplash.com/photo-1564013799919-ab600027ffc6?auto=format&fit=crop&w=1280&q=70",
      "https://images.unsplash.com/photo-1600596542815-ffad4c1539a9?auto=format&fit=crop&w=1280&q=70",
      "https://images.unsplash.com/photo-1600607687939-ce8a6c25118c?auto=format&fit=crop&w=1280&q=70"
    ];
    const pick = REVEAL_IMAGES[Math.floor(Math.random() * REVEAL_IMAGES.length)];
    const pre = new Image();
    pre.src = pick;
    overlay.style.setProperty("--reveal-img", `url("${pick}")`);

    overlay.addEventListener("click", (e) => {
      const link = e.target.closest("a");
      if (!link) return;
      const href = link.getAttribute("href");
      if (!href) return;
      e.preventDefault();
      setOpen(false);
      setTimeout(() => {
        if (href.startsWith("#")) {
          const target = document.querySelector(href);
          if (target) target.scrollIntoView({ behavior: "smooth", block: "start" });
        } else {
          window.location.href = href;
        }
      }, 280);
    });
    const updatePos = (x, y) => {
      overlay.style.setProperty("--mx", x + "px");
      overlay.style.setProperty("--my", y + "px");
      const rect = overlay.getBoundingClientRect();
      const cx = rect.width  / 2;
      const cy = rect.height / 2;
      const dist = Math.hypot(x - cx, y - cy);
      const diag = Math.hypot(cx, cy);
      const t = Math.max(0, 1 - dist / (diag * 0.4));
      const eased = t * t;
      const baseR       = 110;
      const baseFeather = 240;
      const fullR       = Math.max(rect.width, rect.height) * 1.4;
      const fullFeather = Math.max(rect.width, rect.height) * 1.8;
      overlay.style.setProperty("--reveal-r",       (baseR       + (fullR       - baseR)       * eased) + "px");
      overlay.style.setProperty("--reveal-feather", (baseFeather + (fullFeather - baseFeather) * eased) + "px");
    };
    overlay.addEventListener("mousemove", (e) => updatePos(e.clientX, e.clientY));
    overlay.addEventListener("touchstart", (e) => {
      const t = e.touches[0]; if (t) updatePos(t.clientX, t.clientY);
    }, { passive: true });
    overlay.addEventListener("touchmove", (e) => {
      const t = e.touches[0]; if (t) updatePos(t.clientX, t.clientY);
    }, { passive: true });
  }
  document.addEventListener("keydown", (e) => {
    if (e.key === "Escape" && header.classList.contains("mobile-open")) setOpen(false);
  });
})();

const VALID_USER = "House1234";
const VALID_PASS = "House1234!";

/* If already authed in this session, skip straight to dashboard. */
if (HOUSEATOR.isAuthed()) {
  window.location.replace("dashboard.html");
}

const form        = document.getElementById("loginForm");
const userInput   = document.getElementById("loginUser");
const passInput   = document.getElementById("loginPass");
const passToggle  = document.getElementById("passToggle");
const signInBtn   = document.getElementById("signInBtn");
const errorEl     = document.getElementById("loginError");
const hintEl      = document.getElementById("loginHint");

let humanVerified = false;

/* ---------- Show/hide password ---------- */
passToggle.addEventListener("click", () => {
  const show = passInput.type === "password";
  passInput.type = show ? "text" : "password";
  passToggle.textContent = show ? "🙈" : "👁";
});

/* =========================================================
   SLIDE-TO-VERIFY component
   ========================================================= */
const slide = document.getElementById("slideVerify");
const thumb = document.getElementById("slideThumb");
const slideText = document.getElementById("slideVerifyText");

let dragging = false;
let startX = 0;
let currentX = 0;
let maxX = 0;

function trackMaxX() {
  const trackEl = slide.querySelector(".slide-verify-track");
  return trackEl.clientWidth - thumb.offsetWidth - 4; /* 2px each side */
}

function setThumbX(x) {
  currentX = Math.max(0, Math.min(x, maxX));
  thumb.style.transform = `translateX(${currentX}px)`;
  slideText.style.opacity = String(1 - currentX / maxX * 0.95);
}

function resetSlide() {
  currentX = 0;
  thumb.style.transition = "transform .25s ease";
  thumb.style.transform = "translateX(0)";
  slideText.style.opacity = "1";
  setTimeout(() => { thumb.style.transition = ""; }, 260);
}

function lockVerified() {
  humanVerified = true;
  slide.dataset.state = "verified";
  slideText.textContent = "✓ Verified — you're human";
  slideText.style.opacity = "1";
  thumb.style.transition = "transform .2s ease";
  thumb.style.transform = `translateX(${maxX}px)`;
  thumb.disabled = true;
  updateSubmitState();
}

function startDrag(clientX) {
  if (humanVerified) return;
  dragging = true;
  maxX = trackMaxX();
  startX = clientX - currentX;
  thumb.style.transition = "";
  slide.dataset.state = "dragging";
}
function moveDrag(clientX) {
  if (!dragging) return;
  setThumbX(clientX - startX);
}
function endDrag() {
  if (!dragging) return;
  dragging = false;
  if (currentX >= maxX - 4) lockVerified();
  else { slide.dataset.state = "idle"; resetSlide(); }
}

/* Pointer events (mouse + touch unified) */
thumb.addEventListener("pointerdown", (e) => {
  e.preventDefault();
  thumb.setPointerCapture(e.pointerId);
  startDrag(e.clientX);
});
thumb.addEventListener("pointermove", (e) => moveDrag(e.clientX));
thumb.addEventListener("pointerup",   endDrag);
thumb.addEventListener("pointercancel", endDrag);

/* Keyboard fallback: hold ArrowRight on focused thumb */
thumb.addEventListener("keydown", (e) => {
  if (humanVerified) return;
  if (e.key === "ArrowRight") {
    maxX = trackMaxX();
    setThumbX(currentX + 12);
    if (currentX >= maxX - 4) lockVerified();
  } else if (e.key === "ArrowLeft") {
    maxX = trackMaxX();
    setThumbX(currentX - 12);
  }
});

/* Recompute max on resize */
window.addEventListener("resize", () => {
  if (humanVerified) {
    maxX = trackMaxX();
    thumb.style.transform = `translateX(${maxX}px)`;
  }
});

/* =========================================================
   FORM SUBMIT
   ========================================================= */
function updateSubmitState() {
  const ok = humanVerified && userInput.value.trim() && passInput.value.trim();
  signInBtn.disabled = !ok;
  if (humanVerified) hintEl.textContent = "Enter your credentials to sign in.";
}

[userInput, passInput].forEach(el => el.addEventListener("input", updateSubmitState));

form.addEventListener("submit", (e) => {
  e.preventDefault();
  errorEl.hidden = true;

  if (!humanVerified) {
    hintEl.textContent = "Please complete the slide verification first.";
    return;
  }
  if (userInput.value === VALID_USER && passInput.value === VALID_PASS) {
    HOUSEATOR.setAuthed();
    HOUSEATOR.setUser(userInput.value);
    signInBtn.textContent = "Signing in…";
    signInBtn.disabled = true;
    setTimeout(() => { window.location.assign("dashboard.html"); }, 350);
  } else {
    errorEl.hidden = false;
    /* Reset verification on failed login (require re-verify, common pattern) */
    humanVerified = false;
    slide.dataset.state = "idle";
    slideText.textContent = "Slide to verify";
    thumb.disabled = false;
    resetSlide();
    updateSubmitState();
  }
});

updateSubmitState();
