/* global React */
const { useMemo: useMemoAuth, useState: useStateAuth } = React;

function AuthPage({ mode }) {
  const isSignup = mode === 'signup';
  const [isSubmitting, setIsSubmitting] = useStateAuth(false);
  const [error, setError] = useStateAuth('');
  const [form, setForm] = useStateAuth({
    fullName: '',
    email: '',
    phoneNumber: '',
    password: '',
    confirmPassword: '',
    termsAgreed: false,
  });

  const redirectPath = useMemoAuth(() => {
    const params = new URLSearchParams(window.location.search);
    const redirect = params.get('redirect') || '/';
    const allowExternalAppRedirect = params.get('auth_redirect') === 'demo';

    if (redirect.startsWith('/') && !redirect.startsWith('//')) {
      const target = new URL(redirect, window.location.origin);

      if (isAuthPage(target.pathname)) {
        return '/';
      }

      target.searchParams.delete('auth_redirect');

      return `${target.pathname}${target.search}${target.hash}`;
    }

    try {
      const target = new URL(redirect);
      const allowedHosts = [
        'pluginchatbot.com',
        'app.pluginchatbot.com',
      ];

      if (allowedHosts.includes(target.hostname)) {
        if (target.hostname === 'app.pluginchatbot.com' && !allowExternalAppRedirect) {
          return '/';
        }

        if (isAuthPage(target.pathname)) {
          return target.hostname === 'app.pluginchatbot.com' && allowExternalAppRedirect
            ? 'https://app.pluginchatbot.com/'
            : '/';
        }

        target.searchParams.delete('auth_redirect');

        return target.toString();
      }
    } catch (error) {}

    return '/';
  }, []);

  const updateField = (key, value) => {
    setError('');
    setForm(prev => ({ ...prev, [key]: value }));
  };

  const submitForm = async event => {
    event.preventDefault();
    setError('');

    if (isSignup) {
      const passwordError = getPasswordError(form.password);
      if (passwordError) {
        setError(passwordError);
        return;
      }

      if (form.password !== form.confirmPassword) {
        setError('Password and confirm password do not match.');
        return;
      }

      if (!form.termsAgreed) {
        setError('Please accept the Terms of Services.');
        return;
      }
    }

    setIsSubmitting(true);

    try {
      const response = await fetch(isSignup ? '/api/auth/signup' : '/api/auth/login', {
        method: 'POST',
        credentials: 'include',
        headers: {
          'content-type': 'application/json',
        },
        body: JSON.stringify(isSignup ? form : {
          email: form.email,
          password: form.password,
        }),
      });

      const data = await response.json();
      if (!response.ok || !data.ok) {
        throw new Error(data.error || 'Authentication failed.');
      }

      window.location.replace(redirectPath);
    } catch (submitError) {
      setError(submitError.message || 'Authentication failed.');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <main className="auth-page">
      <section className="auth-shell">
        <div className="auth-copy">
          <span className="eyebrow">Pluginchatbot account</span>
          <h1>{isSignup ? 'Create your account.' : 'Welcome back.'}</h1>
          <p>
            {isSignup
              ? 'Sign up to access the embedded chatbot builder and create chatbot widgets for your websites.'
              : 'Log in to continue building and managing your embedded chatbot widget.'}
          </p>
        </div>

        <form className="auth-card" onSubmit={submitForm}>
          <div>
            <h2>{isSignup ? 'Sign up' : 'Login'}</h2>
            <p>{isSignup ? 'Create a secure Pluginchatbot account.' : 'Access your Pluginchatbot builder.'}</p>
          </div>

          {isSignup && (
            <label className="auth-field">
              <span>Full Name</span>
              <input
                type="text"
                value={form.fullName}
                onChange={event => updateField('fullName', event.target.value)}
                required
                autoComplete="name"
              />
            </label>
          )}

          <label className="auth-field">
            <span>Email</span>
            <input
              type="email"
              value={form.email}
              onChange={event => updateField('email', event.target.value)}
              required
              autoComplete="email"
            />
          </label>

          {isSignup && (
            <label className="auth-field">
              <span>Phone Number</span>
              <input
                type="tel"
                value={form.phoneNumber}
                onChange={event => updateField('phoneNumber', event.target.value)}
                required
                autoComplete="tel"
              />
            </label>
          )}

          <label className="auth-field">
            <span>Password</span>
            <input
              type="password"
              value={form.password}
              onChange={event => updateField('password', event.target.value)}
              required
              autoComplete={isSignup ? 'new-password' : 'current-password'}
            />
          </label>

          {isSignup && (
            <>
              <label className="auth-field">
                <span>Confirm Password</span>
                <input
                  type="password"
                  value={form.confirmPassword}
                  onChange={event => updateField('confirmPassword', event.target.value)}
                  required
                  autoComplete="new-password"
                />
              </label>

              <div className="auth-password-note">
                Password must include at least 8 characters, uppercase, lowercase, number, and special character.
              </div>

              <label className="auth-check">
                <input
                  type="checkbox"
                  checked={form.termsAgreed}
                  onChange={event => updateField('termsAgreed', event.target.checked)}
                />
                <span>
                By clicking here I agree that I have read and accepted the{' '}
                <a
                    className="auth-terms-link"
                    href="https://nafcorp.com.au/wp-content/uploads/2026/01/NAFCORP-PTY-LTD-Terms-and-Conditions.pdf"
                    target="_blank"
                    rel="noopener noreferrer"
                >
                    Terms of Services
                </a>.
                </span>
              </label>
            </>
          )}

          {error && <div className="auth-error">{error}</div>}

          <button className="auth-submit pc-arrow-button" type="submit" disabled={isSubmitting}>
            <span>{isSubmitting ? 'Please wait...' : isSignup ? 'Create Account' : 'Login'}</span>
            <span aria-hidden="true">→</span>
          </button>

          <div className="auth-switch">
            {isSignup ? (
              <span>Already have an account? <a href={getAuthSwitchHref('login', redirectPath)}>Login</a></span>
            ) : (
              <span>Need an account? <a href={getAuthSwitchHref('signup', redirectPath)}>Sign up</a></span>
            )}
          </div>
        </form>
      </section>
    </main>
  );
}

function isAuthPage(pathname) {
  return pathname === '/login' || pathname === '/login.html' || pathname === '/signup.html';
}

function getAuthSwitchHref(mode, redirectPath) {
  const page = mode === 'signup' ? '/signup.html' : '/login.html';
  if (!redirectPath || redirectPath === '/') return page;
  const appRedirectParam = redirectPath.startsWith('https://app.pluginchatbot.com') ? '&auth_redirect=demo' : '';
  return `${page}?redirect=${encodeURIComponent(redirectPath)}${appRedirectParam}`;
}

function getPasswordError(password) {
  if (password.length < 8) return 'Password must be at least 8 characters long.';
  if (!/[A-Z]/.test(password)) return 'Password must include at least one uppercase letter.';
  if (!/[a-z]/.test(password)) return 'Password must include at least one lowercase letter.';
  if (!/[0-9]/.test(password)) return 'Password must include at least one number.';
  if (!/[^A-Za-z0-9]/.test(password)) return 'Password must include at least one special character.';
  return '';
}

window.AuthPage = AuthPage;
