/**
 * Shell HTML renderer.
 *
 * Wraps module content in the shared rSpace layout: header with app/space
 * switchers + identity, <main> with module content, shell script + styles.
 */

import type { ModuleInfo, SubPageInfo } from "../shared/module";
import { getDocumentData } from "./community-store";

/** Extract enabledModules and encryption status from a loaded space. */
export function getSpaceShellMeta(spaceSlug: string): { enabledModules: string[] | null; spaceEncrypted: boolean } {
	const data = getDocumentData(spaceSlug);
	return {
		enabledModules: data?.meta?.enabledModules ?? null,
		spaceEncrypted: !!data?.meta?.encrypted,
	};
}

export interface ShellOptions {
	/** Page <title> */
	title: string;
	/** Current module ID (highlighted in app switcher) */
	moduleId: string;
	/** Current space slug */
	spaceSlug: string;
	/** Space display name */
	spaceName?: string;
	/** Module HTML content to inject into <main> */
	body: string;
	/** Additional <script type="module"> tags for module-specific JS */
	scripts?: string;
	/** Additional <link>/<style> tags for module-specific CSS */
	styles?: string;
	/** List of available modules (for app switcher) */
	modules: ModuleInfo[];
	/** Theme for the header: 'dark' or 'light' */
	theme?: "dark" | "light";
	/** Extra <head> content (meta tags, preloads, etc.) */
	head?: string;
	/** Space visibility level (for client-side access gate) */
	spaceVisibility?: string;
	/** Enabled modules for this space (null = all). Filters the app switcher. */
	enabledModules?: string[] | null;
	/** Whether this space has client-side encryption enabled */
	spaceEncrypted?: boolean;
}

export function renderShell(opts: ShellOptions): string {
	const {
		title,
		moduleId,
		spaceSlug,
		spaceName,
		body,
		scripts = "",
		styles = "",
		modules,
		theme = "dark",
		head = "",
		spaceVisibility = "public",
	} = opts;

	// Auto-populate from space data when not explicitly provided
	const spaceMeta = (opts.enabledModules === undefined || opts.spaceEncrypted === undefined)
		? getSpaceShellMeta(spaceSlug)
		: null;
	const enabledModules = opts.enabledModules ?? spaceMeta?.enabledModules ?? null;
	const spaceEncrypted = opts.spaceEncrypted ?? spaceMeta?.spaceEncrypted ?? false;

	// Filter modules by enabledModules (null = show all)
	const visibleModules = enabledModules
		? modules.filter(m => m.id === "rspace" || enabledModules.includes(m.id))
		: modules;
	const moduleListJSON = JSON.stringify(visibleModules);
	const shellDemoUrl = `https://demo.rspace.online/${escapeAttr(moduleId)}`;

	return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🌌</text></svg>">
  <title>${escapeHtml(title)}</title>
  <script>(function(){var t=localStorage.getItem('canvas-theme');if(!t)t=matchMedia('(prefers-color-scheme:light)').matches?'light':'dark';document.documentElement.setAttribute('data-theme',t)})()</script>
  <link rel="stylesheet" href="/theme.css?v=1">
  <link rel="stylesheet" href="/shell.css?v=8">
  <style>
    /* When loaded inside an iframe (e.g. standalone domain redirecting back),
       hide the shell chrome — the parent rSpace page already provides it. */
    html.rspace-embedded .rstack-header { display: none !important; }
    html.rspace-embedded .rstack-tab-row { display: none !important; }
    html.rspace-embedded #app { padding-top: 0 !important; }
    html.rspace-embedded .rspace-iframe-loading,
    html.rspace-embedded .rspace-iframe-error { top: 0 !important; }
  </style>
  <script>if (window.self !== window.parent) document.documentElement.classList.add('rspace-embedded');</script>
  ${styles}
  ${head}
  <style>${WELCOME_CSS}</style>
  <style>${ACCESS_GATE_CSS}</style>
</head>
<body data-space-visibility="${escapeAttr(spaceVisibility)}">
  <header class="rstack-header">
    <div class="rstack-header__left">
      <a href="/" style="display:flex;align-items:center;margin-right:4px"><img src="/favicon.png" alt="rSpace" class="rstack-header__logo"></a>
      <rstack-app-switcher current="${escapeAttr(moduleId)}"></rstack-app-switcher>
      <rstack-space-switcher current="${escapeAttr(spaceSlug)}" name="${escapeAttr(spaceName || spaceSlug)}"></rstack-space-switcher>${spaceEncrypted ? '<span class="rstack-header__encrypted" title="End-to-end encrypted space">&#x1F512;</span>' : ''}<button class="rstack-header__settings-btn" id="settings-btn" title="Space Settings" style="background:none;border:none;color:var(--rs-text-secondary);cursor:pointer;padding:4px;margin-left:4px;display:flex;align-items:center;border-radius:4px;transition:color 0.15s,background 0.15s;" onmouseover="this.style.color='var(--rs-text-primary)';this.style.background='var(--rs-btn-secondary-bg)'" onmouseout="this.style.color='var(--rs-text-secondary)';this.style.background='none'"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg></button>
    </div>
    <div class="rstack-header__center">
      <rstack-mi></rstack-mi>
    </div>
    <div class="rstack-header__right">
      <a class="rstack-header__demo-btn" ${spaceSlug === "demo" ? 'data-hide' : ''} href="${shellDemoUrl}">Try Demo</a>
      <rstack-notification-bell></rstack-notification-bell>
      <rstack-identity></rstack-identity>
    </div>
  </header>
  <rstack-space-settings space="${escapeAttr(spaceSlug)}"></rstack-space-settings>
  <div class="rstack-tab-row">
    <rstack-tab-bar space="${escapeAttr(spaceSlug)}" active="" view-mode="flat"></rstack-tab-bar>
  </div>
  <main id="app"${moduleId === "rspace" ? ' class="canvas-layout"' : ''}>
    ${body}
  </main>

  ${renderWelcomeOverlay()}

  <script type="module">
    import '/shell.js?v=8';
    // ── Settings panel toggle ──
    document.getElementById('settings-btn')?.addEventListener('click', () => {
      const panel = document.querySelector('rstack-space-settings');
      if (panel) panel.toggle();
    });

    // ── Invite acceptance on page load ──
    (function() {
      var params = new URLSearchParams(window.location.search);
      var inviteToken = params.get('invite');
      if (!inviteToken) return;
      // Remove token from URL immediately
      params.delete('invite');
      var newUrl = window.location.pathname + (params.toString() ? '?' + params.toString() : '');
      history.replaceState(null, '', newUrl);
      // Wait for auth then accept
      function tryAccept() {
        try {
          var raw = localStorage.getItem('encryptid_session');
          if (!raw) return;
          var session = JSON.parse(raw);
          if (!session || !session.accessToken) return;
          fetch('/' + '${escapeAttr(spaceSlug)}' + '/invite/accept', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + session.accessToken },
            body: JSON.stringify({ inviteToken: inviteToken }),
          }).then(function(res) { return res.json(); }).then(function(data) {
            if (data.ok) { window.location.reload(); }
          });
        } catch(e) {}
      }
      tryAccept();
      // Also try after auth-change (if user signs in after landing)
      document.addEventListener('auth-change', tryAccept);
    })();

    // Restore saved theme preference across header / tab-row
    (function(){try{var t=localStorage.getItem('canvas-theme');if(t)document.querySelectorAll('[data-theme]').forEach(function(el){el.setAttribute('data-theme',t)})}catch(e){}})();
    // Provide module list to app switcher
    document.querySelector('rstack-app-switcher')?.setModules(${moduleListJSON});

    // ── "Try Demo" button visibility ──
    // Hidden when logged in. When logged out, shown everywhere except demo.rspace.online
    // (bare rspace.online rewrites to demo internally but still shows the button).
    (function() {
      var btn = document.querySelector('.rstack-header__demo-btn');
      if (!btn) return;
      function update() {
        var loggedIn = false;
        try { loggedIn = !!localStorage.getItem('encryptid_session'); } catch(e) {}
        if (loggedIn) { btn.setAttribute('data-hide', ''); return; }
        var host = window.location.host.split(':')[0];
        if (host === 'demo.rspace.online') { btn.setAttribute('data-hide', ''); }
        else { btn.removeAttribute('data-hide'); }
      }
      update();
      document.addEventListener('auth-change', update);
    })();

    // ── Welcome overlay (first visit to demo) ──
    (function() {
      var currentSpace = '${escapeAttr(spaceSlug)}';
      if (currentSpace !== 'demo') return;
      if (localStorage.getItem('rspace_welcomed')) return;
      var el = document.getElementById('rspace-welcome');
      if (el) el.style.display = 'flex';
    })();
    window.__rspaceDismissWelcome = function() {
      localStorage.setItem('rspace_welcomed', '1');
      var el = document.getElementById('rspace-welcome');
      if (el) el.style.display = 'none';
    };

    // ── Save-gate: prompt sign-in on write when unauthenticated ──
    window.__rspaceSaveGate = function(callback) {
      try {
        var raw = localStorage.getItem('encryptid_session');
        if (raw) {
          var session = JSON.parse(raw);
          if (session && session.accessToken) return true; // authenticated
        }
      } catch(e) {}
      // Not authenticated — show modal
      var identity = document.querySelector('rstack-identity');
      if (identity && identity.showAuthModal) {
        identity.showAuthModal({
          title: 'Sign in to save',
          message: 'Sign in with EncryptID to save your work to your own rSpace.',
          onSuccess: function() { if (typeof callback === 'function') callback(); }
        });
      }
      return false;
    };

    // ── Private space access gate ──
    // If the space is private and no session exists, show a sign-in gate
    (function() {
      var vis = document.body.getAttribute('data-space-visibility');
      if (vis !== 'private') return;
      try {
        var raw = localStorage.getItem('encryptid_session');
        if (raw) {
          var session = JSON.parse(raw);
          if (session && session.accessToken) return;
        }
      } catch(e) {}
      // No valid session — gate the content
      var main = document.getElementById('app');
      if (main) main.style.display = 'none';
      var gate = document.createElement('div');
      gate.id = 'rspace-access-gate';
      gate.innerHTML =
        '<div class="access-gate__card">' +
          '<div class="access-gate__icon">&#x1F512;</div>' +
          '<h2 class="access-gate__title">Private Space</h2>' +
          '<p class="access-gate__desc">This space is private. Sign in to continue.</p>' +
          '<button class="access-gate__btn" id="gate-signin">Sign In</button>' +
        '</div>';
      document.body.appendChild(gate);
      var btn = document.getElementById('gate-signin');
      if (btn) btn.addEventListener('click', function() {
        var identity = document.querySelector('rstack-identity');
        if (identity && identity.showAuthModal) {
          identity.showAuthModal({
            onSuccess: function() {
              gate.remove();
              if (main) main.style.display = '';
            }
          });
        }
      });
    })();

    // ── Tab bar / Layer system initialization ──
    // Tabs persist in localStorage so they survive full-page navigations.
    // When a user opens a new rApp (via the app switcher or tab-add),
    // the next page load reads the existing tabs and adds the new module.
    const tabBar = document.querySelector('rstack-tab-bar');
    const spaceSlug = '${escapeAttr(spaceSlug)}';
    const currentModuleId = '${escapeAttr(moduleId)}';
    const TABS_KEY = 'rspace_tabs_' + spaceSlug;
    const moduleList = ${moduleListJSON};

    if (tabBar) {
      // Provide module list for the + add menu dropdown
      tabBar.setModules(moduleList);

      // Helper: look up a module's display name
      function getModuleLabel(id) {
        const m = moduleList.find(mod => mod.id === id);
        return m ? m.name : id;
      }

      // Helper: create a layer object
      function makeLayer(id, order) {
        return {
          id: 'layer-' + id,
          moduleId: id,
          label: getModuleLabel(id),
          order: order,
          color: '',
          visible: true,
          createdAt: Date.now(),
        };
      }

      // ── Restore tabs from localStorage ──
      let layers;
      try {
        const saved = localStorage.getItem(TABS_KEY);
        layers = saved ? JSON.parse(saved) : [];
        if (!Array.isArray(layers)) layers = [];
      } catch(e) { layers = []; }

      // Ensure the current module is in the tab list
      if (!layers.find(l => l.moduleId === currentModuleId)) {
        layers.push(makeLayer(currentModuleId, layers.length));
      }

      // Persist immediately (includes the newly-added tab)
      localStorage.setItem(TABS_KEY, JSON.stringify(layers));

      // Render all tabs with the current one active
      tabBar.setLayers(layers);
      tabBar.setAttribute('active', 'layer-' + currentModuleId);
      // Track current module as recently used
      if (tabBar.trackRecent) tabBar.trackRecent(currentModuleId);

      // Helper: save current tab list to localStorage
      function saveTabs() {
        localStorage.setItem(TABS_KEY, JSON.stringify(layers));
      }

      // ── Tab cache: instant switching via show/hide DOM panes ──
      let tabCache = null;
      try {
        const TC = window.__RSpaceTabCache;
        if (TC) {
          tabCache = new TC(spaceSlug, currentModuleId);
          if (!tabCache.init()) tabCache = null;
        }
      } catch(e) { tabCache = null; }

      // ── Tab events ──
      tabBar.addEventListener('layer-switch', (e) => {
        const { moduleId } = e.detail;
        saveTabs();
        if (tabCache) {
          tabCache.switchTo(moduleId).then(ok => {
            if (!ok) window.location.href = window.__rspaceNavUrl(spaceSlug, moduleId);
          });
        } else {
          window.location.href = window.__rspaceNavUrl(spaceSlug, moduleId);
        }
      });

      tabBar.addEventListener('layer-add', (e) => {
        const { moduleId } = e.detail;
        if (!layers.find(l => l.moduleId === moduleId)) {
          layers.push(makeLayer(moduleId, layers.length));
        }
        saveTabs();
        if (tabCache) {
          tabCache.switchTo(moduleId).then(ok => {
            if (!ok) window.location.href = window.__rspaceNavUrl(spaceSlug, moduleId);
          });
        } else {
          window.location.href = window.__rspaceNavUrl(spaceSlug, moduleId);
        }
      });

      tabBar.addEventListener('layer-close', (e) => {
        const { layerId } = e.detail;
        const closedModuleId = layerId.replace('layer-', '');
        tabBar.removeLayer(layerId);
        layers = layers.filter(l => l.id !== layerId);
        saveTabs();
        // Remove cached pane from DOM
        if (tabCache) tabCache.removePane(closedModuleId);
        // If we closed the active tab, switch to the first remaining
        if (layerId === 'layer-' + currentModuleId && layers.length > 0) {
          const nextModuleId = layers[0].moduleId;
          if (tabCache) {
            tabCache.switchTo(nextModuleId).then(ok => {
              if (!ok) window.location.href = window.__rspaceNavUrl(spaceSlug, nextModuleId);
            });
          } else {
            window.location.href = window.__rspaceNavUrl(spaceSlug, nextModuleId);
          }
        }
      });

      tabBar.addEventListener('view-toggle', (e) => {
        const { mode } = e.detail;
        document.dispatchEvent(new CustomEvent('layer-view-mode', { detail: { mode } }));
      });

      // ── App-switcher → tab system integration ──
      // When user picks a module from the app-switcher, route through tabs
      // instead of doing a full page navigation.
      const appSwitcher = document.querySelector('rstack-app-switcher');
      if (appSwitcher) {
        appSwitcher.addEventListener('module-select', (e) => {
          const { moduleId } = e.detail;
          // Already on this module? No-op.
          if (moduleId === currentModuleId && !tabCache) return;
          if (moduleId === currentModuleId && tabCache) {
            tabCache.switchTo(moduleId);
            return;
          }
          // Add tab if not already open
          if (!layers.find(l => l.moduleId === moduleId)) {
            layers.push(makeLayer(moduleId, layers.length));
          }
          saveTabs();
          tabBar.setLayers(layers);
          tabBar.setAttribute('active', 'layer-' + moduleId);
          if (tabCache) {
            tabCache.switchTo(moduleId).then(ok => {
              if (!ok) window.location.href = window.__rspaceNavUrl(spaceSlug, moduleId);
            });
          } else {
            window.location.href = window.__rspaceNavUrl(spaceSlug, moduleId);
          }
        });
      }

      // Expose tabBar for CommunitySync integration
      window.__rspaceTabBar = tabBar;

      // ── CommunitySync: merge with Automerge once connected ──
      // NOTE: The TAB LIST is shared via Automerge (which modules are open),
      // but the ACTIVE TAB is always local (determined by the URL / currentModuleId).
      // This prevents windows from fighting over which tab is highlighted.
      document.addEventListener('community-sync-ready', (e) => {
        const sync = e.detail?.sync;
        if (!sync) return;

        const localActiveId = 'layer-' + currentModuleId;

        // Merge: Automerge layers win if they exist, otherwise seed from localStorage
        const remoteLayers = sync.getLayers();
        if (remoteLayers.length > 0) {
          // Ensure current module is also in the Automerge set
          if (!remoteLayers.find(l => l.moduleId === currentModuleId)) {
            const newLayer = makeLayer(currentModuleId, remoteLayers.length);
            sync.addLayer(newLayer);
          }
          layers = sync.getLayers();
          tabBar.setLayers(layers);
          tabBar.setFlows(sync.getFlows());
        } else {
          // First connection: push all localStorage tabs into Automerge
          for (const l of layers) {
            sync.addLayer(l);
          }
        }

        // Active tab stays local — always matches the URL
        tabBar.setAttribute('active', localActiveId);

        // Keep localStorage in sync
        saveTabs();

        // Sync layer list changes to Automerge (not active tab)
        tabBar.addEventListener('layer-add', (e) => {
          const { moduleId } = e.detail;
          const newLayer = makeLayer(moduleId, sync.getLayers().length);
          sync.addLayer(newLayer);
        });
        tabBar.addEventListener('layer-close', (e) => {
          sync.removeLayer(e.detail.layerId);
        });
        tabBar.addEventListener('layer-reorder', (e) => {
          const { layerId, newIndex } = e.detail;
          sync.updateLayer(layerId, { order: newIndex });
          const all = sync.getLayers();
          all.forEach((l, i) => { if (l.order !== i) sync.updateLayer(l.id, { order: i }); });
        });
        tabBar.addEventListener('flow-create', (e) => { sync.addFlow(e.detail.flow); });
        tabBar.addEventListener('flow-remove', (e) => { sync.removeFlow(e.detail.flowId); });
        tabBar.addEventListener('view-toggle', (e) => { sync.setLayerViewMode(e.detail.mode); });

        // Listen for remote changes — sync tab list and flows only.
        // Never touch the active tab: it's managed locally by TabCache
        // and the tab-bar component via layer-switch events.
        sync.addEventListener('change', () => {
          layers = sync.getLayers();
          tabBar.setLayers(layers);
          tabBar.setFlows(sync.getFlows());
          const viewMode = sync.doc.layerViewMode;
          if (viewMode) tabBar.setAttribute('view-mode', viewMode);
          saveTabs(); // keep localStorage in sync
        });
      });
    }
  </script>
  ${scripts}
</body>
</html>`;
}

// ── External app iframe shell ──

export interface ExternalAppShellOptions {
	/** Page <title> */
	title: string;
	/** Current module ID */
	moduleId: string;
	/** Current space slug */
	spaceSlug: string;
	/** Space display name */
	spaceName?: string;
	/** List of available modules */
	modules: ModuleInfo[];
	/** External app URL to embed */
	appUrl: string;
	/** External app display name */
	appName: string;
	/** Theme */
	theme?: "dark" | "light";
}

export function renderExternalAppShell(opts: ExternalAppShellOptions): string {
	const {
		title,
		moduleId,
		spaceSlug,
		spaceName,
		modules,
		appUrl,
		appName,
		theme = "dark",
	} = opts;

	const moduleListJSON = JSON.stringify(modules);
	const demoUrl = `?view=demo`;

	return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🌌</text></svg>">
  <title>${escapeHtml(title)}</title>
  <script>(function(){var t=localStorage.getItem('canvas-theme');if(!t)t=matchMedia('(prefers-color-scheme:light)').matches?'light':'dark';document.documentElement.setAttribute('data-theme',t)})()</script>
  <link rel="stylesheet" href="/theme.css?v=1">
  <link rel="stylesheet" href="/shell.css?v=8">
  <style>
    html.rspace-embedded .rstack-header { display: none !important; }
    html.rspace-embedded .rstack-tab-row { display: none !important; }
    html.rspace-embedded .rspace-iframe-wrap { top: 0 !important; height: 100vh !important; }
  </style>
  <script>if (window.self !== window.parent) document.documentElement.classList.add('rspace-embedded');</script>
</head>
<body>
  <header class="rstack-header">
    <div class="rstack-header__left">
      <a href="/" style="display:flex;align-items:center;margin-right:4px"><img src="/favicon.png" alt="rSpace" class="rstack-header__logo"></a>
      <rstack-app-switcher current="${escapeAttr(moduleId)}"></rstack-app-switcher>
      <rstack-space-switcher current="${escapeAttr(spaceSlug)}" name="${escapeAttr(spaceName || spaceSlug)}"></rstack-space-switcher>
    </div>
    <div class="rstack-header__center">
      <rstack-mi></rstack-mi>
    </div>
    <div class="rstack-header__right">
      <a href="${demoUrl}" class="rapp-nav__btn rapp-nav__btn--secondary" style="font-size:0.78rem;padding:5px 12px;">Back to Demo</a>
      <rstack-identity></rstack-identity>
    </div>
  </header>
  <div class="rstack-tab-row">
    <rstack-tab-bar space="${escapeAttr(spaceSlug)}" active="" view-mode="flat"></rstack-tab-bar>
  </div>
  <div class="rspace-iframe-wrap">
    <div class="rspace-iframe-loading" id="iframe-loading">
      <div class="rspace-iframe-spinner"></div>
      <span>Loading ${escapeHtml(appName)}…</span>
    </div>
    <iframe
      class="rspace-iframe"
      src="${escapeAttr(appUrl)}"
      title="${escapeAttr(appName)}"
      allow="clipboard-read; clipboard-write; fullscreen"
      sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads allow-modals"
      onload="document.getElementById('iframe-loading').style.display='none'"
    ></iframe>
    <a class="rspace-iframe-newtab" href="${escapeAttr(appUrl)}" target="_blank" rel="noopener">Open in new tab ↗</a>
  </div>

  <script type="module">
    import '/shell.js?v=8';
    document.querySelector('rstack-app-switcher')?.setModules(${moduleListJSON});

    const tabBar = document.querySelector('rstack-tab-bar');
    const spaceSlug = '${escapeAttr(spaceSlug)}';
    const currentModuleId = '${escapeAttr(moduleId)}';
    const TABS_KEY = 'rspace_tabs_' + spaceSlug;
    const moduleList = ${moduleListJSON};

    if (tabBar) {
      tabBar.setModules(moduleList);
      function getModuleLabel(id) {
        const m = moduleList.find(mod => mod.id === id);
        return m ? m.name : id;
      }
      function makeLayer(id, order) {
        return { id: 'layer-' + id, moduleId: id, label: getModuleLabel(id), order, color: '', visible: true, createdAt: Date.now() };
      }
      let layers;
      try { const saved = localStorage.getItem(TABS_KEY); layers = saved ? JSON.parse(saved) : []; if (!Array.isArray(layers)) layers = []; } catch(e) { layers = []; }
      if (!layers.find(l => l.moduleId === currentModuleId)) layers.push(makeLayer(currentModuleId, layers.length));
      localStorage.setItem(TABS_KEY, JSON.stringify(layers));
      tabBar.setLayers(layers);
      tabBar.setAttribute('active', 'layer-' + currentModuleId);
      if (tabBar.trackRecent) tabBar.trackRecent(currentModuleId);
      function saveTabs() { localStorage.setItem(TABS_KEY, JSON.stringify(layers)); }
      tabBar.addEventListener('layer-switch', (e) => { saveTabs(); window.location.href = window.__rspaceNavUrl(spaceSlug, e.detail.moduleId); });
      tabBar.addEventListener('layer-add', (e) => { const { moduleId } = e.detail; if (!layers.find(l => l.moduleId === moduleId)) layers.push(makeLayer(moduleId, layers.length)); saveTabs(); window.location.href = window.__rspaceNavUrl(spaceSlug, moduleId); });
      tabBar.addEventListener('layer-close', (e) => { const { layerId } = e.detail; tabBar.removeLayer(layerId); layers = layers.filter(l => l.id !== layerId); saveTabs(); if (layerId === 'layer-' + currentModuleId && layers.length > 0) window.location.href = window.__rspaceNavUrl(spaceSlug, layers[0].moduleId); });
    }
  </script>
</body>
</html>`;
}

// ── Welcome overlay (quarter-screen popup for first-time visitors on demo) ──

function renderWelcomeOverlay(): string {
	return `
  <div id="rspace-welcome" class="rspace-welcome" style="display:none">
    <div class="rspace-welcome__popup">
      <button class="rspace-welcome__close" onclick="window.__rspaceDismissWelcome()">&times;</button>
      <h2 class="rspace-welcome__title">Welcome to rSpace</h2>
      <p class="rspace-welcome__text">
        A collaborative, local-first community platform with 22+ interoperable tools.
        You're viewing the <strong>demo space</strong> &mdash; sign in to access your own.
      </p>
      <div class="rspace-welcome__grid">
        <span>🎨 Canvas</span><span>📝 Notes</span>
        <span>🗳 Voting</span><span>💸 Funds</span>
        <span>🗺 Maps</span><span>📁 Files</span>
        <span>🔐 Passkeys</span><span>📡 Offline-First</span>
      </div>
      <div class="rspace-welcome__actions">
        <a href="/create-space" class="rspace-welcome__btn rspace-welcome__btn--primary">Create a Space</a>
        <button onclick="window.__rspaceDismissWelcome()" class="rspace-welcome__btn rspace-welcome__btn--secondary">Explore Demo</button>
      </div>
      <div class="rspace-welcome__footer">
        <a href="/about" class="rspace-welcome__link">Learn more about rSpace</a>
        <span class="rspace-welcome__dot">&middot;</span>
        <a href="https://ridentity.online" class="rspace-welcome__link">EncryptID</a>
      </div>
    </div>
  </div>`;
}

const ACCESS_GATE_CSS = `
#rspace-access-gate {
  position: fixed; inset: 0; z-index: 9999;
  display: flex; align-items: center; justify-content: center;
  background: var(--rs-bg-overlay); backdrop-filter: blur(8px);
}
.access-gate__card {
  text-align: center; color: var(--rs-text-primary); max-width: 400px; padding: 2rem;
}
.access-gate__icon { font-size: 3rem; margin-bottom: 1rem; }
.access-gate__title {
  font-size: 1.5rem; margin: 0 0 0.5rem;
  background: linear-gradient(135deg, #06b6d4, #7c3aed);
  -webkit-background-clip: text; -webkit-text-fill-color: transparent;
}
.access-gate__desc { color: var(--rs-text-secondary); font-size: 0.95rem; line-height: 1.6; margin: 0 0 1.5rem; }
.access-gate__btn {
  padding: 12px 32px; border-radius: 8px; border: none;
  font-size: 1rem; font-weight: 600; cursor: pointer;
  background: linear-gradient(135deg, #06b6d4, #7c3aed); color: white;
  transition: opacity 0.15s, transform 0.15s;
}
.access-gate__btn:hover { opacity: 0.9; transform: translateY(-1px); }
`;

const WELCOME_CSS = `
.rspace-welcome {
  position: fixed; bottom: 20px; right: 20px; z-index: 10000;
  display: none; align-items: flex-end; justify-content: flex-end;
}
.rspace-welcome__popup {
  position: relative;
  width: min(380px, 44vw); max-height: 50vh;
  background: var(--rs-bg-surface); border: 1px solid var(--rs-border);
  border-radius: 16px; padding: 24px 24px 18px;
  box-shadow: 0 20px 60px rgba(0,0,0,0.5); color: var(--rs-text-primary);
  overflow-y: auto; animation: rspace-welcome-in 0.3s ease-out;
}
@keyframes rspace-welcome-in {
  from { opacity: 0; transform: translateY(20px) scale(0.95); }
  to { opacity: 1; transform: translateY(0) scale(1); }
}
.rspace-welcome__close {
  position: absolute; top: 10px; right: 12px;
  background: none; border: none; color: var(--rs-text-muted);
  font-size: 1.4rem; cursor: pointer; line-height: 1;
  padding: 4px; border-radius: 4px;
}
.rspace-welcome__close:hover { color: var(--rs-text-primary); background: var(--rs-bg-hover); }
.rspace-welcome__title {
  font-size: 1.35rem; margin: 0 0 8px;
  background: var(--rs-gradient-brand);
  -webkit-background-clip: text; -webkit-text-fill-color: transparent;
  background-clip: text;
}
.rspace-welcome__text {
  font-size: 0.85rem; color: var(--rs-text-secondary); margin: 0 0 14px; line-height: 1.55;
}
.rspace-welcome__text strong { color: var(--rs-text-primary); }
.rspace-welcome__grid {
  display: grid; grid-template-columns: 1fr 1fr;
  gap: 5px; margin-bottom: 14px; font-size: 0.8rem; color: var(--rs-text-primary);
}
.rspace-welcome__grid span { padding: 3px 0; }
.rspace-welcome__actions {
  display: flex; gap: 8px; margin-bottom: 12px;
}
.rspace-welcome__btn {
  padding: 8px 16px; border-radius: 8px; font-size: 0.82rem;
  font-weight: 600; text-decoration: none; cursor: pointer; border: none;
  transition: transform 0.15s, box-shadow 0.15s;
}
.rspace-welcome__btn:hover { transform: translateY(-1px); }
.rspace-welcome__btn--primary {
  background: var(--rs-gradient-cta); color: white;
  box-shadow: 0 2px 8px rgba(20,184,166,0.3);
}
.rspace-welcome__btn--secondary {
  background: var(--rs-btn-secondary-bg); color: var(--rs-text-secondary);
}
.rspace-welcome__btn--secondary:hover { color: var(--rs-text-primary); }
.rspace-welcome__footer {
  display: flex; align-items: center; gap: 6px;
}
.rspace-welcome__link {
  font-size: 0.72rem; color: var(--rs-text-muted); text-decoration: none;
  transition: color 0.15s;
}
.rspace-welcome__link:hover { color: #c4b5fd; }
.rspace-welcome__dot { color: var(--rs-text-muted); font-size: 0.6rem; }
@media (max-width: 600px) {
  .rspace-welcome { bottom: 12px; right: 12px; left: 12px; }
  .rspace-welcome__popup { width: 100%; max-width: none; }
}
`;


// ── Module landing page (bare-domain rspace.online/{moduleId}) ──

export interface ModuleLandingOptions {
	/** The module to render a landing page for */
	module: ModuleInfo;
	/** All available modules (for app switcher) */
	modules: ModuleInfo[];
	/** Theme */
	theme?: "dark" | "light";
	/** Rich body HTML from a module's landing.ts (replaces generic hero) */
	bodyHTML?: string;
}

export function renderModuleLanding(opts: ModuleLandingOptions): string {
	const { module: mod, modules, theme = "dark", bodyHTML } = opts;
	const moduleListJSON = JSON.stringify(modules);
	const demoUrl = `https://demo.rspace.online/${mod.id}`;

	const cssBlock = bodyHTML
		? `<style>${MODULE_LANDING_CSS}</style>\n  <style>${RICH_LANDING_CSS}</style>`
		: `<style>${MODULE_LANDING_CSS}</style>`;

	const bodyContent = bodyHTML
		? bodyHTML
		: `<div class="ml-hero">
    <div class="ml-container">
      <span class="ml-icon">${mod.icon}</span>
      <h1 class="ml-name">${escapeHtml(mod.name)}</h1>
      <p class="ml-desc">${escapeHtml(mod.description)}</p>
      <div class="ml-ctas">
        <a href="${demoUrl}" class="ml-cta-primary" id="ml-primary">Try Demo</a>
        <a href="/create-space" class="ml-cta-secondary">Create a Space</a>
      </div>
    </div>
  </div>
  <div class="ml-back">
    <a href="/">← Back to rSpace</a>
  </div>`;

	return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>${mod.icon}</text></svg>">
  <title>${escapeHtml(mod.name)} — rSpace</title>
  <script>(function(){var t=localStorage.getItem('canvas-theme');if(!t)t=matchMedia('(prefers-color-scheme:light)').matches?'light':'dark';document.documentElement.setAttribute('data-theme',t)})()</script>
  <link rel="stylesheet" href="/theme.css?v=1">
  <link rel="stylesheet" href="/shell.css?v=8">
  ${cssBlock}
  <script defer src="https://rdata.online/collect.js" data-website-id="6ee7917b-0ed7-44cb-a4c8-91037638526b"></script>
</head>
<body>
  <header class="rstack-header">
    <div class="rstack-header__left">
      <a href="/" style="display:flex;align-items:center;margin-right:4px"><img src="/favicon.png" alt="rSpace" class="rstack-header__logo"></a>
      <rstack-app-switcher current="${escapeAttr(mod.id)}"></rstack-app-switcher>
      <rstack-space-switcher current="" name="Spaces"></rstack-space-switcher>
      <a class="rstack-header__demo-btn" href="${demoUrl}">Try Demo</a>
    </div>
    <div class="rstack-header__center">
      <rstack-mi></rstack-mi>
    </div>
    <div class="rstack-header__right">
      <rstack-identity></rstack-identity>
    </div>
  </header>
  ${bodyContent}
  <script type="module">
    import '/shell.js?v=8';
    document.querySelector('rstack-app-switcher')?.setModules(${moduleListJSON});
    function _updateDemoBtn() {
      var btn = document.querySelector('.rstack-header__demo-btn');
      if (!btn) return;
      try {
        var raw = localStorage.getItem('encryptid_session');
        if (raw && JSON.parse(raw)?.accessToken) { btn.setAttribute('data-hide', ''); }
        else { btn.removeAttribute('data-hide'); }
      } catch(e) {}
    }
    _updateDemoBtn();
    document.addEventListener('auth-change', _updateDemoBtn);
    try {
      var raw = localStorage.getItem('encryptid_session');
      if (raw) {
        var session = JSON.parse(raw);
        if (session?.claims?.username) {
          var username = session.claims.username.toLowerCase();
          var primary = document.getElementById('ml-primary');
          if (primary) {
            primary.textContent = 'Go to My Space';
            primary.href = 'https://' + username + '.rspace.online/${escapeAttr(mod.id)}';
          }
        }
      }
    } catch(e) {}
  </script>
</body>
</html>`;
}

export const MODULE_LANDING_CSS = `
body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  background: var(--rs-bg-page); color: var(--rs-text-primary);
  min-height: 100vh;
  display: flex; flex-direction: column; align-items: center;
  padding-top: 56px;
}
.ml-hero {
  display: flex; flex-direction: column; align-items: center;
  justify-content: center; min-height: calc(80vh - 56px); width: 100%;
}
.ml-container { text-align: center; max-width: 560px; padding: 40px 20px; }
.ml-icon { font-size: 4rem; display: block; margin-bottom: 1rem; }
.ml-name {
  font-size: 2.5rem; margin-bottom: 0.75rem;
  background: var(--rs-gradient-brand);
  -webkit-background-clip: text; -webkit-text-fill-color: transparent;
}
.ml-desc { font-size: 1.15rem; color: var(--rs-text-secondary); margin-bottom: 2.5rem; line-height: 1.6; }
.ml-ctas { display: flex; gap: 1rem; justify-content: center; flex-wrap: wrap; }
.ml-cta-primary {
  display: inline-block; padding: 14px 32px; border-radius: 8px;
  background: var(--rs-gradient-cta);
  color: white; font-size: 1rem; font-weight: 600;
  text-decoration: none; transition: transform 0.2s, box-shadow 0.2s;
}
.ml-cta-primary:hover { transform: translateY(-2px); box-shadow: 0 8px 20px rgba(20,184,166,0.3); }
.ml-cta-secondary {
  display: inline-block; padding: 14px 32px; border-radius: 8px;
  background: var(--rs-btn-secondary-bg); border: 1px solid var(--rs-border);
  color: var(--rs-text-secondary); font-size: 1rem; font-weight: 600;
  text-decoration: none; transition: transform 0.2s, border-color 0.2s, color 0.2s;
}
.ml-cta-secondary:hover { transform: translateY(-2px); border-color: var(--rs-border-strong); color: var(--rs-text-primary); }
.ml-back { padding: 2rem 0 3rem; text-align: center; }
.ml-back a { font-size: 0.85rem; color: var(--rs-text-muted); text-decoration: none; transition: color 0.2s; }
.ml-back a:hover { color: var(--rs-text-primary); }
@media (max-width: 600px) { .ml-name { font-size: 2rem; } .ml-icon { font-size: 3rem; } }
`;

export const RICH_LANDING_CSS = `
/* ── Rich Landing Page Utilities ── */
.rl-section {
  border-top: 1px solid var(--rs-border-subtle);
  padding: 4rem 1.5rem;
}
.rl-section--alt { background: var(--rs-bg-hover); }
.rl-container { max-width: 1100px; margin: 0 auto; }
.rl-hero {
  text-align: center; padding: 5rem 1.5rem 3rem;
  max-width: 820px; margin: 0 auto;
}
.rl-tagline {
  display: inline-block; font-size: 0.7rem; font-weight: 700;
  letter-spacing: 0.12em; text-transform: uppercase;
  color: var(--rs-accent); background: rgba(20,184,166,0.1);
  border: 1px solid rgba(20,184,166,0.2);
  padding: 0.35rem 1rem; border-radius: 9999px; margin-bottom: 1.5rem;
}
.rl-heading {
  font-size: 2rem; font-weight: 700; line-height: 1.15;
  margin-bottom: 0.75rem; letter-spacing: -0.01em;
  background: var(--rs-gradient-brand);
  -webkit-background-clip: text; -webkit-text-fill-color: transparent;
  background-clip: text;
}
.rl-hero .rl-heading { font-size: 2.5rem; }
@media (min-width: 640px) { .rl-hero .rl-heading { font-size: 3rem; } }
.rl-subtitle {
  font-size: 1.25rem; font-weight: 500; color: var(--rs-text-primary);
  margin-bottom: 1rem; letter-spacing: -0.005em;
}
.rl-hero .rl-subtitle { font-size: 1.35rem; }
@media (min-width: 640px) { .rl-hero .rl-subtitle { font-size: 1.5rem; } }
.rl-subtext {
  font-size: 1.05rem; color: var(--rs-text-secondary); line-height: 1.65;
  max-width: 640px; margin: 0 auto 2rem;
}
.rl-hero .rl-subtext { font-size: 1.15rem; }

/* Grids */
.rl-grid-2 { display: grid; grid-template-columns: 1fr; gap: 1.25rem; }
.rl-grid-3 { display: grid; grid-template-columns: 1fr; gap: 1.25rem; }
.rl-grid-4 { display: grid; grid-template-columns: 1fr; gap: 1.25rem; }
@media (min-width: 640px) {
  .rl-grid-2 { grid-template-columns: repeat(2, 1fr); }
  .rl-grid-3 { grid-template-columns: repeat(3, 1fr); }
  .rl-grid-4 { grid-template-columns: repeat(2, 1fr); }
}
@media (min-width: 1024px) {
  .rl-grid-4 { grid-template-columns: repeat(4, 1fr); }
}

/* Card */
.rl-card {
  background: var(--rs-card-bg); border: 1px solid var(--rs-card-border);
  border-radius: 1rem; padding: 1.75rem;
  transition: border-color 0.2s;
}
.rl-card:hover { border-color: rgba(20,184,166,0.3); }
.rl-card h3 { font-size: 0.95rem; font-weight: 600; color: var(--rs-text-primary); margin-bottom: 0.5rem; }
.rl-card p { font-size: 0.875rem; color: var(--rs-text-secondary); line-height: 1.6; }
.rl-card--center { text-align: center; }

/* Step circles */
.rl-step {
  display: flex; flex-direction: column; align-items: center; text-align: center;
}
.rl-step__num {
  width: 2.5rem; height: 2.5rem; border-radius: 9999px;
  background: rgba(20,184,166,0.1); color: var(--rs-accent);
  display: flex; align-items: center; justify-content: center;
  font-size: 0.8rem; font-weight: 700; margin-bottom: 0.75rem;
}
.rl-step h3 { font-size: 0.95rem; font-weight: 600; color: var(--rs-text-primary); margin-bottom: 0.25rem; }
.rl-step p { font-size: 0.82rem; color: var(--rs-text-secondary); line-height: 1.55; }

/* CTA row */
.rl-cta-row {
  display: flex; gap: 0.75rem; justify-content: center; flex-wrap: wrap;
  margin-top: 2rem;
}
.rl-cta-primary {
  display: inline-block; padding: 0.8rem 2rem; border-radius: 0.5rem;
  background: var(--rs-gradient-cta);
  color: white; font-size: 0.95rem; font-weight: 600;
  text-decoration: none; transition: transform 0.2s, box-shadow 0.2s;
}
.rl-cta-primary:hover { transform: translateY(-2px); box-shadow: 0 8px 20px rgba(20,184,166,0.3); }
.rl-cta-secondary {
  display: inline-block; padding: 0.8rem 2rem; border-radius: 0.5rem;
  background: var(--rs-btn-secondary-bg); border: 1px solid var(--rs-border);
  color: var(--rs-text-secondary); font-size: 0.95rem; font-weight: 600;
  text-decoration: none; transition: transform 0.2s, border-color 0.2s, color 0.2s;
}
.rl-cta-secondary:hover { transform: translateY(-2px); border-color: var(--rs-border-strong); color: var(--rs-text-primary); }

/* Check list */
.rl-check-list { list-style: none; padding: 0; margin: 0; }
.rl-check-list li {
  display: flex; align-items: flex-start; gap: 0.5rem;
  font-size: 0.875rem; color: var(--rs-text-secondary); line-height: 1.55;
  padding: 0.35rem 0;
}
.rl-check-list li::before {
  content: "✓"; color: var(--rs-accent); font-weight: 700; flex-shrink: 0; margin-top: 0.05em;
}
.rl-check-list li strong { color: var(--rs-text-primary); font-weight: 600; }

/* Badge */
.rl-badge {
  display: inline-block; font-size: 0.65rem; font-weight: 700;
  color: white; background: var(--rs-accent);
  padding: 0.15rem 0.5rem; border-radius: 9999px;
}

/* Divider */
.rl-divider {
  display: flex; align-items: center; gap: 0.75rem; margin: 1.5rem 0;
}
.rl-divider::before, .rl-divider::after {
  content: ""; flex: 1; height: 1px; background: var(--rs-border-subtle);
}
.rl-divider span { font-size: 0.75rem; color: var(--rs-text-muted); white-space: nowrap; }

/* Icon box */
.rl-icon-box {
  width: 3rem; height: 3rem; border-radius: 0.75rem;
  background: rgba(20,184,166,0.12); color: var(--rs-accent);
  display: flex; align-items: center; justify-content: center;
  font-size: 1.5rem; margin-bottom: 1rem;
}
.rl-card--center .rl-icon-box { margin: 0 auto 1rem; }

/* Integration (2-col with icon) */
.rl-integration {
  display: flex; align-items: flex-start; gap: 1rem;
  background: rgba(20,184,166,0.04); border: 1px solid rgba(20,184,166,0.15);
  border-radius: 1rem; padding: 1.5rem;
}
.rl-integration h3 { font-size: 0.95rem; font-weight: 600; color: var(--rs-text-primary); margin-bottom: 0.35rem; }
.rl-integration p { font-size: 0.85rem; color: var(--rs-text-secondary); line-height: 1.55; }

/* Back link */
.rl-back { padding: 2rem 0 3rem; text-align: center; }
.rl-back a { font-size: 0.85rem; color: var(--rs-text-muted); text-decoration: none; transition: color 0.2s; }
.rl-back a:hover { color: var(--rs-text-primary); }

/* Progress bar */
.rl-progress { height: 0.5rem; border-radius: 9999px; background: var(--rs-border-subtle); overflow: hidden; }
.rl-progress__fill { height: 100%; border-radius: 9999px; background: var(--rs-accent); }

/* Tier row */
.rl-tier {
  display: flex; gap: 0.5rem; margin: 1rem 0;
}
.rl-tier__item {
  flex: 1; text-align: center; border-radius: 0.5rem;
  border: 1px solid var(--rs-border-subtle); padding: 0.5rem; font-size: 0.75rem;
}
.rl-tier__item--active {
  border-color: rgba(20,184,166,0.4); background: rgba(20,184,166,0.05); color: var(--rs-accent);
}
.rl-tier__item--active strong { color: var(--rs-accent); }

/* Temporal zoom bar */
.rl-zoom-bar { display: flex; flex-direction: column; gap: 0.5rem; }
.rl-zoom-bar__row { display: flex; align-items: center; gap: 0.75rem; }
.rl-zoom-bar__label { font-size: 0.7rem; color: var(--rs-text-muted); width: 1.2rem; text-align: right; font-family: monospace; }
.rl-zoom-bar__bar {
  height: 1.5rem; border-radius: 0.375rem; background: rgba(99,102,241,0.15);
  display: flex; align-items: center; padding: 0 0.75rem;
}
.rl-zoom-bar__name { font-size: 0.75rem; font-weight: 600; color: var(--rs-text-primary); white-space: nowrap; }
.rl-zoom-bar__span { font-size: 0.6rem; color: var(--rs-text-muted); margin-left: auto; white-space: nowrap; }

/* Responsive helpers */
@media (max-width: 600px) {
  .rl-hero { padding: 3rem 1rem 2rem; }
  .rl-hero .rl-heading { font-size: 2rem; }
  .rl-section { padding: 2.5rem 1rem; }
}
`;

// ── Sub-page info page (bare-domain rspace.online/{moduleId}/{subPage}) ──

export interface SubPageInfoOptions {
	/** The sub-page info to render */
	subPage: SubPageInfo;
	/** The parent module info */
	module: ModuleInfo;
	/** All available modules (for app switcher) */
	modules: ModuleInfo[];
}

export function renderSubPageInfo(opts: SubPageInfoOptions): string {
	const { subPage, module: mod, modules } = opts;
	const moduleListJSON = JSON.stringify(modules);
	const demoUrl = `https://demo.rspace.online/${mod.id}/${subPage.path}`;

	const featuresGrid = subPage.features?.length
		? `<div class="rl-section">
    <div class="rl-container">
      <div class="rl-grid-3">
        ${subPage.features.map(f => `<div class="rl-card rl-card--center">
          <div class="rl-icon-box">${f.icon}</div>
          <h3>${escapeHtml(f.title)}</h3>
          <p>${escapeHtml(f.text)}</p>
        </div>`).join("\n        ")}
      </div>
    </div>
  </div>`
		: "";

	const bodyContent = subPage.bodyHTML
		? subPage.bodyHTML()
		: `<div class="rl-hero">
    <span class="rl-tagline">${escapeHtml(subPage.tagline)}</span>
    <h1 class="rl-heading">${escapeHtml(subPage.title)}</h1>
    <p class="rl-subtext">${escapeHtml(subPage.description)}</p>
    <div class="rl-cta-row">
      <a href="${demoUrl}" class="rl-cta-primary" id="sp-primary">Try Demo</a>
      <a href="/create-space" class="rl-cta-secondary">Create a Space</a>
    </div>
  </div>
  ${featuresGrid}
  <div class="rl-back">
    <a href="/${escapeAttr(mod.id)}">← Back to ${escapeHtml(mod.name)}</a>
  </div>`;

	return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>${subPage.icon}</text></svg>">
  <title>${escapeHtml(subPage.title)} — ${escapeHtml(mod.name)} | rSpace</title>
  <script>(function(){var t=localStorage.getItem('canvas-theme');if(!t)t=matchMedia('(prefers-color-scheme:light)').matches?'light':'dark';document.documentElement.setAttribute('data-theme',t)})()</script>
  <link rel="stylesheet" href="/theme.css?v=1">
  <link rel="stylesheet" href="/shell.css?v=8">
  <style>${MODULE_LANDING_CSS}</style>
  <style>${RICH_LANDING_CSS}</style>
  <script defer src="https://rdata.online/collect.js" data-website-id="6ee7917b-0ed7-44cb-a4c8-91037638526b"></script>
</head>
<body>
  <header class="rstack-header">
    <div class="rstack-header__left">
      <a href="/" style="display:flex;align-items:center;margin-right:4px"><img src="/favicon.png" alt="rSpace" class="rstack-header__logo"></a>
      <rstack-app-switcher current="${escapeAttr(mod.id)}"></rstack-app-switcher>
      <rstack-space-switcher current="" name="Spaces"></rstack-space-switcher>
      <a class="rstack-header__demo-btn" href="${demoUrl}">Try Demo</a>
    </div>
    <div class="rstack-header__center">
      <rstack-mi></rstack-mi>
    </div>
    <div class="rstack-header__right">
      <rstack-identity></rstack-identity>
    </div>
  </header>
  ${bodyContent}
  <script type="module">
    import '/shell.js?v=8';
    document.querySelector('rstack-app-switcher')?.setModules(${moduleListJSON});
    function _updateDemoBtn() {
      var btn = document.querySelector('.rstack-header__demo-btn');
      if (!btn) return;
      try {
        var raw = localStorage.getItem('encryptid_session');
        if (raw && JSON.parse(raw)?.accessToken) { btn.setAttribute('data-hide', ''); }
        else { btn.removeAttribute('data-hide'); }
      } catch(e) {}
    }
    _updateDemoBtn();
    document.addEventListener('auth-change', _updateDemoBtn);
    try {
      var raw = localStorage.getItem('encryptid_session');
      if (raw) {
        var session = JSON.parse(raw);
        if (session?.claims?.username) {
          var username = session.claims.username.toLowerCase();
          var primary = document.getElementById('sp-primary');
          if (primary) {
            primary.textContent = 'Open in My Space';
            primary.href = 'https://' + username + '.rspace.online/${escapeAttr(mod.id)}/${escapeAttr(subPage.path)}';
          }
        }
      }
    } catch(e) {}
  </script>
</body>
</html>`;
}

// ── Onboarding page (empty rApp state) ──

export interface OnboardingOptions {
	moduleId: string;
	moduleName: string;
	moduleIcon: string;
	moduleDescription: string;
	spaceSlug: string;
	modules: ModuleInfo[];
	/** Pre-rendered landing page HTML from the module (feature cards, etc.) */
	landingHTML?: string;
}

export function renderOnboarding(opts: OnboardingOptions): string {
	const { moduleId, moduleName, moduleIcon, moduleDescription, spaceSlug, modules, landingHTML } = opts;
	const demoUrl = `/${moduleId}/demo`;
	const templateUrl = `/${moduleId}/template`;

	const featuresBlock = landingHTML
		? `<div class="onboarding__features">${landingHTML}</div>`
		: '';

	const body = `
	<div class="onboarding">
		<div class="onboarding__card">
			<span class="onboarding__icon">${moduleIcon}</span>
			<h1 class="onboarding__title">${escapeHtml(moduleName)}</h1>
			<p class="onboarding__desc">${escapeHtml(moduleDescription)}</p>
			<div class="onboarding__ctas">
				<a href="${escapeAttr(templateUrl)}" class="onboarding__btn onboarding__btn--primary">Get Started</a>
				<a href="${escapeAttr(demoUrl)}" class="onboarding__btn onboarding__btn--secondary">Try Demo</a>
			</div>
		</div>
		${featuresBlock}
	</div>`;

	return renderShell({
		title: `${moduleName} — ${spaceSlug} | rSpace`,
		moduleId,
		spaceSlug,
		modules,
		body,
		styles: `<style>${ONBOARDING_CSS}</style>${landingHTML ? `<style>${RICH_LANDING_CSS}</style>` : ''}`,
	});
}

const ONBOARDING_CSS = `
.onboarding {
  display: flex; flex-direction: column; align-items: center;
  min-height: calc(80vh - 56px); padding: 3rem 1.5rem 2rem;
}
.onboarding__card {
  text-align: center; max-width: 520px; width: 100%;
  padding: 2.5rem 2rem; margin-bottom: 2rem;
}
.onboarding__icon { font-size: 3.5rem; display: block; margin-bottom: 1rem; }
.onboarding__title {
  font-size: 2rem; margin: 0 0 0.75rem; font-weight: 700;
  background: var(--rs-gradient-brand);
  -webkit-background-clip: text; -webkit-text-fill-color: transparent;
  background-clip: text;
}
.onboarding__desc {
  font-size: 1.05rem; color: var(--rs-text-secondary);
  line-height: 1.6; margin: 0 0 2rem;
}
.onboarding__ctas {
  display: flex; gap: 0.75rem; justify-content: center; flex-wrap: wrap;
}
.onboarding__btn {
  display: inline-block; padding: 0.75rem 1.75rem; border-radius: 0.5rem;
  font-size: 0.95rem; font-weight: 600; text-decoration: none;
  transition: transform 0.2s, box-shadow 0.2s;
}
.onboarding__btn:hover { transform: translateY(-2px); }
.onboarding__btn--primary {
  background: var(--rs-gradient-cta); color: white;
  box-shadow: 0 2px 8px rgba(20,184,166,0.3);
}
.onboarding__btn--primary:hover { box-shadow: 0 8px 20px rgba(20,184,166,0.3); }
.onboarding__btn--secondary {
  background: var(--rs-btn-secondary-bg); border: 1px solid var(--rs-border);
  color: var(--rs-text-secondary);
}
.onboarding__btn--secondary:hover { border-color: var(--rs-border-strong); color: var(--rs-text-primary); }
.onboarding__features {
  width: 100%; max-width: 1100px;
  border-top: 1px solid var(--rs-border-subtle);
  padding-top: 2rem; margin-top: 1rem;
}
@media (max-width: 600px) {
  .onboarding { padding: 2rem 1rem 1.5rem; }
  .onboarding__title { font-size: 1.6rem; }
  .onboarding__icon { font-size: 2.5rem; }
}
`;

// ── Demo page CSS utilities (rd-* prefix, parallel to rl-* landing pages) ──

export function escapeHtml(s: string): string {
	return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}

export function escapeAttr(s: string): string {
	return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
