<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title><%= title %></title>
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap"
      rel="stylesheet"
    />
    <style>
      :root {
        /* Catppuccin Mocha Palette */
        --ctp-base: #1e1e2e;
        --ctp-mantle: #181825;
        --ctp-crust: #11111b;
        --ctp-surface0: #313244;
        --ctp-surface1: #45475a;
        --ctp-surface2: #585b70;
        --ctp-overlay0: #6c7086;
        --ctp-overlay1: #7f849c;
        --ctp-overlay2: #9399b2;
        --ctp-text: #cdd6f4;
        --ctp-subtext1: #bac2de;
        --ctp-subtext0: #a6adc8;
        --ctp-lavender: #b4befe;
        --ctp-blue: #89b4fa;
        --ctp-sapphire: #74c7ec;
        --ctp-sky: #89dceb;
        --ctp-teal: #94e2d5;
        --ctp-green: #a6e3a1;
        --ctp-yellow: #f9e2af;
        --ctp-peach: #fab387;
        --ctp-maroon: #eba0ac;
        --ctp-red: #f38ba8;
        --ctp-mauve: #cba6f7;
        --ctp-pink: #f5c2e7;
        --ctp-flamingo: #f2cdcd;
        --ctp-rosewater: #f5e0dc;

        /* Application Colors */
        --bg-color: var(--ctp-base);
        --card-bg: var(--ctp-mantle);
        --text-primary: var(--ctp-text);
        --text-secondary: var(--ctp-subtext0);
        --accent: var(--ctp-mauve);
        --accent-hover: var(--ctp-lavender);
        --border: var(--ctp-surface0);
        --danger: var(--ctp-red);
        --success: var(--ctp-green);
      }

      body {
        font-family: "Inter", sans-serif;
        background-color: var(--bg-color);
        color: var(--text-primary);
        margin: 0;
        padding: 2rem;
        line-height: 1.5;
      }

      .container {
        max-width: 1000px;
        margin: 0 auto;
      }

      header {
        margin-bottom: 2rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      h1 {
        font-size: 1.5rem;
        font-weight: 700;
        margin: 0;
      }

      .card {
        background-color: var(--card-bg);
        border-radius: 0.75rem;
        border: 1px solid var(--border);
        padding: 1.5rem;
        margin-bottom: 2rem;
      }

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1rem;
      }

      h2 {
        font-size: 1.25rem;
        font-weight: 600;
        margin: 0;
      }

      input,
      select {
        background-color: var(--ctp-surface0);
        border: 1px solid var(--border);
        color: var(--text-primary);
        padding: 0.5rem 0.75rem;
        border-radius: 0.375rem;
        font-family: inherit;
        width: 100%;
        box-sizing: border-box;
        transition: border-color 0.2s, box-shadow 0.2s;
      }

      input:focus,
      select:focus {
        outline: none;
        border-color: var(--accent);
        box-shadow: 0 0 0 3px rgba(203, 166, 247, 0.1);
      }

      button {
        background-color: var(--accent);
        color: white;
        border: none;
        padding: 0.5rem 1rem;
        border-radius: 0.375rem;
        font-weight: 500;
        cursor: pointer;
        transition: background-color 0.2s;
      }

      button:hover {
        background-color: var(--accent-hover);
      }

      button.danger {
        background-color: transparent;
        color: var(--danger);
        border: 1px solid var(--danger);
      }

      button.danger:hover {
        background-color: rgba(239, 68, 68, 0.1);
      }

      button.secondary {
        background-color: transparent;
        color: var(--text-secondary);
        border: 1px solid var(--border);
      }

      button.secondary:hover {
        background-color: rgba(255, 255, 255, 0.05);
      }

      table {
        width: 100%;
        border-collapse: collapse;
      }

      th,
      td {
        text-align: left;
        padding: 0.75rem;
        border-bottom: 1px solid var(--border);
      }

      th {
        color: var(--text-secondary);
        font-weight: 500;
        font-size: 0.875rem;
      }

      .hidden {
        display: none;
      }

      .form-group {
        margin-bottom: 1rem;
      }

      .form-row {
        display: grid;
        grid-template-columns: 1fr auto;
        gap: 1rem;
        align-items: end;
      }

      #auth-section {
        max-width: 400px;
        margin: 4rem auto;
        text-align: center;
      }

      .env-section {
        margin-bottom: 2rem;
        border-bottom: 1px solid var(--border);
        padding-bottom: 2rem;
      }

      .env-section:last-child {
        border-bottom: none;
      }

      .survey-list {
        margin-top: 1rem;
        padding-left: 1rem;
        border-left: 2px solid var(--border);
      }

      .survey-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0.5rem 0;
        color: var(--text-secondary);
        gap: 1rem;
      }

      .survey-link {
        color: var(--accent);
        text-decoration: none;
        flex: 1;
      }

      .survey-link:hover {
        text-decoration: underline;
      }

      .copy-btn {
        background-color: transparent;
        color: var(--text-secondary);
        border: 1px solid var(--border);
        padding: 0.25rem 0.5rem;
        font-size: 0.75rem;
        cursor: pointer;
        transition: all 0.2s;
        white-space: nowrap;
      }

      .copy-btn:hover {
        background-color: rgba(255, 255, 255, 0.05);
        color: var(--accent);
      }

      .copy-btn.copied {
        background-color: var(--success);
        color: white;
        border-color: var(--success);
      }
    </style>
  </head>
  <body>
    <div id="auth-section" class="card">
      <h2>Admin Authentication</h2>
      <p style="color: var(--text-secondary); margin-bottom: 1.5rem">
        Enter your Admin Token to manage surveys.
      </p>
      <div class="form-group">
        <input type="password" id="admin-token" placeholder="Admin Token" />
      </div>
      <button onclick="authenticate()">Login</button>
    </div>

    <div id="app-section" class="container hidden">
      <header>
        <h1>Environment Management</h1>
        <button onclick="logout()" class="danger">Logout</button>
      </header>

      <div class="card">
        <div class="card-header">
          <h2>Environments & Aliases</h2>
          <div style="display: flex; gap: 0.5rem">
            <button onclick="syncSurveys()" class="secondary">
              Sync Surveys
            </button>
            <button onclick="loadData()">Refresh</button>
          </div>
        </div>
        <div id="environments-container">
          <!-- Environments will be inserted here -->
        </div>
      </div>
    </div>

    <script>
      const API_BASE = "/api/mappings";
      let token = localStorage.getItem("admin_token");

      if (token) {
        showApp();
      }

      function authenticate() {
        const input = document.getElementById("admin-token").value;
        if (input) {
          token = input;
          localStorage.setItem("admin_token", token);
          showApp();
        }
      }

      function logout() {
        token = null;
        localStorage.removeItem("admin_token");
        document.getElementById("auth-section").classList.remove("hidden");
        document.getElementById("app-section").classList.add("hidden");
      }

      function showApp() {
        document.getElementById("auth-section").classList.add("hidden");
        document.getElementById("app-section").classList.remove("hidden");
        loadData();
      }

      async function fetchWithAuth(url, options = {}) {
        const headers = {
          "Content-Type": "application/json",
          "x-admin-token": token,
          ...options.headers,
        };
        const response = await fetch(url, { ...options, headers });
        if (response.status === 403) {
          alert("Invalid Token");
          logout();
          return null;
        }
        return response;
      }

      async function loadData() {
        const res = await fetchWithAuth(`${API_BASE}/environments`);
        if (!res) return;
        const data = await res.json();
        renderEnvironments(data.environments);
      }

      async function renderEnvironments(environments) {
        const container = document.getElementById("environments-container");
        container.innerHTML = "";

        for (const env of environments) {
          const div = document.createElement("div");
          div.className = "env-section";

          // Fetch surveys for this environment
          const surveyRes = await fetchWithAuth(
            `${API_BASE}/environments/${env.environment_id}/surveys`
          );
          const surveyData = await surveyRes.json();
          const surveys = surveyData.surveys || [];

          const aliasValue = env.alias || "";
          const hasAlias = !!aliasValue;

          let surveysHtml = "";
          if (surveys.length > 0) {
            surveysHtml = '<div class="survey-list">';
            surveys.forEach((s) => {
              const displaySlug = s.custom_slug || s.name;
              const url = hasAlias ? `/${aliasValue}/${displaySlug}` : "#";
              const fullUrl = hasAlias
                ? `${window.location.origin}/${aliasValue}/${displaySlug}`
                : "";
              const link = hasAlias
                ? `<a href="${url}" target="_blank" class="survey-link">${url}</a>`
                : `<span style="color: var(--text-secondary);">(Set alias to generate URL)</span>`;
              const copyBtn = hasAlias
                ? `<button class="copy-btn" onclick="copyToClipboard('${fullUrl}', this)">📋 Copy</button>`
                : "";

              surveysHtml += `
                            <div class="survey-item" style="flex-direction: column; align-items: stretch; gap: 0.5rem; padding: 1rem 0; border-bottom: 1px solid var(--border);">
                                <div style="display: flex; justify-content: space-between; align-items: center;">
                                    <span style="font-weight: 500;">${
                                      s.name
                                    }</span>
                                    <span style="font-size: 0.75rem; color: var(--text-secondary);">Type: ${
                                      s.type
                                    }</span>
                                </div>
                                <div style="display: grid; grid-template-columns: 1fr auto auto; gap: 0.5rem; align-items: center;">
                                    <input 
                                        type="text" 
                                        id="slug-${s.id}" 
                                        value="${displaySlug}" 
                                        placeholder="custom-slug"
                                        style="font-size: 0.875rem; padding: 0.375rem 0.5rem;"
                                    />
                                    <button onclick="saveSlug('${
                                      s.id
                                    }')" class="secondary" style="font-size: 0.875rem;">Save Slug</button>
                                    ${copyBtn}
                                </div>
                                ${
                                  hasAlias
                                    ? `<div style="font-size: 0.875rem;">${link}</div>`
                                    : ""
                                }
                            </div>
                        `;
            });
            surveysHtml += "</div>";
          } else {
            surveysHtml =
              '<p style="color: var(--text-secondary); margin-top: 0.5rem;">No surveys found.</p>';
          }

          div.innerHTML = `
                    <div style="margin-bottom: 1rem;">
                        <h3 style="margin: 0 0 0.5rem 0;">Environment ID: <span style="font-family: monospace; font-weight: 400; color: var(--text-secondary);">${env.environment_id}</span></h3>
                        <div class="form-row">
                            <div>
                                <label style="display: block; margin-bottom: 0.5rem; color: var(--text-secondary); font-size: 0.875rem;">Root Path Alias</label>
                                <input type="text" id="alias-${env.environment_id}" value="${aliasValue}" placeholder="e.g. marketing">
                            </div>
                            <button onclick="saveAlias('${env.environment_id}')">Save Alias</button>
                        </div>
                    </div>
                    ${surveysHtml}
                `;
          container.appendChild(div);
        }
      }

      async function saveAlias(envId) {
        const input = document.getElementById(`alias-${envId}`);
        const alias = input.value.trim();

        if (!alias) {
          alert("Alias cannot be empty");
          return;
        }

        const res = await fetchWithAuth(
          `${API_BASE}/environments/${envId}/alias`,
          {
            method: "PUT",
            body: JSON.stringify({ alias }),
          }
        );

        if (res.ok) {
          loadData(); // Refresh to update URLs
        } else {
          const err = await res.json();
          alert(err.error || "Failed to update alias");
        }
      }

      async function copyToClipboard(text, button) {
        try {
          await navigator.clipboard.writeText(text);
          const originalText = button.textContent;
          button.textContent = "✓ Copied!";
          button.classList.add("copied");

          setTimeout(() => {
            button.textContent = originalText;
            button.classList.remove("copied");
          }, 2000);
        } catch (err) {
          console.error("Failed to copy:", err);
          alert("Failed to copy to clipboard");
        }
      }

      async function saveSlug(surveyId) {
        const input = document.getElementById(`slug-${surveyId}`);
        const slug = input.value.trim();

        if (!slug) {
          alert("Slug cannot be empty");
          return;
        }

        const res = await fetchWithAuth(
          `${API_BASE}/surveys/${surveyId}/slug`,
          {
            method: "PUT",
            body: JSON.stringify({ slug }),
          }
        );

        if (res.ok) {
          loadData(); // Refresh to update URLs
        } else {
          const err = await res.json();
          alert(err.error || "Failed to update slug");
        }
      }

        async function syncSurveys() {
            const btn = document.querySelector('button[onclick="syncSurveys()"]');
            const originalText = btn.textContent;
            btn.textContent = 'Syncing...';
            btn.disabled = true;

            try {
                const res = await fetchWithAuth(`${API_BASE}/sync`, { method: 'POST' });
                if (res.ok) {
                    alert('Surveys synced successfully!');
                    loadData();
                } else {
                    const err = await res.json();
                    alert('Sync failed: ' + (err.error || 'Unknown error'));
                }
            } catch (error) {
                alert('Sync failed: ' + error.message);
            } finally {
                btn.textContent = originalText;
                btn.disabled = false;
            }
        }
    </script>
  </body>
</html>
