
import React from 'react'
import { createRoot } from 'react-dom/client'
import App from './App'
import './index.css'

const deny = (msg: string) => {
  document.body.innerHTML = `<div style="display:flex;align-items:center;justify-content:center;min-height:100vh;font-family:system-ui,sans-serif;background:#f8fafc;color:#0f172a;">${msg}</div>`;
};

async function boot() {
  const urlParams = new URLSearchParams(window.location.search);
  const agenticToken = urlParams.get('agentic_token');
  const legacyToken = urlParams.get('auth_token');
  const activeToken = agenticToken || legacyToken;

  if (!activeToken) {
    // Check sessionStorage in case the user navigated away and back
    const storedToken = sessionStorage.getItem('admin_auth_token');
    if (!storedToken) {
      deny('Invalid or missing admin access token.');
      return;
    }
    // Token is in sessionStorage and was already validated - mount app directly
    const root = document.getElementById('root');
    if (!root) { deny('Unable to load admin app.'); return; }
    createRoot(root).render(<React.StrictMode><App /></React.StrictMode>);
    return;
  }

  if (agenticToken) {
    try {
      const verifyRes = await fetch('https://api.mauth.mworld.cloud/mAuthAG/verifyToken', {
        headers: { 'mAuthAgenticToken': agenticToken }
      });
      const verifyData = await verifyRes.json();
      if (!verifyData.success) {
        deny(`Unauthorized: ${verifyData.msg || 'Invalid agentic token'}`);
        return;
      }
      localStorage.setItem('auth_token', agenticToken);
    } catch (err) {
      deny('Authentication service unavailable.');
      return;
    }
  } else if (legacyToken) {
    // Legacy hash-based validation
    const data = new TextEncoder().encode(legacyToken);
    const digest = await crypto.subtle.digest('SHA-256', data);
    const hash = Array.from(new Uint8Array(digest))
      .map((value) => value.toString(16).padStart(2, '0'))
      .join('');

    if (hash !== 'a3fe085c7881857775b34eba615865d844c2b732045f3851db78bf8b79365979') {
      deny('Invalid or missing admin access token.');
      return;
    }
    localStorage.setItem('auth_token', legacyToken);
  }

  // Persist token in sessionStorage so API calls work after React Router navigations
  sessionStorage.setItem('admin_auth_token', activeToken);

  const root = document.getElementById('root');
  if (!root) {
    deny('Unable to load admin app.');
    return;
  }

  createRoot(root).render(
    <React.StrictMode>
      <App />
    </React.StrictMode>,
  );
}

boot().catch(() => {
  deny('Unable to validate admin access token.');
});
