/// Vault initialization wizard — thin shell (render loop + boot).
///
/// Step registry, state, and all step implementations live in ./setup-steps.
/// This module owns only: progress track, rerender/goto loop, and the
/// DOMContentLoaded boot.

import { STEPS, state, clearWizardState, finishSetup } from './setup-steps';
import type { StepId, StepContext } from './setup-steps';
import { escapeHtml } from './setup-helpers';

// --- Progress track ---

const SETUP_STEP_NAMES = ['mode', 'host', 'connection', 'vault', 'device', 'done'];

function renderProgressTrack(current: number): string {
  return `<div class="setup-progress-track">${SETUP_STEP_NAMES.map((_, i) => {
    const cls = i < current ? 'completed' : i === current ? 'active' : 'pending';
    return `<div class="setup-progress-segment setup-progress-segment--${cls}" title="${SETUP_STEP_NAMES[i]}"></div>`;
  }).join('')}</div>`;
}

// --- Render loop ---

let teardown: (() => void) | null = null;

function rerender(): void {
  const app = document.getElementById('app');
  if (!app) return;
  teardown?.();
  const ctx: StepContext = { state, rerender, goto };
  const step = STEPS.find((s) => s.id === state.stepId)!;
  const idx = STEPS.findIndex((s) => s.id === state.stepId);
  app.innerHTML = `<div class="surface-backdrop" style="min-height:100vh;"><div class="pad" style="padding-top:12px;">
    <img class="brand-logo" src="icons/relicario-logo.svg" alt="" style="margin-bottom:12px;">
    <div class="brand" style="margin-bottom:4px;">Relicario vault setup</div>
    ${renderProgressTrack(idx)}
    ${state.error ? `<div class="error">${escapeHtml(state.error)}</div>` : ''}
    ${step.render(ctx)}
  </div></div>`;
  teardown = step.attach(app, ctx);
}

function goto(id: StepId): void {
  if (id === 'mode') clearWizardState();
  state.stepId = id;
  state.error = null;
  rerender();
}

// --- Boot ---

document.addEventListener('DOMContentLoaded', () => {
  window.addEventListener('beforeunload', clearWizardState);
  rerender();
});

// Re-exports so existing test and bundle imports resolve unchanged.
export { STEPS, clearWizardState, finishSetup } from './setup-steps';
