/**
 * dashboard-build.js — Standalone dashboard HTML assembler for testing.
 * Exports buildDashboardHtml() so unit tests can verify assembly.
 */
const fs = require('fs');
const path = require('path');
const shared = require('./engine/shared');
const { safeRead } = shared;

const MINIONS_DIR = __dirname;

function buildDashboardHtml() {
  const dashDir = path.join(MINIONS_DIR, 'dashboard');
  const layoutPath = path.join(dashDir, 'layout.html');

  if (!fs.existsSync(layoutPath)) {
    throw new Error(`Dashboard layout not found: ${layoutPath}. The dashboard/ directory must exist.`);
  }

  const layout = safeRead(layoutPath);
  const css = safeRead(path.join(dashDir, 'styles.css'));

  const pages = ['home', 'work', 'prs', 'plans', 'inbox', 'tools', 'schedule', 'watches', 'pipelines', 'meetings', 'qa', 'engine'];
  let pageHtml = '';
  for (const p of pages) {
    const content = safeRead(path.join(dashDir, 'pages', p + '.html'));
    const activeClass = p === 'home' ? ' active' : '';
    pageHtml += `    <div class="page${activeClass}" id="page-${p}">\n${content}\n    </div>\n\n`;
  }

  const jsFiles = [
    'utils', 'state', 'features-client', 'render-utils', 'detail-panel', 'live-stream',
    'render-agents', 'render-dispatch', 'render-work-items', 'render-prd',
    'render-prs', 'render-plans', 'render-inbox', 'render-kb', 'render-skills',
    'render-other', 'render-managed', 'render-schedules', 'render-watches', 'render-pipelines', 'render-meetings', 'render-pinned',
    'command-parser', 'command-input', 'command-center', 'command-history',
    'confirm-dialog', 'modal', 'modal-qa', 'settings', 'qa', 'fre', 'refresh'
  ];
  let jsHtml = '';
  for (const f of jsFiles) {
    const content = safeRead(path.join(dashDir, 'js', f + '.js'));
    jsHtml += `\n// ─── ${f}.js ────────────────────────────────────────\n${content}\n`;
  }

  // Use function replacer to avoid $ special patterns in String.replace
  return layout
    .replace('/* __CSS__ */', () => css)
    .replace('<!-- __PAGES__ -->', () => pageHtml)
    .replace('/* __JS__ */', () => jsHtml);
}

// Slim-UX surface (feature flag 'slim-ux'). Same fragment-assembly model as
// the main dashboard: a shell layout with /* __CSS__ */, <!-- __BODY__ -->,
// /* __JS__ */ placeholders, filled from dashboard/slim/. The JS is one shared
// IIFE scope, so the parts are concatenated in dependency order (matching the
// original single-file source) inside the wrapper that layout.html provides.
const SLIM_JS_ORDER = [
  'helpers', 'settings', 'link-pr', 'chat', 'projects',
  'command-send', 'status', 'members', 'modals-tiles', 'history', 'pinned',
];

function buildSlimHtml(opts) {
  const slimDir = path.join(MINIONS_DIR, 'dashboard', 'slim');
  const layoutPath = path.join(slimDir, 'layout.html');
  if (!fs.existsSync(layoutPath)) {
    throw new Error(`Slim layout not found: ${layoutPath}. The dashboard/slim/ directory must exist.`);
  }
  const layout = safeRead(layoutPath);
  const css = safeRead(path.join(slimDir, 'styles.css'));
  const body = safeRead(path.join(slimDir, 'body.html'));
  // Join with a newline so a fragment that loses its trailing newline can't
  // glue two statements together (e.g. `}var foo`). Parts share one IIFE
  // scope, so order is load-bearing — see SLIM_JS_ORDER.
  const js = SLIM_JS_ORDER.map(f => safeRead(path.join(slimDir, 'js', f + '.js'))).join('\n');

  // Feature-flag bootstrap (window.MINIONS_FEATURES) injected at the top of the
  // slim IIFE. serveSlimUx passes the live flags as JSON via opts.featuresJson;
  // the default is a valid empty object so direct buildSlimHtml() calls (tests,
  // other builders) still produce parseable JS.
  const featuresJson = (opts && opts.featuresJson) || '{ "flags": {}, "defaults": {} }';

  return layout
    .replace('/* __CSS__ */', () => css)
    // Tolerate CRLF drift in layout.html (LF is enforced by .gitattributes, but
    // an exact '\n' match would silently no-op and ship an empty body on CRLF).
    .replace(/<!-- __BODY__ -->\r?\n/, () => body)
    .replace('{{minions_features}}', () => featuresJson)
    .replace('/* __JS__ */', () => js);
}

module.exports = { buildDashboardHtml, buildSlimHtml, SLIM_JS_ORDER };
