import { LEGAL_DOCS, getLegalDocBySlug, renderPublicPolicyFooter } from "../config/legal-links.js";
import { escapeHtml } from "../utils/html.js";

export function renderLegalPage(app, pathname = window.location.pathname) {
  document.body.classList.add("welcome-body");
  app.className = "welcome-page legal-page";

  const slug = pathname.replace(/^\/legal\/?/, "").replace(/\/+$/, "");
  const selected = slug ? getLegalDocBySlug(slug) : null;

  app.innerHTML = `
    <header class="welcome-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="Policy navigation">
        <a href="/">Overview</a>
        <a href="/onboarding">Estate signup</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="legal-shell">
      <aside class="legal-sidebar" aria-label="Policy documents">
        <p class="welcome-kicker">Policy Center</p>
        <h1>Legal, privacy, and trust policies.</h1>
        <p>GateWise NG is a product of Globulus Technology Limited. These pages explain user rights, service terms, data protection, deletion, cookies, and incident-response commitments.</p>
        <nav>
          ${LEGAL_DOCS.map((doc) => `
            <a class="${selected?.slug === doc.slug ? "active" : ""}" href="/legal/${escapeHtml(doc.slug)}">
              <strong>${escapeHtml(doc.title)}</strong>
              <span>${escapeHtml(doc.description)}</span>
            </a>
          `).join("")}
        </nav>
      </aside>
      <article class="legal-document" data-legal-document>
        ${selected ? renderLoadingState(selected) : renderPolicyIndex()}
      </article>
    </main>

    ${renderPublicPolicyFooter()}
  `;

  if (selected) {
    loadPolicyDocument(app, selected);
  }
}

function renderPolicyIndex() {
  return `
    <p class="welcome-kicker">GateWise NG</p>
    <h2>Policy Center</h2>
    <p class="legal-intro">Choose a policy to read the full customer-facing document. The WebApp is the canonical public reference for GateWise NG legal and privacy links; the MobileApp points users back to these pages.</p>
    <div class="legal-card-grid">
      ${LEGAL_DOCS.map((doc) => `
        <a class="legal-card" href="/legal/${escapeHtml(doc.slug)}">
          <h3>${escapeHtml(doc.title)}</h3>
          <p>${escapeHtml(doc.description)}</p>
        </a>
      `).join("")}
    </div>
  `;
}

function renderLoadingState(doc) {
  return `
    <p class="welcome-kicker">Policy document</p>
    <h2>${escapeHtml(doc.title)}</h2>
    <p class="legal-intro">Loading the latest published policy...</p>
  `;
}

async function loadPolicyDocument(app, doc) {
  const target = app.querySelector("[data-legal-document]");
  if (!target) {
    return;
  }

  try {
    const response = await fetch(`/legal/${doc.file}`, { cache: "no-store" });
    if (!response.ok) {
      throw new Error("Policy document could not be loaded.");
    }
    const markdown = await response.text();
    target.innerHTML = markdownToHtml(markdown);
    document.title = `${doc.title} | GateWise NG`;
  } catch (error) {
    target.innerHTML = `
      <p class="welcome-kicker">Policy document</p>
      <h2>${escapeHtml(doc.title)}</h2>
      <p class="legal-intro">${escapeHtml(error.message || "This policy could not be loaded right now.")}</p>
      <a class="welcome-btn" href="/legal">Back to Policy Center</a>
    `;
  }
}

function markdownToHtml(markdown) {
  const lines = markdown.replace(/\r\n/g, "\n").split("\n");
  const html = [];
  let paragraph = [];
  let list = [];
  let table = [];

  const flushParagraph = () => {
    if (paragraph.length) {
      html.push(`<p>${formatInline(paragraph.join(" "))}</p>`);
      paragraph = [];
    }
  };

  const flushList = () => {
    if (list.length) {
      html.push(`<ul>${list.map((item) => `<li>${formatInline(item)}</li>`).join("")}</ul>`);
      list = [];
    }
  };

  const flushTable = () => {
    if (!table.length) {
      return;
    }
    const rows = table.map((line) => line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((cell) => cell.trim()));
    const header = rows[0] || [];
    const body = rows.slice(2);
    html.push(`
      <div class="legal-table-wrap">
        <table>
          <thead><tr>${header.map((cell) => `<th>${formatInline(cell)}</th>`).join("")}</tr></thead>
          <tbody>${body.map((row) => `<tr>${row.map((cell) => `<td>${formatInline(cell)}</td>`).join("")}</tr>`).join("")}</tbody>
        </table>
      </div>
    `);
    table = [];
  };

  for (const line of lines) {
    const trimmed = line.trim();

    if (!trimmed) {
      flushParagraph();
      flushList();
      flushTable();
      continue;
    }

    if (trimmed.startsWith("|")) {
      flushParagraph();
      flushList();
      table.push(trimmed);
      continue;
    }

    flushTable();

    if (trimmed.startsWith("# ")) {
      flushParagraph();
      flushList();
      html.push(`<h2>${formatInline(trimmed.slice(2))}</h2>`);
    } else if (trimmed.startsWith("## ")) {
      flushParagraph();
      flushList();
      html.push(`<h3>${formatInline(trimmed.slice(3))}</h3>`);
    } else if (trimmed.startsWith("### ")) {
      flushParagraph();
      flushList();
      html.push(`<h4>${formatInline(trimmed.slice(4))}</h4>`);
    } else if (trimmed.startsWith("- ")) {
      flushParagraph();
      list.push(trimmed.slice(2));
    } else {
      paragraph.push(trimmed);
    }
  }

  flushParagraph();
  flushList();
  flushTable();

  return html.join("\n");
}

function formatInline(value) {
  return escapeHtml(value)
    .replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>")
    .replace(/\[(.+?)\]\((.+?)\)/g, '<a href="$2">$1</a>');
}
