import { useState, useEffect } from 'react';
import { Routes, Route } from 'react-router';
import ErrorBoundary from './components/ErrorBoundary';
import DashboardLayout from './components/Layout/DashboardLayout';
import DashboardPage from './components/Dashboard/DashboardPage';
import WorkspaceTour from './components/deleteme_onboarding/WorkspaceTour';

function DashboardError() {
  return (
    <div style={{ background: '#222122', color: '#fff', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100dvh', width: '100vw', position: 'fixed', inset: 0, zIndex: 50, fontFamily: 'system-ui, -apple-system, sans-serif', textAlign: 'center', padding: '24px' }}>
      <video
        autoPlay
        loop
        muted
        playsInline
        style={{ height: 120, objectFit: 'contain', marginBottom: 32 }}
      >
        <source src="/morphy_hi.mov" type='video/mp4; codecs="hvc1"' />
        <source src="/morphy_hi.webm" type="video/webm" />
      </video>
      <h1 style={{ fontSize: 20, fontWeight: 600, marginBottom: 8 }}>Oopss.. Something wrong is not right</h1>
      <p style={{ fontSize: 14, color: 'rgba(255,255,255,0.5)', maxWidth: 320, lineHeight: 1.5 }}>
      If your agent is working, this is normal. If not, go poke them
      </p>
    </div>
  );
}

export default function App() {
  const [showOnboard, setShowOnboard] = useState(false);
  const [userName, setUserName] = useState('');
  const [botName, setBotName] = useState('Bloby');

  // ── Seamless reload: splash before full-reloads ───────────────────
  // Vite's reload-on-reconnect is suppressed by the supervisor-injected
  // workspace-guard (which also owns location.reload wrapping), so the
  // only reloads left are real ones: Vite full-reloads after frontend
  // changes. Show the HTML splash before those so the user sees
  // app → splash → app instead of a white flash.
  useEffect(() => {
    const splash = document.getElementById('splash');

    // Show the dark background before the reload unloads the page
    function showSplash() {
      if (!splash) return;
      splash.style.display = 'block';
      splash.style.opacity = '1';
    }

    // Vite HMR: show splash before a full-reload
    if (import.meta.hot) {
      import.meta.hot.on('vite:beforeFullReload', () => showSplash());
    }
  }, []);

  useEffect(() => {
    fetch('/api/settings', { signal: AbortSignal.timeout(3000) })
      .then((r) => {
        if (!r.ok) return;
        return r.json();
      })
      .then((s) => {
        if (!s) return;
        if (s.onboard_complete !== 'true') setShowOnboard(true);
        if (s.user_name) setUserName(s.user_name);
        if (s.agent_name) setBotName(s.agent_name);
      })
      .catch(() => {});
  }, []);

  // Listen for events from Bloby iframes via postMessage.
  // 'bloby:hmr-update' is intentionally ignored: Vite HMR handles hot
  // updates natively, and a manual location.reload() here would kill the
  // chat iframe's WebSocket connection for nothing.
  useEffect(() => {
    const handler = (e: MessageEvent) => {
      if (e.data?.type === 'bloby:onboard-complete') {
        setShowOnboard(false);
      }
    };
    window.addEventListener('message', handler);
    return () => window.removeEventListener('message', handler);
  }, []);

  return (
    <>
      <ErrorBoundary fallback={<DashboardError />}>
        <DashboardLayout userName={userName} botName={botName}>
          <Routes>
            <Route path="/" element={<DashboardPage />} />
            <Route path="*" element={<DashboardPage />} />
          </Routes>
        </DashboardLayout>
        <WorkspaceTour disabled={showOnboard} />
      </ErrorBoundary>

      {showOnboard && (
        <iframe
          src="/bloby/onboard.html"
          style={{ position: 'fixed', inset: 0, width: '100vw', height: '100dvh', border: 'none', zIndex: 200 }}
        />
      )}
    </>
  );
}
