import React from 'react';
import type { AppProps } from 'next/app';
import type { ReactElement, ReactNode } from 'react';
import type { NextPage } from 'next';
import Head from 'next/head';
import { store } from '../stores/store';
import { Provider } from 'react-redux';
import '../css/main.css';
import axios from 'axios';
import { baseURLApi } from '../config';
import { useRouter } from 'next/router';
import ErrorBoundary from '../components/ErrorBoundary';
import 'intro.js/introjs.css';
import { appWithTranslation } from 'next-i18next';
import '../i18n';
import IntroGuide from '../components/IntroGuide';
import { PublicCoachSiteProvider } from '../components/PublicCoachSiteProvider';
import {
  appSteps,
  loginSteps,
  usersSteps,
  rolesSteps,
} from '../stores/introSteps';

// Initialize axios
axios.defaults.baseURL = process.env.NEXT_PUBLIC_BACK_API
  ? process.env.NEXT_PUBLIC_BACK_API
  : baseURLApi;

axios.defaults.headers.common['Content-Type'] = 'application/json';
axios.defaults.withCredentials = true;

export type NextPageWithLayout<P = Record<string, unknown>, IP = P> = NextPage<
  P,
  IP
> & {
  getLayout?: (page: ReactElement) => ReactNode;
};

type AppPropsWithLayout = AppProps & {
  Component: NextPageWithLayout;
};

function MyApp({ Component, pageProps }: AppPropsWithLayout) {
  // Use the layout defined at the page level, if available
  const getLayout = Component.getLayout || ((page) => page);
  const router = useRouter();
  const [stepsEnabled, setStepsEnabled] = React.useState(false);
  const [stepName, setStepName] = React.useState('');
  const [steps, setSteps] = React.useState([]);

  // TODO: Remove this code in future releases
  React.useEffect(() => {
    const allowedOrigin = (() => {
      if (!document.referrer) {
        return null;
      }
      try {
        return new URL(document.referrer).origin;
      } catch (error) {
        console.warn(
          '[postMessage] Failed to parse parent origin from referrer',
          error,
        );
        return null;
      }
    })();

    const handleMessage = async (event: MessageEvent) => {
      const reply = (data: unknown) => {
        if (event.source) {
          (event.source as Window).postMessage(data, event.origin);
        }
      };

      if (event.data === 'getLocation') {
        reply({ iframeLocation: window.location.pathname });
        return;
      }

      if (event.data === 'getAuthToken') {
        if (allowedOrigin && event.origin !== allowedOrigin) {
          console.warn(
            '[postMessage] Blocked getAuthToken from origin',
            event.origin,
          );
          return;
        }
        reply({ iframeAuthToken: null, iframeAuthUser: null });
        return;
      }

      if (event.data === 'getScreenshot') {
        try {
          const html2canvas = (await import('html2canvas')).default;
          const canvas = await html2canvas(document.body, { useCORS: true });
          const url = canvas.toDataURL('image/jpeg', 0.8);
          reply({ iframeScreenshot: url });
        } catch (e) {
          console.error('html2canvas failed', e);
          reply({ iframeScreenshot: null });
        }
      }
    };

    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, []);

  React.useEffect(() => {
    // Tour is disabled by default in generated projects.
    return;
    const isCompleted = (stepKey: string) => {
      return localStorage.getItem(`completed_${stepKey}`) === 'true';
    };
    if (router.pathname === '/login' && !isCompleted('loginSteps')) {
      setSteps(loginSteps);
      setStepName('loginSteps');
      setStepsEnabled(true);
    } else if (router.pathname === '/dashboard' && !isCompleted('appSteps')) {
      setTimeout(() => {
        setSteps(appSteps);
        setStepName('appSteps');
        setStepsEnabled(true);
      }, 1000);
    } else if (
      router.pathname === '/users/users-list' &&
      !isCompleted('usersSteps')
    ) {
      setTimeout(() => {
        setSteps(usersSteps);
        setStepName('usersSteps');
        setStepsEnabled(true);
      }, 1000);
    } else if (
      router.pathname === '/roles/roles-list' &&
      !isCompleted('rolesSteps')
    ) {
      setTimeout(() => {
        setSteps(rolesSteps);
        setStepName('rolesSteps');
        setStepsEnabled(true);
      }, 1000);
    } else {
      setSteps([]);
      setStepsEnabled(false);
    }
  }, [router.pathname]);

  const handleExit = () => {
    setStepsEnabled(false);
  };

  const title = 'Coaching Workspace — Client Portal & AI Session Memory';
  const description =
    'A coaching workspace for client context, session memory, action items, resources, and client portal delivery.';
  const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || '';
  const url = siteUrl || (typeof window === 'undefined' ? '' : window.location.origin);
  const privateRoute = /^\/(dashboard|clients|intake-leads|session-memory|start-session|client-portal|profile|workspace-settings|users|roles|permissions)/.test(router.pathname);
  const noIndex = process.env.NEXT_PUBLIC_DEMO_MODE === 'true' || privateRoute;
  const image = url
    ? `${url.replace(/\/$/, '')}/images/coaching/coaching-workspace.jpg`
    : '/images/coaching/coaching-workspace.jpg';
  const imageWidth = '1920';
  const imageHeight = '960';

  return (
    <Provider store={store}>
      <PublicCoachSiteProvider>
        {getLayout(
          <>
          <Head>
            <meta name='description' content={description} />
            <meta name='robots' content={noIndex ? 'noindex,nofollow,noarchive' : 'index,follow'} />
            {!noIndex && url && <link rel='canonical' href={`${url}${router.asPath.split('?')[0]}`} />}

            <meta property='og:url' content={url} />
            <meta property='og:type' content='website' />
            <meta property='og:site_name' content='Coaching Workspace' />
            <meta property='og:title' content={title} />
            <meta property='og:description' content={description} />
            <meta property='og:image' content={image} />
            <meta property='og:image:type' content='image/jpeg' />
            <meta property='og:image:width' content={imageWidth} />
            <meta property='og:image:height' content={imageHeight} />

            <meta name='twitter:card' content='summary_large_image' />
            <meta name='twitter:title' content={title} />
            <meta name='twitter:description' content={description} />
            <meta name='twitter:image' content={image} />

            <link rel='icon' href='/favicon.svg' />
          </Head>

          {process.env.NEXT_PUBLIC_DEMO_MODE === 'true' && (
            <div role='status' className='bg-amber-100 px-4 py-2 text-center text-sm font-semibold text-amber-950'>
              DEMO — FICTIONAL DATA. This read-only workspace does not save changes or run paid AI operations.
            </div>
          )}
          <ErrorBoundary><Component {...pageProps} /></ErrorBoundary>
          <IntroGuide
            steps={steps}
            stepsName={stepName}
            stepsEnabled={stepsEnabled}
            onExit={handleExit}
          />
          </>,
        )}
      </PublicCoachSiteProvider>
    </Provider>
  );
}

export default appWithTranslation(MyApp);
