import { apiFetch } from "../api/client.js";
import { renderPublicPolicyFooter } from "../config/legal-links.js";
import { escapeHtml } from "../utils/html.js";

const SESSION_KEY = "gatewise.demoAccess";
const MAX_SESSION_MS = 2 * 60 * 60 * 1000;

export function hasValidDemoAccess(now = Date.now()) {
  try {
    const session = JSON.parse(sessionStorage.getItem(SESSION_KEY) || "null");
    return Boolean(session?.approved && session?.role === "ESTATE_ADMIN" && Number(session?.expiresAt || 0) > now);
  } catch {
    return false;
  }
}

export function renderDemoAccessPage(app) {
  document.body.classList.add("welcome-body");
  app.className = "welcome-page demo-access-page";
  document.title = "Approved Demo Access | GateWise NG";
  const params = new URLSearchParams(window.location.search);
  app.innerHTML = `
    <header class="welcome-nav compact-public-nav">
      <a class="welcome-brand" href="/" aria-label="GateWise NG home">
        <span class="welcome-brand-mark" aria-hidden="true">GW</span>
        <span>GateWise NG</span>
      </a>
      <nav class="welcome-links" aria-label="Demo access navigation">
        <a href="/">Home</a>
        <a href="/onboarding">Estate signup</a>
        <a href="/plans">Plans</a>
        <a href="/app">Login</a>
        <button class="public-theme-toggle" type="button" data-public-theme-toggle aria-label="Toggle light or dark mode">Theme</button>
      </nav>
    </header>

    <main class="demo-access-shell">
      <section class="demo-access-card">
        <div>
          <p class="welcome-kicker">Protected demo</p>
          <h1>Approved estate admin access required.</h1>
          <p>
            The demo workspace is available only after estate registration, verification, business approval, and payment confirmation.
            Approved estate admins sign in with their OTP-enabled phone number. Access expires automatically after the time allowed by the business team.
          </p>
        </div>
        <form class="demo-access-form" data-demo-access-form>
          <div class="field">
            <label for="demo-phone">Approved estate admin phone</label>
            <input id="demo-phone" name="phone" type="tel" autocomplete="tel" value="${escapeHtml(params.get("phone") || "")}" required>
          </div>
          <div class="field">
            <label for="demo-otp">OTP</label>
            <input id="demo-otp" name="otp" inputmode="numeric" autocomplete="one-time-code" placeholder="Enter OTP after request" required>
          </div>
          <div class="demo-access-actions">
            <button class="welcome-btn" type="button" data-demo-request-otp>Request OTP</button>
            <button class="welcome-btn primary" type="submit">Enter demo workspace</button>
          </div>
          <div class="demo-request-status" data-demo-access-status aria-live="polite"></div>
        </form>
      </section>
      <aside class="demo-access-rules">
        <h2>Protected from public visitors</h2>
        <p>Internal operational tools and credentials stay hidden from public visitors.</p>
        <div class="demo-assurance-list">
          <span>Estate admin role required</span>
          <span>Approved estate registration required</span>
          <span>Time-limited demo session</span>
          <span>Production estate data stays isolated</span>
        </div>
      </aside>
    </main>

    ${renderPublicPolicyFooter()}
  `;

  app.querySelector("[data-demo-request-otp]")?.addEventListener("click", requestOtp);
  app.querySelector("[data-demo-access-form]")?.addEventListener("submit", verifyOtp);
}

async function requestOtp(event) {
  const form = event.currentTarget.closest("form");
  const status = form.querySelector("[data-demo-access-status]");
  const phone = new FormData(form).get("phone");
  setStatus(status, "Requesting OTP for approved estate admin...", "pending");
  try {
    await apiFetch("/auth/login", { method: "POST", body: { phone } });
    setStatus(status, "OTP sent. Enter the code to continue.", "success");
  } catch (error) {
    setStatus(status, error.message || "Could not request OTP.", "error");
  }
}

async function verifyOtp(event) {
  event.preventDefault();
  const form = event.currentTarget;
  const status = form.querySelector("[data-demo-access-status]");
  const data = Object.fromEntries(new FormData(form).entries());
  setStatus(status, "Verifying approved demo access...", "pending");
  try {
    const result = await apiFetch("/auth/verify-otp", {
      method: "POST",
      body: { phone: data.phone, otp: data.otp }
    });
    const role = extractRole(result);
    if (role !== "ESTATE_ADMIN") {
      throw new Error("Demo access is restricted to approved estate admins.");
    }
    const expiresAt = Date.now() + MAX_SESSION_MS;
    sessionStorage.setItem(SESSION_KEY, JSON.stringify({ approved: true, role, expiresAt }));
    localStorage.setItem("estateSecurity.tokens", JSON.stringify({ accessToken: result.accessToken, refreshToken: result.refreshToken }));
    localStorage.setItem("estateSecurity.role", "ESTATE_ADMIN");
    localStorage.setItem("estateSecurity.user", JSON.stringify({ name: "Ade Okafor", role: "ESTATE_ADMIN", phone: data.phone }));
    window.location.reload();
  } catch (error) {
    setStatus(status, error.message || "Demo access could not be verified.", "error");
  }
}

function extractRole(result) {
  const token = String(result?.accessToken || "");
  const payload = token.split(".")[1];
  if (!payload) {
    return "";
  }
  try {
    const normalized = payload.replace(/-/g, "+").replace(/_/g, "/");
    const padded = normalized + "=".repeat((4 - (normalized.length % 4)) % 4);
    const decoded = JSON.parse(atob(padded));
    return String(decoded.role || "").toUpperCase();
  } catch {
    return "";
  }
}

function setStatus(node, message, type) {
  if (!node) {
    return;
  }
  node.className = `demo-request-status ${type || ""}`.trim();
  node.textContent = message;
}