/* ============================================================
   Bizia — Auth pages  (/login /signup /forgot-password /invite)
   ============================================================ */
(function () {
  const { useState } = React;
  const { Button, Input, Icon, BiziaLogo, BiziaMark, Badge } = window;

  function SocialButtons() {
    return React.createElement('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 } },
      [['google', 'Google'], ['apple', 'Apple']].map(s =>
        React.createElement('button', { key: s[0], onClick: () => window.toast({ title: 'Demo only', desc: 'Social login is mocked in this prototype.', tone: 'info' }),
          style: { display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9, height: 44, borderRadius: 'var(--r-md)', border: '1px solid var(--border-strong)', background: 'var(--surface)', cursor: 'pointer', fontSize: 14, fontWeight: 550, color: 'var(--text)' },
          onMouseEnter: (e) => e.currentTarget.style.background = 'var(--surface-3)', onMouseLeave: (e) => e.currentTarget.style.background = 'var(--surface)' },
          React.createElement(Icon, { name: s[0], size: 18 }), 'Continue with ' + s[1])),
    );
  }

  function Divider({ label }) {
    return React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 12, margin: '20px 0' } },
      React.createElement('div', { style: { flex: 1, height: 1, background: 'var(--border)' } }),
      React.createElement('span', { style: { fontSize: 12.5, color: 'var(--muted-2)' } }, label),
      React.createElement('div', { style: { flex: 1, height: 1, background: 'var(--border)' } }),
    );
  }

  // Right-side brand showcase
  function BrandPanel() {
    return React.createElement('div', { className: 'bz-auth-aside', style: { flex: 1, position: 'relative', overflow: 'hidden', background: 'linear-gradient(150deg,var(--primary) 0%, var(--primary-700) 60%, #2D2EA8 100%)', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', padding: 48 } },
      React.createElement('div', { style: { position: 'absolute', inset: 0, backgroundImage: 'repeating-linear-gradient(135deg, rgba(255,255,255,0.05) 0 1px, transparent 1px 18px)' } }),
      React.createElement('div', { style: { position: 'absolute', top: '-20%', right: '-10%', width: 400, height: 400, borderRadius: '50%', background: 'radial-gradient(circle, rgba(45,212,191,0.35), transparent 70%)' } }),
      React.createElement('div', { style: { position: 'relative' } }, React.createElement(BiziaLogo, { size: 24, mono: true })),
      React.createElement('div', { style: { position: 'relative' } },
        React.createElement('h2', { style: { fontSize: 34, fontWeight: 740, color: '#fff', letterSpacing: '-0.03em', lineHeight: 1.1 } }, 'Launch your whole business from one prompt.'),
        React.createElement('p', { style: { fontSize: 16, color: 'rgba(255,255,255,0.82)', marginTop: 16, lineHeight: 1.55, maxWidth: 420 } }, 'Website, domain, hosting, logins, socials, e-cards, leads and analytics — Bizia plans and builds it all.'),
        React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 12, marginTop: 28 } },
          [['globe', 'Domain & hosting decided for you'], ['inbox', 'Leads flow into one simple inbox'], ['idcard', 'Team e-cards & social kit, ready to go']].map((r, i) =>
            React.createElement('div', { key: i, style: { display: 'flex', alignItems: 'center', gap: 12 } },
              React.createElement('div', { style: { width: 36, height: 36, borderRadius: 10, background: 'rgba(255,255,255,0.16)', backdropFilter: 'blur(8px)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff' } }, React.createElement(Icon, { name: r[0], size: 18 })),
              React.createElement('span', { style: { fontSize: 14.5, color: '#fff', fontWeight: 500 } }, r[1]),
            )),
        ),
      ),
      React.createElement('div', { style: { position: 'relative', display: 'flex', alignItems: 'center', gap: 12 } },
        React.createElement('div', { style: { display: 'flex' } },
          window.DATA.employees.slice(0, 4).map((e, i) => React.createElement('div', { key: i, style: { marginLeft: i ? -10 : 0 } }, React.createElement(window.Avatar, { name: e.name, tone: e.color, size: 34, ring: true }))),
        ),
        React.createElement('span', { style: { fontSize: 13.5, color: 'rgba(255,255,255,0.85)' } }, 'Trusted by 12,000+ small businesses'),
      ),
    );
  }

  function Field({ children }) { return React.createElement('div', { style: { marginBottom: 16 } }, children); }

  function AuthPage({ mode }) {
    const [theme, setTheme] = window.useTheme();
    const [step, setStep] = useState('form'); // form | org (signup)
    const [email, setEmail] = useState('');
    const [pw, setPw] = useState('');
    const [showPw, setShowPw] = useState(false);
    const [err, setErr] = useState('');
    const [sent, setSent] = useState(false);
    const [org, setOrg] = useState('');
    const [orgType, setOrgType] = useState('');
    const [loading, setLoading] = useState(false);

    const titles = {
      login: ['Welcome back', 'Log in to your Bizia workspace'],
      signup: ['Create your account', 'Start launching in minutes — no card required'],
      forgot: ['Reset your password', 'We’ll email you a secure reset link'],
      invite: ['You’re invited', 'Join your workspace on Bizia'],
    }[mode] || ['', ''];

    async function submit() {
      if (mode === 'forgot') {
        if (!email.includes('@')) { setErr('Enter a valid email address'); return; }
        setSent(true); return;
      }
      if (!email.includes('@')) { setErr('Enter a valid email address'); return; }
      if (mode !== 'forgot' && pw.length < 6) { setErr('Password must be at least 6 characters'); return; }
      setErr('');
      if (mode === 'signup') { setStep('org'); return; }
      if (mode === 'login') {
        setLoading(true);
        try {
          const data = await window.API.auth.login(email, pw);
          window.API.auth.setToken(data.token);
          sessionStorage.setItem('bz_user', JSON.stringify(data.user));
          window.toast({ title: 'Signed in', desc: 'Welcome back.', tone: 'success' });
          window.navigate('/app');
        } catch (e) {
          setErr(e.message || 'Login failed. Check your email and password.');
        } finally {
          setLoading(false);
        }
        return;
      }
      // Invitation acceptance has no real backend endpoint yet — only
      // grants a session in explicit demo mode (see BiziaAuth.loginDemo).
      if (window.BiziaAuth.loginDemo()) {
        window.toast({ title: 'Signed in', desc: 'Welcome to your workspace.', tone: 'success' });
      }
    }

    function finishOrg() {
      // Self-service sign-up has no real backend endpoint (Bizia is
      // invitation-only) — only grants a session in explicit demo mode.
      if (!window.BiziaAuth.loginDemo()) return;
      window.toast({ title: 'Workspace created', desc: org || 'Your business', tone: 'success' });
      window.navigate('/app/new');
    }

    const formInner = step === 'org'
      ? React.createElement('div', { className: 'bz-anim-up' },
          React.createElement('div', { style: { marginBottom: 8 } }, React.createElement(Badge, { tone: 'secondary', icon: 'check' }, 'Account created')),
          React.createElement('h1', { style: { fontSize: 26, fontWeight: 720, letterSpacing: '-0.03em' } }, 'Set up your workspace'),
          React.createElement('p', { style: { fontSize: 14.5, color: 'var(--muted)', marginTop: 8, marginBottom: 24 } }, 'Tell us about your business so Bizia can tailor your launch plan.'),
          React.createElement(Field, null, React.createElement(Input, { label: 'Business name', icon: 'building', placeholder: 'e.g. AmazeBites Cafe', value: org, onChange: (e) => setOrg(e.target.value) })),
          React.createElement('div', { style: { marginBottom: 8, fontSize: 13, fontWeight: 600, color: 'var(--text-2)' } }, 'What kind of business is it?'),
          React.createElement('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 24 } },
            window.DATA.wizard.types.slice(0, 6).map(t => React.createElement(window.Chip, { key: t.id, icon: t.icon, active: orgType === t.id, onClick: () => setOrgType(t.id) }, t.label)),
          ),
          React.createElement(Button, { variant: 'primary', full: true, size: 'lg', iconRight: 'arrowRight', onClick: finishOrg }, 'Continue to launch plan'),
        )
      : React.createElement('div', { className: 'bz-anim-up' },
          React.createElement('h1', { style: { fontSize: 27, fontWeight: 720, letterSpacing: '-0.03em' } }, titles[0]),
          React.createElement('p', { style: { fontSize: 14.5, color: 'var(--muted)', marginTop: 8, marginBottom: 26 } }, titles[1]),
          // No real invitation-lookup endpoint exists yet — show a neutral
          // message rather than a fabricated inviting org/person.
          mode === 'invite' ? React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 12, padding: 14, borderRadius: 'var(--r-md)', background: 'var(--surface-2)', border: '1px solid var(--border)', marginBottom: 22 } },
            React.createElement(window.Icon, { name: 'mail', size: 20, style: { color: 'var(--muted)' } }),
            React.createElement('div', { style: { fontSize: 13.5, color: 'var(--muted)' } }, 'You’ve been invited to join a Bizia workspace.'),
          ) : null,

          sent ? React.createElement('div', { style: { textAlign: 'center', padding: '20px 0' } },
            React.createElement('div', { style: { width: 56, height: 56, borderRadius: 16, background: 'var(--secondary-soft)', color: 'var(--secondary)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px' } }, React.createElement(Icon, { name: 'mail', size: 28 })),
            React.createElement('h3', { style: { fontSize: 18, fontWeight: 650 } }, 'Check your inbox'),
            React.createElement('p', { style: { fontSize: 14, color: 'var(--muted)', marginTop: 8 } }, 'We sent a reset link to ', React.createElement('strong', { style: { color: 'var(--text)' } }, email)),
            React.createElement(Button, { variant: 'ghost', icon: 'arrowLeft', style: { marginTop: 18 }, onClick: () => window.navigate('/login') }, 'Back to log in'),
          ) : React.createElement(React.Fragment, null,
            mode !== 'forgot' ? React.createElement(React.Fragment, null, React.createElement(SocialButtons, null), React.createElement(Divider, { label: 'or with email' })) : null,
            React.createElement(Field, null, React.createElement(Input, { label: 'Email', icon: 'mail', type: 'email', placeholder: 'you@business.com', value: email, onChange: (e) => { setEmail(e.target.value); setErr(''); }, error: err && !email.includes('@') ? err : '' })),
            mode !== 'forgot' ? React.createElement(Field, null,
              React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 7 } },
                React.createElement('span', { style: { fontSize: 13, fontWeight: 600, color: 'var(--text-2)' } }, 'Password'),
                mode === 'login' ? React.createElement('button', { onClick: () => window.navigate('/forgot-password'), style: { fontSize: 12.5, color: 'var(--primary)', fontWeight: 600, border: 'none', background: 'none', cursor: 'pointer' } }, 'Forgot?') : null,
              ),
              React.createElement(Input, { icon: 'lock', type: showPw ? 'text' : 'password', placeholder: mode === 'signup' ? 'Create a password' : '••••••••', value: pw, onChange: (e) => { setPw(e.target.value); setErr(''); }, error: err && pw.length < 6 && email.includes('@') ? err : '',
                suffix: React.createElement('button', { onClick: () => setShowPw(s => !s), style: { border: 'none', background: 'none', cursor: 'pointer', color: 'var(--muted)', display: 'flex' } }, React.createElement(Icon, { name: showPw ? 'eyeOff' : 'eye', size: 17 })) }),
              mode === 'signup' && pw.length > 0 ? React.createElement('div', { style: { display: 'flex', gap: 4, marginTop: 8 } },
                [0, 1, 2, 3].map(i => React.createElement('div', { key: i, style: { flex: 1, height: 4, borderRadius: 999, background: pw.length > i * 2 + 2 ? (pw.length > 9 ? 'var(--success)' : pw.length > 6 ? 'var(--accent)' : 'var(--warning)') : 'var(--surface-3)' } }))) : null,
            ) : null,
            err && email.includes('@') && (mode === 'forgot' || pw.length >= 6) ? React.createElement('div', {
              role: 'alert',
              style: { fontSize: 13, color: 'var(--danger)', background: 'var(--danger-soft, #fef2f2)', borderRadius: 'var(--r-sm)', padding: '9px 12px', marginBottom: 14 },
            }, err) : null,
            React.createElement(Button, { variant: 'primary', full: true, size: 'lg', onClick: submit, loading, disabled: loading, style: { marginTop: 6 } },
              loading ? 'Signing in…' : mode === 'login' ? 'Log in' : mode === 'signup' ? 'Create account' : mode === 'invite' ? 'Accept & join' : 'Send reset link'),
            mode === 'signup' ? React.createElement('p', { style: { fontSize: 12, color: 'var(--muted-2)', textAlign: 'center', marginTop: 14, lineHeight: 1.5 } }, 'By continuing you agree to Bizia’s Terms & Privacy Policy.') : null,
          ),

          mode !== 'forgot' && !sent ? React.createElement('p', { style: { fontSize: 14, color: 'var(--muted)', textAlign: 'center', marginTop: 22 } },
            mode === 'login' ? 'New to Bizia? ' : 'Already have an account? ',
            React.createElement('button', { onClick: () => window.navigate(mode === 'login' ? '/signup' : '/login'), style: { color: 'var(--primary)', fontWeight: 650, border: 'none', background: 'none', cursor: 'pointer', fontSize: 14 } }, mode === 'login' ? 'Create an account' : 'Log in'),
          ) : null,

          !sent ? React.createElement('div', { style: { marginTop: 24, borderTop: '1px solid var(--border)', paddingTop: 20 } },
            React.createElement('button', {
              onClick: () => window.BiziaAuth.loginDemo(),
              style: {
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, width: '100%',
                height: 44, borderRadius: 'var(--r-md)', border: '1.5px dashed var(--border-strong)',
                background: 'var(--surface-2)', cursor: 'pointer', fontSize: 14, fontWeight: 600,
                color: 'var(--text-2)', transition: 'background .14s, border-color .14s',
              },
              onMouseEnter: (e) => { e.currentTarget.style.background = 'var(--surface-3)'; e.currentTarget.style.borderColor = 'var(--primary)'; e.currentTarget.style.color = 'var(--primary)'; },
              onMouseLeave: (e) => { e.currentTarget.style.background = 'var(--surface-2)'; e.currentTarget.style.borderColor = 'var(--border-strong)'; e.currentTarget.style.color = 'var(--text-2)'; },
            },
              React.createElement(Icon, { name: 'sparkles', size: 16 }),
              'Continue in Demo Mode',
            ),
            React.createElement('p', { style: { fontSize: 11.5, color: 'var(--muted-2)', textAlign: 'center', marginTop: 8 } }, 'Local dev only — no account required'),
          ) : null,
        );

    return React.createElement('div', { className: 'bz-app-bg', style: { minHeight: '100vh', display: 'flex' } },
      // form side
      React.createElement('div', { style: { flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, maxWidth: 560, margin: '0 auto', width: '100%' } },
        React.createElement('div', { style: { padding: '24px 32px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' } },
          React.createElement(BiziaLogo, { size: 21, showByline: true, onClick: () => window.navigate('/') }),
          React.createElement(window.IconButton, { name: theme === 'dark' ? 'sun' : 'moon', label: 'Theme', onClick: () => setTheme(theme === 'dark' ? 'light' : 'dark') }),
        ),
        React.createElement('div', { style: { flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '12px 32px 40px' } },
          React.createElement('div', { style: { width: '100%', maxWidth: 380 } }, formInner),
        ),
      ),
      React.createElement(BrandPanel, null),
      React.createElement('style', null, '@media(max-width:920px){.bz-auth-aside{display:none !important}}'),
    );
  }

  window.AuthPage = AuthPage;
})();
