<%- include("partials/layout-top", { title, pageWidth: "wide", pageId: "theme-studio" }) %>
<link rel="stylesheet" href="/theme-editor.css?v=<%= assetVersion %>" />
<%
  const fieldLabels = {
    bg1: "Background glow",
    bg2: "Page background",
    bg3: "Accent glow",
    text: "Primary text",
    muted: "Muted text",
    accent: "Primary",
    accentAlt: "Accent",
    success: "Success",
    warning: "Warning",
    danger: "Danger",
    info: "Information",
    surface: "Surface",
    surface2: "Subtle surface",
    surface3: "Raised surface",
    border: "Border",
    link: "Link",
    buttonBg: "Button background",
    buttonText: "Button text",
    buttonHover: "Button hover",
    inputBg: "Input background",
    inputBorder: "Input border",
    inputText: "Input text",
    focusRing: "Focus ring"
  };
  const basicFields = [
    "accent", "accentAlt", "bg2", "surface", "surface2", "text", "muted",
    "border", "success", "warning", "danger", "info"
  ];
  const advancedFields = [
    "bg1", "bg3", "surface3", "link", "buttonBg", "buttonText",
    "buttonHover", "inputBg", "inputBorder", "inputText", "focusRing"
  ];
  const fontStackEntries = Object.entries((typeof fontStacks !== "undefined" && fontStacks) || {});
  const baseTheme = (typeof editingBaseTheme !== "undefined" && editingBaseTheme) || editingTheme || activeTheme;
%>

<header class="page-header">
  <div>
    <span class="eyebrow">Appearance</span>
    <h1>Theme studio</h1>
    <p class="command-subtitle">
      Select a protected Lumi preset or duplicate one into a custom theme.
    </p>
  </div>
  <span class="status-indicator status-success" data-active-theme-status>
    Active: <strong><%= activeTheme.name %></strong>
  </span>
</header>

<section class="theme-library" aria-labelledby="theme-library-title">
  <div class="section-header">
    <div>
      <h2 id="theme-library-title">Theme library</h2>
      <p class="hint">Built-in themes are read-only and always remain available.</p>
    </div>
  </div>
  <div class="theme-card-grid">
    <% themes.forEach((item) => { %>
    <% const customId = item.builtin ? null : item.id.replace("custom:", ""); %>
    <article class="theme-card <%= item.id === activeTheme.id ? 'is-active' : '' %>">
      <div class="theme-swatch" style="--swatch-bg: <%= item.light.bg2 %>; --swatch-surface: <%= item.light.surface %>; --swatch-primary: <%= item.light.accent %>; --swatch-accent: <%= item.light.accentAlt %>;">
        <span></span><span></span><span></span>
      </div>
      <div class="theme-card-copy">
        <div class="theme-card-title">
          <h3><%= item.name %></h3>
          <span class="theme-kind"><%- item.builtin ? "Built-in &middot; read-only" : "Custom" %></span>
        </div>
        <p><%= item.description %></p>
      </div>
      <div class="theme-card-actions">
        <% if (item.id !== activeTheme.id) { %>
        <form method="post" action="/admin/theming/select">
          <input type="hidden" name="theme_id" value="<%= item.id %>" />
          <%- include("partials/state-button", {
            type: "submit",
            classes: "subtle",
            states: [
              { id: "idle", text: "Apply" },
              { id: "loading", text: "Applying", spinner: true },
              { id: "success", text: "Applied" }
            ]
          }) %>
        </form>
        <% } else { %>
        <span class="button subtle disabled" aria-current="true">Active</span>
        <% } %>
        <% if (!item.builtin) { %>
        <a class="button subtle" href="/admin/theming?edit=<%= encodeURIComponent(item.id) %>#theme-editor">Edit</a>
        <% } %>
      </div>
      <details class="theme-card-more">
        <summary>More actions</summary>
        <div class="theme-card-more-body">
          <form method="post" action="/admin/theming/duplicate" class="compact-form">
            <input type="hidden" name="theme_id" value="<%= item.id %>" />
            <label>
              <span>Copy name</span>
              <input name="name" value="<%= item.name %> Copy" maxlength="60" required />
            </label>
            <%- include("partials/state-button", {
              type: "submit",
              states: [
                { id: "idle", text: "Duplicate" },
                { id: "loading", text: "Duplicating", spinner: true },
                { id: "success", text: "Created" }
              ]
            }) %>
          </form>
          <% if (!item.builtin) { %>
          <form method="post" action="/admin/theming/custom/<%= customId %>/rename" class="compact-form">
            <label>
              <span>Theme name</span>
              <input name="name" value="<%= item.name %>" maxlength="60" required />
            </label>
            <%- include("partials/state-button", {
              type: "submit",
              classes: "subtle",
              states: [
                { id: "idle", text: "Rename" },
                { id: "loading", text: "Renaming", spinner: true },
                { id: "success", text: "Renamed" }
              ]
            }) %>
          </form>
          <form
            method="post"
            action="/admin/theming/custom/<%= customId %>/delete"
            data-confirm-mode="modal"
            data-confirm-title="Delete custom theme"
            data-confirm-text="Delete <%= item.name %>? Built-in themes are not affected."
            data-confirm-label="Delete theme"
          >
            <button type="submit" class="button danger">Delete</button>
          </form>
          <% } %>
        </div>
      </details>
    </article>
    <% }) %>
  </div>
</section>

<% if (editingTheme) { %>
<section class="theme-editor-shell" id="theme-editor" data-theme-editor>
  <div class="theme-editor-main card">
    <div class="section-header">
      <div>
        <span class="eyebrow">Custom theme</span>
        <h2>Edit <%= editingTheme.name %></h2>
        <p class="hint">Based on <%= themes.find((item) => item.id === editingTheme.baseThemeId)?.name || "Lumi Default" %>.</p>
      </div>
      <div class="button-group" aria-label="Preview color scheme">
        <button type="button" class="button subtle is-selected" data-theme-preview-mode="light">Light preview</button>
        <button type="button" class="button subtle" data-theme-preview-mode="dark">Dark preview</button>
        <button type="button" class="button subtle theme-mobile-preview-action" data-theme-popout>Preview</button>
      </div>
    </div>

    <form
      method="post"
      action="/admin/theming/custom/<%= editingTheme.id.replace('custom:', '') %>/save"
      class="theme-edit-form"
      data-theme-form
      data-lumi-enhanced-form
      data-lumi-form-id="theme-editor"
    >
      <% ["light", "dark"].forEach((mode) => { %>
      <fieldset class="theme-fieldset" data-theme-mode-fields="<%= mode %>">
        <legend><%= mode === "light" ? "Light mode" : "Dark mode" %></legend>
        <div class="theme-control-grid">
          <% basicFields.forEach((field) => { %>
          <label class="theme-color-control">
            <span><%= fieldLabels[field] %></span>
            <span class="theme-color-input">
              <input
                type="color"
                name="<%= mode %>_<%= field %>"
                value="<%= editingTheme[mode][field] %>"
                data-theme-token="<%= field %>"
                data-theme-mode="<%= mode %>"
                data-base-value="<%= baseTheme[mode][field] %>"
              />
              <output><%= editingTheme[mode][field] %></output>
            </span>
          </label>
          <% }) %>
        </div>
        <details class="advanced-theme-controls">
          <summary>Advanced <%= mode %> variables</summary>
          <div class="theme-control-grid">
            <% advancedFields.forEach((field) => { %>
            <label class="theme-color-control">
              <span><%= fieldLabels[field] %></span>
              <span class="theme-color-input">
                <input
                  type="color"
                  name="<%= mode %>_<%= field %>"
                  value="<%= editingTheme[mode][field] %>"
                  data-theme-token="<%= field %>"
                  data-theme-mode="<%= mode %>"
                  data-base-value="<%= baseTheme[mode][field] %>"
                />
                <output><%= editingTheme[mode][field] %></output>
              </span>
            </label>
            <% }) %>
          </div>
        </details>
      </fieldset>
      <% }) %>

      <fieldset class="theme-fieldset">
        <legend>Roles and shape</legend>
        <div class="theme-control-grid">
          <% ["public", "mod", "admin"].forEach((role) => { %>
          <label class="theme-color-control">
            <span><%= role.charAt(0).toUpperCase() + role.slice(1) %> role</span>
            <span class="theme-color-input">
              <input type="color" name="role_<%= role %>" value="<%= editingTheme.role[role] %>" data-theme-role="<%= role %>" data-base-value="<%= baseTheme.role[role] %>" />
              <output><%= editingTheme.role[role] %></output>
            </span>
          </label>
          <% }) %>
          <label class="theme-range-control">
            <span>Border radius <output data-range-output><%= editingTheme.metrics.radius %>px</output></span>
            <input type="range" name="metrics_radius" min="0" max="32" step="1" value="<%= editingTheme.metrics.radius %>" data-theme-metric="radius" data-unit="px" data-base-value="<%= baseTheme.metrics.radius %>" />
          </label>
          <label class="theme-range-control">
            <span>Shadow strength <output data-range-output><%= editingTheme.metrics.shadowStrength %></output></span>
            <input type="range" name="metrics_shadowStrength" min="0" max="0.35" step="0.01" value="<%= editingTheme.metrics.shadowStrength %>" data-theme-metric="shadowStrength" data-base-value="<%= baseTheme.metrics.shadowStrength %>" />
          </label>
          <label class="theme-range-control">
            <span>Spacing scale <output data-range-output><%= editingTheme.metrics.spacingScale %></output></span>
            <input type="range" name="metrics_spacingScale" min="0.75" max="1.35" step="0.05" value="<%= editingTheme.metrics.spacingScale %>" data-theme-metric="spacingScale" data-base-value="<%= baseTheme.metrics.spacingScale %>" />
          </label>
        </div>
      </fieldset>

      <fieldset class="theme-fieldset">
        <legend>Typography</legend>
        <div class="theme-control-grid">
          <% [
            ["bodyFont", "Body font", "data-theme-font='body'"],
            ["displayFont", "Heading font", "data-theme-font='display'"],
            ["monoFont", "Monospace font", "data-theme-font='mono'"]
          ].forEach(([field, label, dataAttr]) => { %>
          <label class="theme-select-control">
            <span><%= label %></span>
            <select
              name="typography_<%= field %>"
              <%- dataAttr %>
              data-base-value="<%= baseTheme.typography[field] %>"
            >
              <% fontStackEntries.forEach(([key, font]) => { %>
              <option value="<%= key %>" data-font-stack="<%= font.stack %>" <%= editingTheme.typography[field] === key ? "selected" : "" %>><%= font.label %></option>
              <% }) %>
            </select>
          </label>
          <% }) %>
          <label class="theme-range-control">
            <span>Base text size <output data-range-output><%= editingTheme.typography.baseSize %>px</output></span>
            <input type="range" name="typography_baseSize" min="14" max="19" step="1" value="<%= editingTheme.typography.baseSize %>" data-theme-typography="baseSize" data-unit="px" data-base-value="<%= baseTheme.typography.baseSize %>" />
          </label>
          <label class="theme-range-control">
            <span>Heading scale <output data-range-output><%= editingTheme.typography.headingScale %></output></span>
            <input type="range" name="typography_headingScale" min="0.9" max="1.2" step="0.01" value="<%= editingTheme.typography.headingScale %>" data-theme-typography="headingScale" data-base-value="<%= baseTheme.typography.headingScale %>" />
          </label>
          <label class="theme-range-control">
            <span>Control density <output data-range-output><%= editingTheme.typography.controlScale %></output></span>
            <input type="range" name="typography_controlScale" min="0.9" max="1.12" step="0.01" value="<%= editingTheme.typography.controlScale %>" data-theme-typography="controlScale" data-base-value="<%= baseTheme.typography.controlScale %>" />
          </label>
        </div>
        <div class="theme-inline-actions">
          <button type="button" class="button subtle" data-theme-reset-to-base>Reset changed controls to base theme</button>
        </div>
      </fieldset>

      <div class="theme-validation-panel" data-theme-warnings aria-live="polite"></div>
      <p class="hint lumi-form-status" data-lumi-form-status role="status" aria-live="polite">Draft changes stay in this preview until you save.</p>

      <div class="theme-editor-actions">
        <label class="switch">
          <input type="checkbox" class="switch-input" name="apply" <%= editingTheme.id === activeTheme.id ? "checked" : "" %> />
          <span class="switch-track" aria-hidden="true"></span>
          <span class="switch-text">Apply globally after saving</span>
        </label>
        <div class="button-group">
          <%- include("partials/state-button", {
            type: "button",
            classes: "subtle",
            attrs: "data-theme-reset",
            resetDelay: 1200,
            states: [
              { id: "idle", text: "Revert unsaved" },
              { id: "success", text: "Reverted" }
            ]
          }) %>
          <a href="/admin/theming" class="button subtle">Cancel</a>
          <%- include("partials/state-button", {
            type: "submit",
            states: [
              { id: "idle", text: "Save theme" },
              { id: "loading", text: "Saving", spinner: true },
              { id: "success", text: "Saved" }
            ]
          }) %>
        </div>
      </div>
    </form>
  </div>

  <aside class="theme-preview card" aria-label="Live theme preview">
    <div class="theme-preview-header">
      <span class="eyebrow">Live preview</span>
      <button type="button" class="button subtle theme-popout-button" data-theme-popout>Pop out</button>
    </div>
    <div class="theme-preview-window" data-theme-preview-root>
      <div class="theme-preview-nav">
        <span class="theme-preview-logo">L</span>
        <span class="is-active"></span><span></span><span></span>
      </div>
      <div class="theme-preview-content">
        <span class="eyebrow theme-preview-pill">Preview pill</span>
        <h2>Theme controlled heading</h2>
        <p class="hint">Typography, spacing, colors, radius, shadows, and state tokens update only inside this preview.</p>
        <div class="theme-preview-sample-card">
          <strong>Community overview</strong>
          <p>Preview text, surfaces, borders, and controls before saving.</p>
          <div class="button-group">
            <span class="button">Primary</span>
            <span class="button subtle">Secondary</span>
            <span class="button lumi-state-btn">
              <span class="lumi-state-btn-content">
                <span data-state-view="idle">Download</span>
                <span data-state-view="loading" data-state-hidden="true"><span class="lumi-state-btn-spinner" aria-hidden="true"></span>Downloading</span>
                <span data-state-view="success" data-state-hidden="true">Downloaded</span>
              </span>
            </span>
          </div>
          <input value="Input preview" readonly aria-label="Input preview" />
          <label class="switch">
            <input class="switch-input" type="checkbox" checked />
            <span class="switch-track" aria-hidden="true"></span>
            <span class="switch-text">Toggle sample</span>
          </label>
          <div class="theme-preview-statuses">
            <span class="status-success">Success</span>
            <span class="status-warning">Warning</span>
            <span class="status-danger">Danger</span>
          </div>
          <div class="theme-preview-badges">
            <span class="badge">Badge</span>
            <span class="pill">Role <span><span class="theme-role-swatch" aria-hidden="true"></span>admin</span></span>
          </div>
          <div class="is-unsaved theme-preview-dirty">Dirty state marker</div>
          <div class="table-wrap theme-preview-table">
            <table class="table">
              <thead><tr><th>Level</th><th>Message</th></tr></thead>
              <tbody><tr><td>Info</td><td>Command synced</td></tr><tr><td>Warn</td><td>Queue growing</td></tr></tbody>
            </table>
          </div>
          <div class="theme-preview-modal-sample">
            <strong>Modal sample</strong>
            <p class="hint">Radius, border, surface, and shadow.</p>
          </div>
          <div class="theme-spacing-sample"><span></span><span></span><span></span></div>
        </div>
      </div>
    </div>
    <p class="hint" data-theme-popout-status>Preview changes are local to this page until you save.</p>
  </aside>
</section>
<% } else { %>
<section class="empty-state">
  <div>
    <h2>Create a custom theme to edit</h2>
    <p>Open "More actions" on any built-in or custom theme, then duplicate it.</p>
  </div>
</section>
<% } %>

<script src="/theme-editor.js?v=<%= assetVersion %>" defer></script>
<%- include("partials/layout-bottom") %>
