import React from 'react';
import { Routes, Route, Navigate, useLocation } from 'react-router-dom';
import Container from '@/components/Layout/Container';
import { AccountLayout } from './components/AccountLayout';
import Dashboard from './Dashboard';
import Orders from './Orders';
import OrderDetails from './OrderDetails';
import Downloads from './Downloads';
import Addresses from './Addresses';
import Wishlist from './Wishlist';
import AccountDetails from './AccountDetails';
import Licenses from './Licenses';
import LicenseConnect from './LicenseConnect';
import Subscriptions from './Subscriptions';
import SubscriptionDetail from './SubscriptionDetail';
import AffiliateDashboard from './AffiliateDashboard';

export default function Account() {
  const user = (window as any).woonoowCustomer?.user;
  const location = useLocation();

  // Redirect to login if not authenticated
  if (!user?.isLoggedIn) {
    const currentPath = location.pathname + location.search;
    return <Navigate to={`/login?redirect=${encodeURIComponent(currentPath)}`} replace />;
  }

  // Check if this is the license-connect route (render without AccountLayout)
  if (location.pathname.includes('/license-connect')) {
    return <LicenseConnect />;
  }

  return (
    <Container>
      <AccountLayout>
        <Routes>
          <Route index element={<Dashboard />} />
          <Route path="orders" element={<Orders />} />
          <Route path="orders/:orderId" element={<OrderDetails />} />
          <Route path="downloads" element={<Downloads />} />
          <Route path="addresses" element={<Addresses />} />
          <Route path="wishlist" element={<Wishlist />} />
          <Route path="licenses" element={<Licenses />} />
          <Route path="subscriptions" element={<Subscriptions />} />
          <Route path="subscriptions/:id" element={<SubscriptionDetail />} />
          <Route path="affiliate" element={<AffiliateDashboard />} />
          <Route path="account-details" element={<AccountDetails />} />
          <Route path="*" element={<Navigate to="/my-account" replace />} />
        </Routes>
      </AccountLayout>
    </Container>
  );
}
