import { normalizeEngineOverrideEntries } from "./engineOverrides";

export const DEFAULT_WORLDSHAPER_THEME_PRESET = "azure";

export const WORLDSHAPER_THEME_PRESETS = [
  {
    id: "azure",
    label: "Azure",
    swatch: ["#17325d", "#244c84", "#7fd1ff", "#10203c"],
    vars: {
      "--editor-shell-bg": "#0A1020",
      "--editor-shell-fg": "#D8E8FF",
      "--editor-menu-grad-1": "#152645",
      "--editor-menu-grad-2": "#10203C",
      "--editor-sidebar-bg": "#0E1A33",
      "--editor-stage-bg": "#060A14",
      "--editor-border": "#2E426C",
      "--editor-border-strong": "#3C5E95",
      "--editor-panel-bg": "#121F3B",
      "--editor-panel-bg-alt": "#132B4F",
      "--editor-panel-bg-elevated": "#10284B",
      "--editor-panel-bg-hover": "#1A3F6D",
      "--editor-control-bg": "#1A345E",
      "--editor-control-bg-hover": "#214679",
      "--editor-control-bg-active": "#1E4B82",
      "--editor-control-border": "#3C5E95",
      "--editor-control-fg": "#D6E7FF",
      "--editor-muted": "#9FB8E5",
      "--editor-muted-strong": "#CFE2FF",
      "--editor-accent": "#64AAF8",
      "--editor-accent-strong": "#8FD0FF",
      "--editor-accent-soft": "#22466E",
      "--editor-tool-armed": "#7EE8C6",
      "--editor-tool-armed-soft": "#1A3C40",
      "--editor-warn": "#FFD166",
      "--editor-danger": "#3C1A1A",
      "--editor-danger-border": "#7F4C4C",
      "--editor-danger-hover": "#5A2323",
      "--editor-preview-bg": "#0D1B34",
      "--editor-drop-line": "#64AAF8",
      "--editor-drop-shadow": "rgba(100, 170, 248, 0.3)",
      "--editor-status-ok": "#B9CFEF",
      "--editor-status-error": "#FF9E9E",
      "--editor-tooltip-shadow": "rgba(0, 0, 20, 0.8)",
      "--editor-tab-shadow": "rgba(3, 8, 18, 0.8)",
    },
  },
  {
    id: "verdant",
    label: "Verdant",
    swatch: ["#17372E", "#285B4A", "#7CE0AF", "#0E251E"],
    vars: {
      "--editor-shell-bg": "#081510",
      "--editor-shell-fg": "#DDF7EA",
      "--editor-menu-grad-1": "#16352B",
      "--editor-menu-grad-2": "#0E251E",
      "--editor-sidebar-bg": "#0D221B",
      "--editor-stage-bg": "#06100D",
      "--editor-border": "#305847",
      "--editor-border-strong": "#46806A",
      "--editor-panel-bg": "#122A22",
      "--editor-panel-bg-alt": "#17362C",
      "--editor-panel-bg-elevated": "#133127",
      "--editor-panel-bg-hover": "#21503F",
      "--editor-control-bg": "#1B4335",
      "--editor-control-bg-hover": "#245844",
      "--editor-control-bg-active": "#2D7258",
      "--editor-control-border": "#46806A",
      "--editor-control-fg": "#DDF7EA",
      "--editor-muted": "#A5D2BE",
      "--editor-muted-strong": "#D2F0E0",
      "--editor-accent": "#70D8A6",
      "--editor-accent-strong": "#8AE8BE",
      "--editor-accent-soft": "#275845",
      "--editor-tool-armed": "#8FD8FF",
      "--editor-tool-armed-soft": "#173642",
      "--editor-warn": "#F5D66D",
      "--editor-danger": "#472123",
      "--editor-danger-border": "#8B5559",
      "--editor-danger-hover": "#633034",
      "--editor-preview-bg": "#10271F",
      "--editor-drop-line": "#70D8A6",
      "--editor-drop-shadow": "rgba(112, 216, 166, 0.3)",
      "--editor-status-ok": "#C0E9D5",
      "--editor-status-error": "#FFADAD",
      "--editor-tooltip-shadow": "rgba(0, 12, 8, 0.78)",
      "--editor-tab-shadow": "rgba(2, 10, 8, 0.76)",
    },
  },
  {
    id: "ember",
    label: "Ember",
    swatch: ["#4F231C", "#87412F", "#FFB36C", "#24110F"],
    vars: {
      "--editor-shell-bg": "#160C0B",
      "--editor-shell-fg": "#FFE8D9",
      "--editor-menu-grad-1": "#432018",
      "--editor-menu-grad-2": "#24110F",
      "--editor-sidebar-bg": "#21110E",
      "--editor-stage-bg": "#100706",
      "--editor-border": "#6A3B33",
      "--editor-border-strong": "#9A5A4D",
      "--editor-panel-bg": "#311A16",
      "--editor-panel-bg-alt": "#3F211B",
      "--editor-panel-bg-elevated": "#341B17",
      "--editor-panel-bg-hover": "#5A2E26",
      "--editor-control-bg": "#4A261F",
      "--editor-control-bg-hover": "#67352B",
      "--editor-control-bg-active": "#8B4937",
      "--editor-control-border": "#9A5A4D",
      "--editor-control-fg": "#FFE8D9",
      "--editor-muted": "#E2B6A2",
      "--editor-muted-strong": "#FFE0CF",
      "--editor-accent": "#FFB36C",
      "--editor-accent-strong": "#FFD08E",
      "--editor-accent-soft": "#684133",
      "--editor-tool-armed": "#FF9D8A",
      "--editor-tool-armed-soft": "#4A2824",
      "--editor-warn": "#FFE17A",
      "--editor-danger": "#512225",
      "--editor-danger-border": "#A16063",
      "--editor-danger-hover": "#6A2E32",
      "--editor-preview-bg": "#281311",
      "--editor-drop-line": "#FFB36C",
      "--editor-drop-shadow": "rgba(255, 179, 108, 0.32)",
      "--editor-status-ok": "#F6C8AF",
      "--editor-status-error": "#FFB1A3",
      "--editor-tooltip-shadow": "rgba(20, 6, 0, 0.76)",
      "--editor-tab-shadow": "rgba(16, 6, 2, 0.76)",
    },
  },
  {
    id: "amethyst",
    label: "Amethyst",
    swatch: ["#342456", "#5A3B8A", "#D3A8FF", "#171125"],
    vars: {
      "--editor-shell-bg": "#0F0B19",
      "--editor-shell-fg": "#F0E6FF",
      "--editor-menu-grad-1": "#2A1F45",
      "--editor-menu-grad-2": "#171125",
      "--editor-sidebar-bg": "#17112A",
      "--editor-stage-bg": "#0A0712",
      "--editor-border": "#4E4474",
      "--editor-border-strong": "#7662A9",
      "--editor-panel-bg": "#211A39",
      "--editor-panel-bg-alt": "#2A2149",
      "--editor-panel-bg-elevated": "#241D41",
      "--editor-panel-bg-hover": "#3B3066",
      "--editor-control-bg": "#35295D",
      "--editor-control-bg-hover": "#473678",
      "--editor-control-bg-active": "#5B4594",
      "--editor-control-border": "#7662A9",
      "--editor-control-fg": "#F0E6FF",
      "--editor-muted": "#C6B3E6",
      "--editor-muted-strong": "#E5D9FF",
      "--editor-accent": "#C38BFF",
      "--editor-accent-strong": "#DDB5FF",
      "--editor-accent-soft": "#493C72",
      "--editor-tool-armed": "#8FE7FF",
      "--editor-tool-armed-soft": "#22384C",
      "--editor-warn": "#F7D37E",
      "--editor-danger": "#4A213F",
      "--editor-danger-border": "#935C8A",
      "--editor-danger-hover": "#632D56",
      "--editor-preview-bg": "#1A1430",
      "--editor-drop-line": "#C38BFF",
      "--editor-drop-shadow": "rgba(195, 139, 255, 0.32)",
      "--editor-status-ok": "#D9C5FF",
      "--editor-status-error": "#FFB6DE",
      "--editor-tooltip-shadow": "rgba(10, 4, 24, 0.8)",
      "--editor-tab-shadow": "rgba(10, 6, 20, 0.78)",
    },
  },
];

const themePresetIds = new Set(WORLDSHAPER_THEME_PRESETS.map((preset) => preset.id));

export function normalizeWorldshaperThemePreset(value: unknown): string {
  const normalized = String(value || "").trim().toLowerCase();
  return themePresetIds.has(normalized) ? normalized : DEFAULT_WORLDSHAPER_THEME_PRESET;
}

export function getWorldshaperStudioThemePreset(value: unknown) {
  const presetId = normalizeWorldshaperThemePreset(value);
  return WORLDSHAPER_THEME_PRESETS.find((preset) => preset.id === presetId) || WORLDSHAPER_THEME_PRESETS[0];
}

export function getWorldshaperThemeLabel(value: unknown): string {
  return getWorldshaperStudioThemePreset(value).label;
}

export function applyWorldshaperThemePreset(value: unknown, targetDocument: Document = document): string {
  const presetId = normalizeWorldshaperThemePreset(value);
  targetDocument.documentElement.setAttribute("data-editor-theme", presetId);
  return presetId;
}

export function getDefaultEditorSettings() {
  return {
    schemaVersion: 1,
    worldshaperStudio: {
      themePreset: DEFAULT_WORLDSHAPER_THEME_PRESET,
      engineOverrides: [],
    },
  };
}

export function normalizeEditorSettings(value: unknown) {
  const fallback = getDefaultEditorSettings();
  const source = value && typeof value === "object" && !Array.isArray(value)
    ? value as Record<string, unknown>
    : {};
  const worldshaperStudioSource = source.worldshaperStudio && typeof source.worldshaperStudio === "object" && !Array.isArray(source.worldshaperStudio)
    ? source.worldshaperStudio as Record<string, unknown>
    : {};
  return {
    schemaVersion: typeof source.schemaVersion === "number" ? source.schemaVersion : fallback.schemaVersion,
    worldshaperStudio: {
      themePreset: normalizeWorldshaperThemePreset(worldshaperStudioSource.themePreset),
      engineOverrides: normalizeEngineOverrideEntries(worldshaperStudioSource.engineOverrides),
    },
  };
}

async function readErrorResponse(response: Response): Promise<string> {
  try {
    const text = await response.text();
    const trimmed = String(text || "").trim();
    return trimmed ? `: ${trimmed.slice(0, 240)}` : "";
  } catch {
    return "";
  }
}

export async function fetchEditorSettings(apiBase: string) {
  const normalizedBase = String(apiBase || "").replace(/\/+$/, "");
  try {
    const response = await fetch(normalizedBase + "/api/editor-settings");
    if (!response.ok) {
      return getDefaultEditorSettings();
    }
    return normalizeEditorSettings(await response.json());
  } catch {
    return getDefaultEditorSettings();
  }
}

export async function persistEditorSettings(apiBase: string, value: unknown) {
  const normalizedBase = String(apiBase || "").replace(/\/+$/, "");
  const payload = normalizeEditorSettings(value);
  const response = await fetch(normalizedBase + "/api/editor-settings", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  });
  if (!response.ok) {
    throw new Error("Theme save failed (" + response.status + ")" + await readErrorResponse(response));
  }
  return normalizeEditorSettings(await response.json());
}

function varsToCss(vars: Record<string, string>): string {
  return Object.entries(vars)
    .map(([key, val]) => `${key}: ${val};`)
    .join(" ");
}

export function buildWorldshaperStudioThemeOverrideCss(): string {
  const rootCss = `:root { ${varsToCss(WORLDSHAPER_THEME_PRESETS[0].vars)} }`;
  const presetCss = WORLDSHAPER_THEME_PRESETS
    .map((preset) => `html[data-editor-theme="${preset.id}"] { ${varsToCss(preset.vars)} }`)
    .join("\n");

  return `
    ${rootCss}
    ${presetCss}
    html, body {
      background: var(--editor-shell-bg) !important;
      color: var(--editor-shell-fg) !important;
    }
    .menu-bar {
      border-bottom-color: var(--editor-border) !important;
      background: linear-gradient(180deg, var(--editor-menu-grad-1) 0%, var(--editor-menu-grad-2) 100%) !important;
    }
    .menu-bar-right {
      margin-left: auto;
      display: grid;
      grid-template-columns: auto 180px;
      align-items: center;
      gap: 10px;
      min-width: 0;
    }
    .theme-preset-bar {
      display: grid;
      grid-template-columns: repeat(4, 40px);
      align-items: center;
      gap: 6px;
    }
    .theme-preset-btn {
      width: 40px;
      height: 40px;
      padding: 0;
      border: 1px solid var(--editor-control-border);
      border-radius: 10px;
      background: var(--editor-panel-bg);
      display: inline-flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: transform 120ms ease, border-color 120ms ease, box-shadow 120ms ease;
      overflow: visible;
    }
    .theme-preset-btn:hover {
      transform: translateY(-1px);
      border-color: var(--editor-accent);
    }
    .theme-preset-btn.active {
      border-color: var(--editor-accent);
      box-shadow: 0 0 0 1px var(--editor-accent);
    }
    .theme-preset-btn:focus-visible {
      outline: none;
      border-color: var(--editor-accent);
      box-shadow: 0 0 0 1px var(--editor-accent);
    }
    .theme-preset-swatch {
      width: 24px;
      height: 24px;
      border-radius: 7px;
      border: 1px solid rgba(255, 255, 255, 0.18);
      background:
        linear-gradient(135deg, var(--theme-swatch-a) 0 50%, var(--theme-swatch-b) 50% 100%),
        linear-gradient(315deg, var(--theme-swatch-c) 0 50%, var(--theme-swatch-d) 50% 100%);
      box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.08);
      transition: transform 120ms ease;
      transform-origin: center;
    }
    .theme-preset-btn.active .theme-preset-swatch,
    .theme-preset-btn:focus-visible .theme-preset-swatch {
      transform: scale(1.18);
    }
    .save-status {
      width: 180px;
      min-width: 180px;
      max-width: 180px;
      font-size: 12px;
      color: var(--editor-status-ok);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      text-align: left;
      cursor: context-menu;
    }
    .sidebar,
    .sidebar-tabs,
    .sidebar-tabs::before {
      background: var(--editor-sidebar-bg) !important;
    }
    .sidebar,
    .sidebar-tabs,
    .history-preview,
    .npc-editor-panel,
    .npc-compact-menu,
    .at-tooltip-panel,
    .stage,
    .meta {
      border-color: var(--editor-border) !important;
    }
    .stage {
      background: var(--editor-stage-bg) !important;
    }
    .menu-btn,
    .menu-layer-select,
    .layer-delete-btn,
    .mini-btn,
    .canvas-tool-btn,
    .panel-square-btn,
    .selector-drag-handle,
    .layer-drag-handle,
    .layer-visibility-btn,
    .icon-action-btn,
    .background-mode-btn,
    .npc-icon-btn,
    .folder-toggle-btn,
    .sprite-dropdown-btn,
    .sprite-option-btn,
    .at-tooltip-item,
    .paint-swatch-btn,
    .selector-section-toggle,
    .selector-section-label,
    .map-manager select,
    .map-manager input:not([type="color"]),
    .npc-editor-row input,
    .npc-editor-row select {
      border-color: var(--editor-control-border) !important;
      background: var(--editor-control-bg) !important;
      color: var(--editor-control-fg) !important;
    }
    .menu-btn:hover,
    .layer-delete-btn:hover,
    .panel-square-btn:hover,
    .canvas-tool-btn:hover,
    .selector-drag-handle:hover,
    .layer-drag-handle:hover,
    .mini-btn:hover,
    .background-mode-btn:hover,
    .icon-action-btn:hover,
    .sprite-option-btn:hover,
    .at-tooltip-item:hover,
    .at-tooltip-item.active,
    .selector-drag-handle.dragging,
    .selector-drag-handle:active {
      background: var(--editor-control-bg-hover) !important;
    }
    .sidebar-tab-btn,
    .layer-row,
    .history-row,
    .folder-row,
    .folder-empty,
    .folder-root-drop-zone,
    .legend-item,
    .history-preview,
    .background-mode-preview,
    .npc-thumb,
    .npc-thumb-fallback,
    .info-help-panel {
      border-color: var(--editor-border) !important;
      background: var(--editor-panel-bg) !important;
      color: var(--editor-control-fg) !important;
    }
    .npc-editor-panel,
    .npc-compact-menu,
    .sprite-dropdown-menu {
      background: var(--editor-panel-bg-elevated) !important;
    }
    .npc-editor-panel,
    .npc-compact-menu,
    .sprite-dropdown-menu,
    .info-footer-bar {
      border-color: var(--editor-border) !important;
    }
    .info-footer-bar {
      background: linear-gradient(180deg, var(--editor-menu-grad-1) 0%, var(--editor-menu-grad-2) 100%) !important;
    }
    .info-footer-link {
      color: var(--editor-accent-strong) !important;
    }
    .info-footer-link:hover,
    .info-footer-link:focus-visible {
      color: var(--editor-shell-fg) !important;
    }
    .sidebar-tab-btn,
    .mini-btn,
    .selector-section-toggle,
    .selector-section-label {
      background: var(--editor-panel-bg-alt) !important;
      color: var(--editor-muted-strong) !important;
    }
    .sidebar-tab-btn.active,
    .layer-row.active,
    .npc-row.active,
    .layer-visibility-btn.active,
    .npc-icon-btn.active,
    .sprite-option-btn.active,
    .canvas-tool-btn.active {
      border-color: var(--editor-accent) !important;
      background: var(--editor-control-bg-active) !important;
      color: var(--editor-shell-fg) !important;
    }
    .history-row.active,
    .paint-swatch-btn.active {
      border-color: var(--editor-warn) !important;
      background: var(--editor-accent-soft) !important;
    }
    .layer-row.layer-add-row,
    .folder-root-drop-active {
      border-color: var(--editor-accent) !important;
      background: var(--editor-accent-soft) !important;
    }
    .folder-row {
      background: var(--editor-panel-bg-alt) !important;
      border-color: var(--editor-control-border) !important;
    }
    .folder-empty,
    .folder-root-drop-zone {
      color: var(--editor-muted) !important;
    }
    .folder-children {
      border-left-color: var(--editor-drop-shadow) !important;
    }
    .layer-row-wrap.reorder-drop-before::before,
    .layer-row-wrap.reorder-drop-after::after,
    .folder-drop-before::before,
    .folder-drop-after::after {
      background: var(--editor-drop-line) !important;
      box-shadow: 0 0 0 1px var(--editor-drop-shadow) !important;
    }
    .folder-drop-inside {
      box-shadow: inset 0 0 0 1px var(--editor-drop-line) !important;
    }
    .icon-action-btn.danger {
      border-color: var(--editor-danger-border) !important;
      background: var(--editor-danger) !important;
    }
    .icon-action-btn.danger:hover {
      background: var(--editor-danger-hover) !important;
    }
    .background-mode-preview {
      background: var(--editor-preview-bg) !important;
    }
    .background-mode-title,
    .history-preview h4,
    .meta-stats {
      color: var(--editor-shell-fg) !important;
    }
    .menu-layer-label,
    .field-row label,
    .map-manager label,
    .npc-editor-row label,
    .background-mode-meta,
    .history-meta,
    .history-preview-empty,
    .at-tooltip-label,
    .legend,
    .meta,
    .selector-section-chevron,
    .info-help-title,
    .shortcut-plus {
      color: var(--editor-muted) !important;
    }
    .shortcut-action,
    .shortcut-mouse-label {
      color: var(--editor-muted-strong) !important;
    }
    .sidebar h3 {
      color: var(--editor-muted) !important;
    }
    .at-tooltip-panel {
      background: var(--editor-panel-bg-elevated) !important;
      box-shadow: 0 6px 28px var(--editor-tooltip-shadow) !important;
    }
    .sidebar-tabs {
      box-shadow: 0 8px 14px var(--editor-tab-shadow) !important;
    }
  `;
}

