// MCP Hero — auth flows: login, register (3 steps), forgot password, invitation accept
const { useState: useAuthState } = React;

function AuthShell({ children, footer, nav }) {
  const goHome = () => {
    if (nav) { nav('/'); }
    else { window.location.hash = '/'; window.scrollTo({ top: 0 }); }
  };
  return (
    <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 24, position: 'relative', overflow: 'hidden' }}>
      <div aria-hidden="true" style={{
        position: 'absolute', inset: 0, pointerEvents: 'none', opacity: .6,
        background: 'radial-gradient(600px 300px at 15% 0%, color-mix(in oklch, var(--accent) 12%, transparent), transparent 70%), radial-gradient(500px 280px at 90% 100%, color-mix(in oklch, var(--accent) 9%, transparent), transparent 70%)',
      }}></div>
      <button onClick={goHome} title="Back to marketplace" style={{
        position: 'absolute', top: 22, left: 22, display: 'flex', alignItems: 'center', gap: 7,
        border: '1px solid var(--border)', background: 'color-mix(in oklch, var(--bg-raised) 70%, transparent)',
        backdropFilter: 'blur(8px)', cursor: 'pointer', padding: '8px 13px 8px 10px', borderRadius: 999,
        fontSize: 13, fontWeight: 600, color: 'var(--text-2)', transition: 'color .13s ease, border-color .13s ease',
      }}>
        <Icon name="arrowLeft" size={15}></Icon> Marketplace
      </button>
      <div className="mh-anim" style={{ position: 'relative', width: '100%', maxWidth: 440, display: 'flex', flexDirection: 'column', gap: 20 }}>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <button onClick={goHome} title="Back to marketplace" style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 0 }}>
            <Logo size={34}></Logo>
          </button>
        </div>
        <Card style={{ padding: 30 }}>{children}</Card>
        {footer ? <div style={{ textAlign: 'center', fontSize: 13.5, color: 'var(--text-3)' }}>{footer}</div> : null}
      </div>
    </div>
  );
}

function AuthTitle({ title, sub }) {
  return (
    <div style={{ marginBottom: 20 }}>
      <h1 style={{ margin: 0, fontSize: 23, fontFamily: 'var(--font-display)', fontWeight: 700, letterSpacing: '-.01em' }}>{title}</h1>
      {sub ? <p style={{ margin: '6px 0 0', fontSize: 14, color: 'var(--text-2)', lineHeight: 1.5 }}>{sub}</p> : null}
    </div>
  );
}

function AuthLink({ onClick, children }) {
  return <a onClick={(e) => { e.preventDefault(); onClick(); }} href="#" style={{ color: 'var(--accent)', fontWeight: 600, textDecoration: 'none' }}>{children}</a>;
}

// ---------- Login ----------
function LoginScreen({ nav }) {
  const [email, setEmail] = useAuthState('');
  const [pw, setPw] = useAuthState('');
  const [remember, setRemember] = useAuthState(false);
  const [error, setError] = useAuthState(false);
  const submit = () => {
    if (!email || !pw) { setError(true); return; }
    nav('/dashboard');
  };
  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> Email or password is incorrect
        </div>
      ) : null}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 15 }}>
        <Field label="Email"><TextInput value={email} onChange={setEmail} placeholder="you@company.com" type="email"></TextInput></Field>
        <Field label="Password"><TextInput value={pw} onChange={setPw} placeholder="••••••••" type="password"></TextInput></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)} style={{ accentColor: 'var(--accent)', width: 15, height: 15 }}></input>
            Remember me for 30 days
          </label>
          <AuthLink onClick={() => nav('/forgot')}>Forgot password?</AuthLink>
        </div>
        <Btn size="lg" onClick={submit} style={{ justifyContent: 'center', marginTop: 4 }}>Sign in</Btn>
      </div>
    </AuthShell>
  );
}

// ---------- Forgot password ----------
function ForgotScreen({ nav }) {
  const [email, setEmail] = useAuthState('');
  const [sent, setSent] = useAuthState(false);
  return (
    <AuthShell nav={nav} footer={<span><AuthLink onClick={() => nav('/login')}>Back to sign in</AuthLink></span>}>
      {sent ? (
        <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={`If an account exists for ${email || 'that address'}, we've sent a reset link. It expires in 1 hour.`}></AuthTitle>
          <Btn variant="secondary" onClick={() => setSent(false)}>Resend email</Btn>
        </div>
      ) : (
        <div>
          <AuthTitle title="Reset your password" sub="Enter your account email and we'll send you a single-use reset link."></AuthTitle>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 15 }}>
            <Field label="Email"><TextInput value={email} onChange={setEmail} placeholder="you@company.com" type="email"></TextInput></Field>
            <Btn size="lg" onClick={() => setSent(true)} style={{ justifyContent: 'center' }}>Send reset link</Btn>
          </div>
        </div>
      )}
    </AuthShell>
  );
}

// ---------- Register (3 steps) ----------
function PasswordStrength({ pw }) {
  const ok8 = pw.length >= 8;
  const okNum = /\d/.test(pw);
  const Rule = ({ ok, children }) => (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 12, fontWeight: 600, color: ok ? 'var(--ok)' : 'var(--text-3)' }}>
      <Icon name={ok ? 'check' : 'clock'} size={12}></Icon>{children}
    </span>
  );
  return (
    <div style={{ display: 'flex', gap: 14 }}>
      <Rule ok={ok8}>8+ characters</Rule>
      <Rule ok={okNum}>At least one number</Rule>
    </div>
  );
}

function StepDots({ step }) {
  return (
    <div style={{ display: 'flex', gap: 6, marginBottom: 18 }}>
      {[1, 2, 3].map((n) => (
        <div key={n} style={{
          height: 5, borderRadius: 3, flex: 1, transition: 'background .25s ease',
          background: n <= step ? 'var(--accent)' : 'var(--border)',
        }}></div>
      ))}
    </div>
  );
}

function RegisterScreen({ nav }) {
  const [step, setStep] = useAuthState(1);
  const [form, setForm] = useAuthState({ email: '', pw: '', name: '', type: null, orgName: '' });
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const credsOk = form.email.includes('@') && form.pw.length >= 8 && /\d/.test(form.pw) && form.name;
  const typeOk = form.type === 'personal' || (form.type === 'org' && form.orgName.trim());

  const TypeCard = ({ id, icon, title, desc }) => {
    const active = form.type === id;
    return (
      <button onClick={() => set('type', id)} style={{
        display: 'flex', gap: 13, alignItems: 'flex-start', textAlign: 'left', padding: '15px 16px',
        borderRadius: 13, cursor: 'pointer', transition: 'all .15s ease', width: '100%',
        border: `2px solid ${active ? 'var(--accent)' : 'var(--border)'}`,
        background: active ? 'color-mix(in oklch, var(--accent) 7%, var(--bg-raised))' : 'var(--bg-raised)',
      }}>
        <div style={{
          width: 38, height: 38, borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          background: active ? 'var(--accent)' : 'var(--bg-sunken)', color: active ? '#fff' : 'var(--text-3)', transition: 'all .15s ease',
        }}><Icon name={icon} size={19}></Icon></div>
        <div>
          <div style={{ fontWeight: 700, fontSize: 14.5, color: 'var(--text)' }}>{title}</div>
          <div style={{ fontSize: 12.5, color: 'var(--text-3)', marginTop: 2, lineHeight: 1.45 }}>{desc}</div>
        </div>
      </button>
    );
  };

  return (
    <AuthShell nav={nav} footer={step < 3 ? <span>Already have an account? <AuthLink onClick={() => nav('/login')}>Sign in</AuthLink></span> : null}>
      <StepDots step={step}></StepDots>
      {step === 1 ? (
        <div>
          <AuthTitle title="Create your account" sub="Install MCPs into your AI client in minutes."></AuthTitle>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 15 }}>
            <Field label="Full name"><TextInput value={form.name} onChange={(v) => set('name', v)} placeholder="Amir Hakim"></TextInput></Field>
            <Field label="Email"><TextInput value={form.email} onChange={(v) => set('email', v)} placeholder="you@company.com" type="email"></TextInput></Field>
            <Field label="Password">
              <TextInput value={form.pw} onChange={(v) => set('pw', v)} placeholder="••••••••" type="password"></TextInput>
            </Field>
            <PasswordStrength pw={form.pw}></PasswordStrength>
            <Btn size="lg" disabled={!credsOk} onClick={() => setStep(2)} style={{ justifyContent: 'center', marginTop: 4 }}>Continue</Btn>
          </div>
        </div>
      ) : null}
      {step === 2 ? (
        <div>
          <AuthTitle title="How will you use MCP Hero?" sub="This choice is fixed after registration."></AuthTitle>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
            <TypeCard id="personal" icon="key" title="Personal" desc="Just you. Private credit wallet, your own API keys."></TypeCard>
            <TypeCard id="org" icon="users" title="Organization" desc="A team workspace with a shared credit pool. Invite members as Admins or Editors."></TypeCard>
            {form.type === 'org' ? (
              <div className="mh-anim">
                <Field label="Organization name">
                  <TextInput value={form.orgName} onChange={(v) => set('orgName', v)} placeholder="Kapital Partners Sdn Bhd"></TextInput>
                </Field>
                <p style={{ fontSize: 12.5, color: 'var(--text-3)', margin: '8px 0 0' }}>You'll be the first <strong>Org Admin</strong> — you can invite your team after setup.</p>
              </div>
            ) : null}
            <div style={{ display: 'flex', gap: 10, marginTop: 6 }}>
              <Btn variant="secondary" size="lg" onClick={() => setStep(1)} icon="arrowLeft">Back</Btn>
              <Btn size="lg" disabled={!typeOk} onClick={() => setStep(3)} style={{ flex: 1, justifyContent: 'center' }}>Create account</Btn>
            </div>
          </div>
        </div>
      ) : null}
      {step === 3 ? (
        <div style={{ textAlign: 'center', padding: '10px 0' }}>
          <div style={{ width: 58, height: 58, borderRadius: '50%', background: 'var(--ok-bg)', color: 'var(--ok)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px' }}>
            <Icon name="mail" size={26}></Icon>
          </div>
          <AuthTitle title="Check your email" sub={`We've sent a verification link to ${form.email || 'your inbox'}. Verify within 24 hours to start installing MCPs.`}></AuthTitle>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <Btn size="lg" onClick={() => nav('/dashboard')} style={{ justifyContent: 'center' }}>I've verified — go to dashboard</Btn>
            <Btn variant="ghost" onClick={() => {}}>Resend verification email</Btn>
          </div>
        </div>
      ) : null}
    </AuthShell>
  );
}

// ---------- Invitation accept ----------
function InvitationScreen({ nav }) {
  const [pw, setPw] = useAuthState('');
  const pwOk = pw.length >= 8 && /\d/.test(pw);
  return (
    <AuthShell nav={nav} footer={<span>Wrong account? Contact your Org Admin.</span>}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderRadius: 12, background: 'color-mix(in oklch, var(--accent) 8%, var(--bg-raised))', border: '1px solid color-mix(in oklch, var(--accent) 25%, var(--border))', marginBottom: 20 }}>
        <Avatar initials="KP" size={40} hue={250}></Avatar>
        <div>
          <div style={{ fontWeight: 700, fontSize: 14.5 }}>Kapital Partners</div>
          <div style={{ fontSize: 12.5, color: 'var(--text-3)' }}>Sarah Lim invited you to join as <strong style={{ color: 'var(--text-2)' }}>Editor</strong></div>
        </div>
      </div>
      <AuthTitle title="Join your team" sub="Set a password to activate your account. No email verification needed — this invitation counts."></AuthTitle>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 15 }}>
        <Field label="Email"><TextInput value="daniel@kapitalpartners.my" disabled></TextInput></Field>
        <Field label="Set a password"><TextInput value={pw} onChange={setPw} placeholder="••••••••" type="password"></TextInput></Field>
        <PasswordStrength pw={pw}></PasswordStrength>
        <Btn size="lg" disabled={!pwOk} onClick={() => nav('/dashboard')} style={{ justifyContent: 'center', marginTop: 4 }}>Accept invitation</Btn>
        <p style={{ fontSize: 12, color: 'var(--text-3)', margin: 0, textAlign: 'center' }}>This link is single-use and expires 48 hours after it was sent.</p>
      </div>
    </AuthShell>
  );
}

Object.assign(window, { LoginScreen, ForgotScreen, RegisterScreen, InvitationScreen, AuthShell, AuthTitle, PasswordStrength });
