import React, { useState, useEffect, useLayoutEffect, useCallback } from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.jsx';
import LandingPage from './components/LandingPage.jsx';
import ErrorBoundary from './components/ErrorBoundary.jsx';
import { isStaticEdgeHost } from './utils/helpers.js';
import './index.css';

const reportEdgeError = (payload) => {
  try {
    const raw = sessionStorage.getItem('astra_client_telemetry');
    const list = raw ? JSON.parse(raw) : [];
    list.unshift({
      id: `edge_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`,
      ...payload,
      category: 'RUNTIME_EXCEPTION',
      severity: 'HIGH',
      mitreTactic: 'TA0040 Impact',
      mitreId: 'T1499.004 (Application Crash / Memory Fault)',
      sourceIp: 'Browser Edge',
      actionTaken: 'CAPTURED_BY_SENTRY',
      occurrences: 1,
      firstSeen: Date.now(),
      lastSeen: Date.now(),
      affectedUserCount: 1
    });
    sessionStorage.setItem('astra_client_telemetry', JSON.stringify(list.slice(0, 100)));
  } catch (e) {}

  try {
    if (!isStaticEdgeHost()) {
      fetch('/api/admin/log-error', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      }).catch(() => {});
    }
  } catch (e) {}
};

// Global error handlers for Sentry-like observability
window.addEventListener('error', (event) => {
  reportEdgeError({
    type: 'unhandled',
    message: event.message || 'Window Unhandled Error',
    stack: event.error?.stack || `${event.filename}:${event.lineno}:${event.colno}`,
    source: 'client-window',
    context: { url: window.location.href }
  });
});

window.addEventListener('unhandledrejection', (event) => {
  const reason = event.reason;
  reportEdgeError({
    type: 'unhandled',
    message: typeof reason === 'object' && reason?.message ? reason.message : String(reason),
    stack: reason?.stack || '',
    source: 'client-promise',
    context: { url: window.location.href }
  });
});

function getRouteFlags() {
  const hash = (window.location.hash || '').toLowerCase();
  const path = (window.location.pathname || '').toLowerCase().replace(/\/+$/, '');
  const search = (window.location.search || '').toLowerCase();

  const isAdminRoute =
    hash === '#astravistababy' ||
    hash === '#admin' ||
    path.endsWith('/astravistababy') ||
    path.endsWith('/admin');

  const isInviteRoute =
    hash.includes('room=') ||
    hash.includes('invite=') ||
    hash.startsWith('#dm=') ||
    search.includes('invite=') ||
    search.includes('room=');

  const isExplicitChat =
    hash === '#chat' ||
    hash.startsWith('#chat?') ||
    search.includes('chat=1');

  return { hash, isAdminRoute, isInviteRoute, isExplicitChat };
}

const SESSION_IDLE_TIMEOUT_MS = 30 * 60 * 1000;

function purgeExpiredSessionAtBoot() {
  try {
    const lastActiveRaw =
      localStorage.getItem('telecrypt_last_active') ||
      sessionStorage.getItem('telecrypt_last_active');
    if (lastActiveRaw && Date.now() - Number(lastActiveRaw) >= SESSION_IDLE_TIMEOUT_MS) {
      localStorage.removeItem('telecrypt_username');
      localStorage.removeItem('telecrypt_joined_rooms');
      localStorage.removeItem('telecrypt_active_room_id');
      localStorage.removeItem('telecrypt_last_active');
      sessionStorage.removeItem('telecrypt_username');
      sessionStorage.removeItem('telecrypt_ephemeral_rooms');
      sessionStorage.removeItem('telecrypt_active_room_id');
      sessionStorage.removeItem('telecrypt_last_active');
      sessionStorage.removeItem('astra_session_token');
    }
  } catch (e) {}
}

purgeExpiredSessionAtBoot();

// PWA Service Worker registration (relative path safe for GitHub Pages subpath & Cloudflare root)
if (typeof window !== 'undefined' && 'serviceWorker' in navigator && window.location.protocol !== 'file:') {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('./sw.js').catch((err) => {
      console.warn('[PWA] Service Worker registration skipped:', err?.message || err);
    });
  });

  window.addEventListener('beforeinstallprompt', (e) => {
    e.preventDefault();
    window._astraDeferredInstallPrompt = e;
    window.dispatchEvent(new CustomEvent('astra-pwa-installable'));
  });
}

function shouldOpenChatForLocation() {
  const { isAdminRoute, isInviteRoute, isExplicitChat } = getRouteFlags();
  return isAdminRoute || isInviteRoute || isExplicitChat;
}

function RootRouter() {
  const [showChat, setShowChat] = useState(shouldOpenChatForLocation);

  useLayoutEffect(() => {
    const html = document.documentElement;
    const themeMeta = document.querySelector('meta[name="theme-color"]');

    if (showChat) {
      html.classList.add('astra-chat-mode');
      window.scrollTo(0, 0);
      document.title = 'Astra Chat | Ephemeral End-to-End Encrypted Web Chat';
      if (themeMeta) themeMeta.setAttribute('content', '#18222d');
    } else {
      html.classList.remove('astra-chat-mode');
      html.classList.remove('dark');
      document.title = 'Astra Chat — Private conversations, here for now';
      if (themeMeta) themeMeta.setAttribute('content', '#f7f6f2');
    }
  }, [showChat]);

  useEffect(() => {
    const syncRoute = () => {
      const { hash, isAdminRoute, isInviteRoute, isExplicitChat } = getRouteFlags();
      if (isAdminRoute || isInviteRoute || isExplicitChat) {
        setShowChat(true);
      } else if (!hash || hash === '#features' || hash === '#setup' || hash === '#top') {
        setShowChat(false);
      }
    };

    window.addEventListener('hashchange', syncRoute);
    window.addEventListener('popstate', syncRoute);
    return () => {
      window.removeEventListener('hashchange', syncRoute);
      window.removeEventListener('popstate', syncRoute);
    };
  }, []);

  const handleEnterChat = useCallback(() => {
    const { isAdminRoute, isInviteRoute } = getRouteFlags();
    if (!isAdminRoute && !isInviteRoute) {
      const nextUrl = `${window.location.pathname}${window.location.search}#chat`;
      window.history.pushState({ astraView: 'chat' }, '', nextUrl);
    }
    setShowChat(true);
  }, []);

  if (showChat) {
    return <App />;
  }

  return <LandingPage onEnterChat={handleEnterChat} />;
}

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <ErrorBoundary>
      <RootRouter />
    </ErrorBoundary>
  </React.StrictMode>
);
