/**
 * Module: {{ dashboard_name }} dev harness
 * Description: Local development entry point — renders dashboard as a standalone SPA
 *
 * This file is used by `huitzo dashboard dev` (via index.html).
 * In production, Hub loads main.tsx via import() and calls mount/unmount.
 *
 * @implements docs/cli/dashboards.md#dev-mode-vs-hub-mode
 * @implements docs/dashboards/loading.md#huitzocontext
 */

import { mount, type HuitzoMountContext } from './main';

/**
 * Mock context for local development.
 * Mirrors the canonical HuitzoContext interface from docs/dashboards/loading.md.
 * In Hub, this is provided by the platform.
 */
const devContext: HuitzoMountContext = {
  apiUrl: 'http://localhost:8080/api',
  token: 'dev-token',
  slug: '{{ dashboard_name }}',
  sdkVersion: '0.0.0',
  user: {
    id: 'dev-user',
    email: 'developer@localhost',
    roles: ['admin'],
    tenantId: 'dev-tenant',
  },
  navigate: (path: string) => {
    console.log(`[dev] navigate to: ${path}`);
    window.location.hash = path;
  },
  navigateToHub: () => {
    console.log('[dev] navigate to Hub');
  },
  navigateToDashboard: (slug: string) => {
    console.log(`[dev] navigate to dashboard: ${slug}`);
  },
  showNotification: (message: string, type: 'info' | 'error' | 'success') => {
    console.log(`[dev] notification (${type}): ${message}`);
  },
  on: (event: string, handler: (data: unknown) => void) => {
    console.log(`[dev] subscribed to event: ${event}`);
    return () => console.log(`[dev] unsubscribed from event: ${event}`);
  },
  emit: (event: string, data: unknown) => {
    console.log(`[dev] emitted event: ${event}`, data);
  },
};

// ---------------------------------------------------------------------------
// Simulated Hub header — plain DOM, renders before React initializes.
// Emulates apps/dashboard/src/components/layout/HubHeader.tsx visually.
// ---------------------------------------------------------------------------

function createDevHeader(): void {
  const header = document.createElement('header');
  header.style.cssText = [
    'display: flex',
    'align-items: center',
    'justify-content: space-between',
    'height: var(--header-height, 4rem)',
    'padding: 0 var(--space-6, 1.5rem)',
    'background-color: var(--color-bg-primary, #000000)',
    'border-bottom: 1px solid var(--color-border, #1A1A1F)',
    'box-sizing: border-box',
  ].join('; ');

  // Left side: ← Hub / dashboard name
  const left = document.createElement('div');
  left.style.cssText = 'display: flex; align-items: center; gap: var(--space-3, 0.75rem);';

  const backLink = document.createElement('span');
  backLink.style.cssText = [
    'color: var(--color-accent, #155DFC)',
    'font-weight: 500',
    'cursor: default',
  ].join('; ');
  backLink.textContent = '← Hub';

  const separator = document.createElement('span');
  separator.style.cssText = 'color: var(--color-text-muted, #6B6B76);';
  separator.textContent = '/';

  const title = document.createElement('h1');
  title.style.cssText = [
    'font-size: var(--text-xl, 1.25rem)',
    'font-weight: 600',
    'color: var(--color-text-primary, #FFFFFF)',
    'margin: 0',
  ].join('; ');
  title.textContent = '{{ dashboard_name }}';

  left.appendChild(backLink);
  left.appendChild(separator);
  left.appendChild(title);

  // Right side: theme toggle + user email
  const right = document.createElement('div');
  right.style.cssText = 'display: flex; align-items: center; gap: var(--space-2, 0.5rem);';

  // Theme toggle button
  const themeBtn = document.createElement('button');
  themeBtn.setAttribute('aria-label', 'Toggle theme');
  themeBtn.style.cssText = [
    'display: flex',
    'align-items: center',
    'justify-content: center',
    'width: 2.5rem',
    'height: 2.5rem',
    'border-radius: var(--radius-md, 0.375rem)',
    'color: var(--color-text-secondary, #E9E9E9)',
    'background: transparent',
    'border: none',
    'cursor: pointer',
    'padding: 0',
  ].join('; ');

  // Sun SVG (shown when dark — click to go light)
  const sunSvg = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>';
  // Moon SVG (shown when light — click to go dark)
  const moonSvg = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>';

  function updateThemeIcon(): void {
    const isDark = document.documentElement.getAttribute('data-theme') !== 'light';
    themeBtn.innerHTML = isDark ? sunSvg : moonSvg;
    themeBtn.setAttribute('aria-label', isDark ? 'Switch to light mode' : 'Switch to dark mode');
  }

  themeBtn.addEventListener('click', () => {
    const isDark = document.documentElement.getAttribute('data-theme') !== 'light';
    document.documentElement.setAttribute('data-theme', isDark ? 'light' : 'dark');
    updateThemeIcon();
  });

  updateThemeIcon();

  // User email
  const userInfo = document.createElement('div');
  userInfo.style.cssText = [
    'display: flex',
    'align-items: center',
    'padding-left: var(--space-4, 1rem)',
    'margin-left: var(--space-2, 0.5rem)',
    'border-left: 1px solid var(--color-border, #1A1A1F)',
  ].join('; ');

  const userEmail = document.createElement('span');
  userEmail.style.cssText = [
    'font-size: var(--text-sm, 0.875rem)',
    'font-weight: 500',
    'color: var(--color-text-primary, #FFFFFF)',
  ].join('; ');
  userEmail.textContent = devContext.user.email;

  userInfo.appendChild(userEmail);
  right.appendChild(themeBtn);
  right.appendChild(userInfo);

  header.appendChild(left);
  header.appendChild(right);

  // Insert header before #root
  const root = document.getElementById('root');
  if (root) {
    document.body.insertBefore(header, root);
  }
}

createDevHeader();

const container = document.getElementById('root');
if (!container) {
  throw new Error('Root element not found. Ensure index.html has <div id="root"></div>.');
}

// Use the same mount function that Hub will call
mount(container, devContext);

// HMR support — re-mount on module update
if (import.meta.hot) {
  import.meta.hot.accept();
}
