// Basic Error Boundary
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }

  componentDidCatch(error, errorInfo) {
    console.error('ErrorBoundary caught an error:', error, errorInfo.componentStack);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="min-h-screen flex items-center justify-center bg-gray-50">
          <div className="text-center p-8 bg-white rounded-xl shadow-lg max-w-md">
            <div className="w-16 h-16 bg-red-100 text-red-600 rounded-full flex items-center justify-center mx-auto mb-4">
                <span className="icon-triangle-alert text-3xl"></span>
            </div>
            <h1 className="text-2xl font-bold text-gray-900 mb-2">Something went wrong</h1>
            <p className="text-gray-600 mb-6">We encountered an unexpected error. Please try reloading the page.</p>
            <button
              onClick={() => window.location.reload()}
              className="px-6 py-2 bg-gray-900 text-white rounded-lg hover:bg-black transition-colors"
            >
              Reload System
            </button>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

// Placeholder Components for routes not yet implemented
function PlaceholderView({ title }) {
  return (
    <div className="flex flex-col items-center justify-center h-96 text-gray-400">
      <span className="icon-hammer text-6xl mb-4 text-gray-200"></span>
      <h2 className="text-2xl font-bold text-gray-300">{title} Module</h2>
      <p className="text-gray-400 mt-2">This module is currently under development.</p>
    </div>
  );
}

function App() {
  const [isLoaderReady, setIsLoaderReady] = React.useState(true);
  const [currentUser, setCurrentUser] = React.useState(null);
  const [currentView, setCurrentView] = React.useState('dashboard');
  
  // Toast State
  const [toasts, setToasts] = React.useState([]);

  // Handle Login
  const handleLogin = (user) => {
      setCurrentUser(user);
      // Save user to localStorage for persistence
      localStorage.setItem('pos_user', JSON.stringify(user));
      // Reload backend data after login
      if (window.BackendLoader && window.BackendLoader.init) {
          window.BackendLoader.init().catch(err => {
              console.error('Failed to reload backend data:', err);
          });
      }
      // Default view based on role
      if (user.role === 'cashier') {
          setCurrentView('pos');
      } else {
          setCurrentView('dashboard');
      }
      addToast('Welcome Back', `Logged in as ${user.name}`, 'success');
  };

  // Handle Logout
  const handleLogout = () => {
      setCurrentUser(null);
      setCurrentView('dashboard');
      // Clear session from localStorage
      localStorage.removeItem('pos_user');
      // Clear cached data
      Object.keys(localStorage).forEach(key => {
          if (key.startsWith('pos_')) {
              localStorage.removeItem(key);
          }
      });
      addToast('Logged Out', 'You have been signed out successfully.', 'info');
  };

  React.useEffect(() => {
     // Try to restore session from localStorage
     const savedUser = localStorage.getItem('pos_user');
     if (savedUser) {
         try {
             const userObj = JSON.parse(savedUser);
             setCurrentUser(userObj);
             
             // Verify user still exists in DB
             if (window.POSApiService) {
                 window.POSApiService.get(`auth.php?action=get_user&id=${userObj.id}`).then(res => {
                     if (res.error) {
                         console.warn('Session user not found in DB, logging out...');
                         handleLogout();
                     }
                 }).catch(err => console.error("Verify user fail:", err));
             }
         } catch (e) {
             console.error('Failed to restore session:', e);
             localStorage.removeItem('pos_user');
         }
     }

     // Load backend data
     if (window.BackendLoader) {
         window.BackendLoader.init().then(() => setIsLoaderReady(true));
     } else {
         setIsLoaderReady(true);
     }
  }, []);

  const addToast = (title, message, type = 'info') => {
      const id = Date.now();
      setToasts(prev => [...prev, { id, title, message, type }]);
      setTimeout(() => removeToast(id), 3000);
  };

  const removeToast = (id) => {
      setToasts(prev => prev.filter(t => t.id !== id));
  };


  // Render the appropriate view based on state
  const renderView = () => {
    const commonProps = { notify: addToast, user: currentUser, onChangeView: setCurrentView };
    
    switch(currentView) {
      case 'dashboard':
        return <Dashboard {...commonProps} />;
      case 'pos':
        return typeof POS !== 'undefined' ? <POS {...commonProps} /> : <PlaceholderView title="POS" />;
      case 'returns':
        return typeof Returns !== 'undefined' ? <Returns {...commonProps} /> : <PlaceholderView title="Returns & Exchange" />;
      case 'products':
        return typeof Products !== 'undefined' ? <Products {...commonProps} /> : <PlaceholderView title="Products" />;
      case 'promotions':
        return typeof Promotions !== 'undefined' ? <Promotions {...commonProps} /> : <PlaceholderView title="Promotions" />;
      case 'reports':
        return typeof Reports !== 'undefined' ? <Reports {...commonProps} /> : <PlaceholderView title="Reports" />;
      case 'inventory':
        return typeof Inventory !== 'undefined' ? <Inventory {...commonProps} /> : <PlaceholderView title="Inventory" />;
      case 'customers':
        return typeof Customers !== 'undefined' ? <Customers {...commonProps} /> : <PlaceholderView title="Customers" />;
      case 'suppliers':
        return typeof Suppliers !== 'undefined' ? <Suppliers {...commonProps} /> : <PlaceholderView title="Suppliers" />;
      case 'expenses':
        return typeof Expenses !== 'undefined' ? <Expenses {...commonProps} /> : <PlaceholderView title="Expenses" />;
      case 'label-print':
        return typeof LabelPrintCenter !== 'undefined' ? <LabelPrintCenter {...commonProps} /> : <PlaceholderView title="Label Print Center" />;
      case 'settings':
        return typeof Settings !== 'undefined' ? <Settings {...commonProps} /> : <PlaceholderView title="Settings" />;
      default:
        return <Dashboard {...commonProps} />;
    }
  };

  if (!isLoaderReady) {
      return (
          <div className="min-h-screen flex items-center justify-center bg-gray-50 flex-col gap-4">
              <span className="icon-loader text-4xl text-[var(--primary)] animate-spin"></span>
              <p className="text-gray-600 font-medium">Connecting to Backend System...</p>
          </div>
      );
  }

  if (!currentUser) {
      return (
        <>
            <Login onLogin={handleLogin} notify={addToast} />
            <ToastContainer toasts={toasts} removeToast={removeToast} />
            <DialogHost />
        </>
      );
  }

  return (
    <Layout 
      currentView={currentView} 
      onChangeView={setCurrentView}
      user={currentUser}
      onLogout={handleLogout}
    >
      {renderView()}
      <ToastContainer toasts={toasts} removeToast={removeToast} />
      <DialogHost />
    </Layout>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <ErrorBoundary>
    <App />
  </ErrorBoundary>
);