/* eslint-disable react-hooks/exhaustive-deps */
import { PaymentProvider } from '@blocklet/payment-react';
import { useEffect } from 'react';
import { Header } from '@blocklet/ui-react';
import { Box, CircularProgress } from '@mui/material';
import { useSessionContext } from '../../contexts/session';

function LayoutLoading() {
  return (
    <Box
      sx={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}>
      <CircularProgress />
    </Box>
  );
}

// window.blocklet is bootstrapped synchronously in public/index.html but the
// full payload is overlaid from /__blocklet__.js. Treat the layout as "not
// ready" until the overlay has populated the fields the downstream components
// (Header, PaymentProvider) rely on, so we never render children against a
// half-initialized blocklet config.
function isBlockletReady() {
  const b = (window as any).blocklet;
  return !!(b && b.appPid && b.prefix);
}

/**
 * CF Workers layout for customer pages.
 * Uses Dashboard component for consistent header + SessionUser dropdown.
 * Adds "My Billing" to the user dropdown via sessionManagerProps.menu.
 */
export default function UserLayoutCF(props: any) {
  const { session, connectApi } = useSessionContext();

  useEffect(() => {
    if (session.initialized && !session.user) {
      session.login(() => {});
    }
  }, [session.initialized]);

  // Show a loading state (not a blank page, not a redirect) while either
  // window.blocklet or the session is still being resolved. Any child that
  // fires API calls on mount (useRequest / useEffect) must not run until
  // both are in place — otherwise the request goes out without the right
  // auth cookies/headers and may cascade into a redirect.
  if (!isBlockletReady() || !session.initialized) {
    return <LayoutLoading />;
  }

  // Session initialized but not logged in: the effect above will trigger the
  // DID Connect login modal. Keep showing the loading state instead of a
  // blank screen so the user doesn't perceive it as "bounced to home".
  if (!session.user) {
    return <LayoutLoading />;
  }

  return (
    <PaymentProvider session={session} connect={connectApi}>
      <Header
        meta={undefined}
        addons={undefined}
        sessionManagerProps={undefined}
        homeLink={undefined}
        theme={undefined}
        hideNavMenu={undefined}
        maxWidth={false}
        sx={{ borderBottom: '1px solid', borderColor: 'divider' }}
      />
      <Box sx={{ flex: 1, maxWidth: 1200, mx: 'auto', px: 3, py: 3, width: '100%' }}>{props.children}</Box>
    </PaymentProvider>
  );
}
