// MCP Hero - Authentication with Real API Integration
const { useState: useAuthState, useEffect: useAuthEffect } = React;

// API Service Integration
function LoginScreen({ nav }) {
  const [email, setEmail] = useAuthState('');
  const [pw, setPw] = useAuthState('');
  const [remember, setRemember] = useAuthState(false);
  const [loading, setLoading] = useAuthState(false);
  const [error, setError] = useAuthState('');

  const submit = async () => {
    if (!email || !pw) {
      setError('Please enter email and password');
      return;
    }

    setLoading(true);
    setError('');

    try {
      const response = await window.apiService.login({
        email,
        password: pw,
        rememberMe: remember
      });

      if (response.success) {
        // Trigger app-wide state update
        window.dispatchEvent(new CustomEvent('auth-change', {
          detail: { user: response.user, token: response.token }
        }));
        nav('/dashboard');
      }
    } catch (err) {
      setError(err.message || 'Login failed. Please check your credentials.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <AuthShell nav={nav} footer={<span>New to MCP Hero? <AuthLink onClick={() => nav('/register')}>Create an account</AuthLink></span>}>
      <AuthTitle title="Welcome back" sub="Sign in to manage your MCPs and credits."></AuthTitle>
      {error ? (
        <div style={{ display: 'flex', gap: 8, alignItems: 'center', padding: '10px 14px', borderRadius: 10, background: 'var(--danger-bg)', color: 'var(--danger)', fontSize: 13.5, fontWeight: 600, marginBottom: 16 }}>
          <Icon name="alert" size={15}></Icon> {error}
        </div>
      ) : null}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 15 }}>
        <Field label="Email">
          <TextInput
            value={email}
            onChange={setEmail}
            placeholder="you@company.com"
            type="email"
            disabled={loading}
          />
        </Field>
        <Field label="Password">
          <TextInput
            value={pw}
            onChange={setPw}
            placeholder="••••••••"
            type="password"
            disabled={loading}
          />
        </Field>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <label style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 13.5, color: 'var(--text-2)', cursor: 'pointer' }}>
            <input
              type="checkbox"
              checked={remember}
              onChange={(e) => setRemember(e.target.checked)}
              disabled={loading}
              style={{ accentColor: 'var(--accent)', width: 15, height: 15 }}
            />
            Remember me for 30 days
          </label>
          <AuthLink onClick={() => nav('/forgot')}>Forgot password?</AuthLink>
        </div>
        <Btn
          size="lg"
          onClick={submit}
          style={{ justifyContent: 'center', marginTop: 4 }}
          disabled={loading}
        >
          {loading ? 'Signing in...' : 'Sign in'}
        </Btn>
      </div>
    </AuthShell>
  );
}

// Register Screen with Real API
function RegisterScreen({ nav }) {
  const [step, setStep] = useAuthState(1);
  const [form, setForm] = useAuthState({
    email: '',
    password: '',
    fullName: '',
    accountType: null,
    organizationName: ''
  });
  const [loading, setLoading] = useAuthState(false);
  const [error, setError] = useAuthState('');
  const [requiresVerification, setRequiresVerification] = useAuthState(false);

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const credsOk = form.email.includes('@') && form.password.length >= 8 && /\d/.test(form.password) && form.fullName;
  const typeOk = form.accountType === 'individual' || (form.accountType === 'organization' && form.organizationName.trim());

  const handleRegister = async () => {
    setLoading(true);
    setError('');

    try {
      const userData = {
        email: form.email,
        password: form.password,
        fullName: form.fullName,
        accountType: form.accountType
      };

      if (form.accountType === 'organization') {
        userData.organizationName = form.organizationName;
      }

      const response = await window.apiService.register(userData);

      if (response.success) {
        if (response.requiresVerification) {
          setRequiresVerification(true);
        } else {
          // Auto-login after registration if no verification required
          const loginResponse = await window.apiService.login({
            email: form.email,
            password: form.password
          });

          if (loginResponse.success) {
            window.dispatchEvent(new CustomEvent('auth-change', {
              detail: { user: loginResponse.user, token: loginResponse.token }
            }));
            nav('/dashboard');
          }
        }
      }
    } catch (err) {
      setError(err.message || 'Registration failed. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  if (requiresVerification) {
    return (
      <AuthShell nav={nav}>
        <div style={{ textAlign: 'center', padding: '12px 0' }}>
          <div style={{
            width: 54, height: 54, borderRadius: '50%',
            background: 'var(--ok-bg)', color: 'var(--ok)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            margin: '0 auto 16px'
          }}>
            <Icon name="mail" size={24}></Icon>
          </div>
          <AuthTitle
            title="Check your email"
            sub={`We've sent a verification link to ${form.email}. Please click the link to activate your account.`}
          />
          <p style={{ fontSize: 13.5, color: 'var(--text-2)', marginTop: 16 }}>
            After verification, you can sign in to access your account.
          </p>
          <Btn
            variant="secondary"
            onClick={() => nav('/login')}
            style={{ marginTop: 20 }}
          >
            Go to sign in
          </Btn>
        </div>
      </AuthShell>
    );
  }

  const TypeCard = ({ id, icon, title, desc }) => {
    const active = form.accountType === id;
    return (
      <div
        onClick={() => (active ? null : set('accountType', id))}
        style={{
          border: `2px solid ${active ? 'var(--accent)' : 'var(--border)'}`,
          borderRadius: 12, padding: 16, cursor: 'pointer',
          background: active ? 'color-mix(in oklch, var(--accent) 8%, transparent)' : 'var(--bg)',
          transition: 'all .2s ease'
        }}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
          <Icon name={icon} size={20} style={{ color: active ? 'var(--accent)' : 'var(--text-2)' }}></Icon>
          <span style={{ fontSize: 15, fontWeight: 700, color: active ? 'var(--accent)' : 'var(--text)' }}>{title}</span>
        </div>
        <p style={{ margin: 0, fontSize: 13, color: 'var(--text-2)', lineHeight: 1.4 }}>{desc}</p>
      </div>
    );
  };

  return (
    <AuthShell nav={nav} footer={<span>Already have an account? <AuthLink onClick={() => nav('/login')}>Sign in</AuthLink></span>}>
      <StepDots step={step} />

      {step === 1 && (
        <>
          <AuthTitle title="Create your account" sub="Step 1 of 3"></AuthTitle>
          {error && (
            <div style={{
              display: 'flex', gap: 8, alignItems: 'center',
              padding: '10px 14px', borderRadius: 10,
              background: 'var(--danger-bg)', color: 'var(--danger)',
              fontSize: 13.5, fontWeight: 600, marginBottom: 16
            }}>
              <Icon name="alert" size={15}></Icon> {error}
            </div>
          )}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 15 }}>
            <Field label="Full name">
              <TextInput
                value={form.fullName}
                onChange={(v) => set('fullName', v)}
                placeholder="John Doe"
                disabled={loading}
              />
            </Field>
            <Field label="Email">
              <TextInput
                value={form.email}
                onChange={(v) => set('email', v)}
                placeholder="you@company.com"
                type="email"
                disabled={loading}
              />
            </Field>
            <Field label="Password">
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                <TextInput
                  value={form.password}
                  onChange={(v) => set('password', v)}
                  placeholder="••••••••"
                  type="password"
                  disabled={loading}
                />
                <PasswordStrength pw={form.password} />
              </div>
            </Field>
            <Btn
              size="lg"
              onClick={() => setStep(2)}
              disabled={!credsOk || loading}
              style={{ justifyContent: 'center', marginTop: 4 }}
            >
              Continue
            </Btn>
          </div>
        </>
      )}

      {step === 2 && (
        <>
          <AuthTitle title="Choose account type" sub="Step 2 of 3"></AuthTitle>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <TypeCard
              id="individual"
              icon="user"
              title="Personal account"
              desc="For individual developers and personal projects"
            />
            <TypeCard
              id="organization"
              icon="building"
              title="Organization"
              desc="For teams and businesses with multiple users"
            />
            <Btn
              variant="secondary"
              onClick={() => setStep(1)}
              disabled={loading}
              style={{ justifyContent: 'center' }}
            >
              Back
            </Btn>
          </div>
        </>
      )}

      {step === 3 && (
        <>
          <AuthTitle title="Organization details" sub="Step 3 of 3"></AuthTitle>
          {error && (
            <div style={{
              display: 'flex', gap: 8, alignItems: 'center',
              padding: '10px 14px', borderRadius: 10,
              background: 'var(--danger-bg)', color: 'var(--danger)',
              fontSize: 13.5, fontWeight: 600, marginBottom: 16
            }}>
              <Icon name="alert" size={15}></Icon> {error}
            </div>
          )}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 15 }}>
            {form.accountType === 'organization' && (
              <Field label="Organization name">
                <TextInput
                  value={form.organizationName}
                  onChange={(v) => set('organizationName', v)}
                  placeholder="Acme Corporation"
                  disabled={loading}
                />
              </Field>
            )}
            <div style={{
              padding: 14, borderRadius: 10, background: 'var(--bg-sunken)',
              fontSize: 12.5, color: 'var(--text-2)', lineHeight: 1.5
            }}>
              By creating an account, you agree to our Terms of Service and Privacy Policy.
            </div>
            <div style={{ display: 'flex', gap: 12 }}>
              <Btn
                variant="secondary"
                onClick={() => setStep(2)}
                disabled={loading}
                style={{ flex: 1 }}
              >
                Back
              </Btn>
              <Btn
                size="lg"
                onClick={handleRegister}
                disabled={!typeOk || loading}
                style={{ flex: 1, justifyContent: 'center' }}
              >
                {loading ? 'Creating account...' : 'Create account'}
              </Btn>
            </div>
          </div>
        </>
      )}
    </AuthShell>
  );
}

// Logout function that can be called from anywhere
async function handleLogout(nav) {
  try {
    await window.apiService.logout();
    window.dispatchEvent(new CustomEvent('auth-change', {
      detail: { user: null, token: null }
    }));
    nav('/login');
  } catch (error) {
    console.error('Logout error:', error);
    // Force logout even if API call fails
    window.apiService.clearSession();
    window.dispatchEvent(new CustomEvent('auth-change', {
      detail: { user: null, token: null }
    }));
    nav('/login');
  }
}