// AuthScreen.jsx — AegisComply Login + Registration (Supabase-powered)

// ── Supabase client (initialised in config.js, exposed on window) ──────────
// window.supabaseClient — created by config.js after Supabase SDK loads

// ── Helper: fetch user profile from public.users after auth ───────────────
async function fetchUserProfile(userId) {
  const sb = window.supabaseClient;
  if (!sb) throw new Error('Supabase client not initialised');
  const { data, error } = await sb.from('users').select('*').eq('id', userId).single();
  if (error) throw error;
  return data;
}

// ── Map Supabase auth errors to friendly messages ─────────────────────────
function friendlyAuthError(err) {
  const msg = (err?.message || '').toLowerCase();
  if (msg.includes('invalid login credentials')) return 'Incorrect email or password.';
  if (msg.includes('email not confirmed'))       return 'Please check your email and confirm your account first.';
  if (msg.includes('user already registered'))   return 'An account with this email already exists. Please sign in.';
  if (msg.includes('password should be'))        return 'Password must be at least 8 characters.';
  if (msg.includes('rate limit'))                return 'Too many attempts. Please wait a moment and try again.';
  if (msg.includes('network'))                   return 'Connection problem. Check your internet and try again.';
  return err?.message || 'Something went wrong. Please try again.';
}

// ── Styles ─────────────────────────────────────────────────────────────────
const authStyles = {
  shell: { minHeight: '100vh', background: 'linear-gradient(135deg, #0B1F3A 0%, #0D2E4A 50%, #0A2540 100%)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 },
  card: { background: 'white', borderRadius: 16, width: '100%', maxWidth: 440, boxShadow: '0 24px 64px rgba(0,0,0,0.25)', overflow: 'hidden' },
  header: { background: '#0B1F3A', padding: '26px 32px 22px', textAlign: 'center' },
  logo: { display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, marginBottom: 4 },
  logoText: { fontFamily: "'Helvetica', Arial, sans-serif", fontSize: 22, fontWeight: 700, color: 'white', letterSpacing: '-0.3px' },
  logoAccent: { color: '#14B8A6', fontWeight: 700 },
  headerSub: { fontSize: 12, color: 'rgba(255,255,255,0.45)', marginTop: 4 },
  tabs: { display: 'flex', background: 'rgba(255,255,255,0.07)', borderRadius: 8, margin: '16px 0 0', padding: 3, gap: 3 },
  tab: { flex: 1, padding: '8px 0', fontSize: 13, fontWeight: 600, border: 'none', background: 'transparent', color: 'rgba(255,255,255,0.45)', cursor: 'pointer', borderRadius: 6, fontFamily: "'DM Sans',sans-serif", transition: 'all 150ms' },
  tabActive: { background: 'white', color: '#0B1F3A' },
  body: { padding: '24px 32px' },
  fieldGroup: { marginBottom: 14 },
  fieldLabel: { fontSize: 12, fontWeight: 600, color: '#334155', display: 'block', marginBottom: 5 },
  fieldInput: { width: '100%', height: 38, border: '1px solid #CBD5E1', borderRadius: 7, padding: '0 12px', fontFamily: "'DM Sans',sans-serif", fontSize: 13, color: '#0F172A', outline: 'none', background: 'white' },
  grid2: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 },
  submitBtn: { width: '100%', height: 42, border: 'none', borderRadius: 7, background: '#0D9488', fontSize: 14, fontWeight: 700, color: 'white', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif", marginTop: 6, transition: 'background 150ms' },
  errorBox: { background: '#FFF5F5', border: '1px solid #FECACA', borderRadius: 7, padding: '10px 12px', fontSize: 12, color: '#DC2626', marginBottom: 12, lineHeight: 1.5 },
  successBox: { background: '#F0FDF4', border: '1px solid #BBF7D0', borderRadius: 7, padding: '10px 12px', fontSize: 12, color: '#16A34A', marginBottom: 12 },
  pilotBox: { background: '#F0FDFA', border: '1px solid #99F6E4', borderRadius: 8, padding: '10px 14px', fontSize: 12, color: '#0F766E', marginBottom: 16, lineHeight: 1.6 },
  footer: { padding: '14px 32px', background: '#F8FAFC', borderTop: '1px solid #F1F5F9', textAlign: 'center', fontSize: 11, color: '#94A3B8' },
  subscribeBox: { background: '#FFF5F5', border: '1px solid #FECACA', borderRadius: 8, padding: '14px 16px', marginBottom: 16, lineHeight: 1.6 },
  subscribeTitle: { fontSize: 13, fontWeight: 700, color: '#DC2626', marginBottom: 4 },
  subscribeText: { fontSize: 12, color: '#7F1D1D' },
  subscribeBtn: { width: '100%', height: 38, border: 'none', borderRadius: 7, background: '#DC2626', fontSize: 13, fontWeight: 700, color: 'white', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif", marginTop: 10 },
  planSelect: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 14 },
  planOption: { border: '2px solid #E2E8F0', borderRadius: 8, padding: '10px 12px', cursor: 'pointer', transition: 'all 150ms', textAlign: 'center' },
  planOptionSelected: { border: '2px solid #0D9488', background: '#F0FDFA' },
  planName: { fontSize: 13, fontWeight: 700, color: '#0F172A', marginBottom: 2 },
  planPrice: { fontSize: 11, color: '#64748B' },
};

const PLANS = [
  { id: 'pilot',   name: '14-Day Pilot', price: 'Free', desc: 'Full access, no card' },
  { id: 'monthly', name: 'Monthly',      price: 'RM 289/mo', desc: 'Cancel anytime' },
  { id: 'yearly',  name: 'Yearly',       price: 'RM 249/mo', desc: 'RM 2,988/yr saved' },
];

// ── Login Form ──────────────────────────────────────────────────────────────
function LoginForm({ onLogin }) {
  const [form, setForm] = React.useState({ email: '', password: '' });
  const [error, setError] = React.useState('');
  const [info, setInfo] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [showSubscribe, setShowSubscribe] = React.useState(false);
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError(''); setInfo('');
    if (!form.email || !form.password) { setError('Please enter your email and password.'); return; }

    setLoading(true);
    try {
      const sb = window.supabaseClient;
      if (!sb) throw new Error('Supabase not initialised — check console.');

      const { data, error: signInError } = await sb.auth.signInWithPassword({
        email: form.email.trim().toLowerCase(),
        password: form.password,
      });
      if (signInError) throw signInError;

      // Fetch profile from public.users
      const profile = await fetchUserProfile(data.user.id);

      // Frozen tier — block login at app level (App.jsx already handles read-only banner)
      if (profile.tier === 'frozen') {
        setShowSubscribe(true);
        await sb.auth.signOut(); // sign out so they need to re-auth after subscribing
        return;
      }

      onLogin(profile);
    } catch (err) {
      console.error('[AuthScreen] Login error:', err);
      setError(friendlyAuthError(err));
    } finally {
      setLoading(false);
    }
  };

  const handleForgotPassword = async () => {
    setError(''); setInfo('');
    if (!form.email) { setError('Enter your email above first, then click "Forgot password".'); return; }
    try {
      const sb = window.supabaseClient;
      const { error: resetError } = await sb.auth.resetPasswordForEmail(form.email.trim().toLowerCase());
      if (resetError) throw resetError;
      setInfo('Password reset link sent. Check your email.');
    } catch (err) {
      setError(friendlyAuthError(err));
    }
  };

  if (showSubscribe) return (
    <div>
      <div style={authStyles.subscribeBox}>
        <div style={authStyles.subscribeTitle}>Your subscription has lapsed</div>
        <div style={authStyles.subscribeText}>
          The account <strong>{form.email}</strong> is currently frozen. To restore access, please contact us to renew your subscription.
        </div>
        <button style={authStyles.subscribeBtn} onClick={() => window.open('mailto:billing@aegiscomply.my?subject=Subscription Renewal — ' + form.email, '_blank')}>
          Contact Us to Renew →
        </button>
      </div>
      <div style={{ textAlign: 'center', fontSize: 12, color: '#94A3B8' }}>
        Plans from <strong style={{ color: '#0D9488' }}>RM 289/month</strong>. Email: billing@aegiscomply.my
      </div>
      <button style={{ ...authStyles.submitBtn, background: 'transparent', color: '#64748B', border: '1px solid #E2E8F0', marginTop: 12 }} onClick={() => setShowSubscribe(false)}>
        ← Back to Login
      </button>
    </div>
  );

  return (
    <form onSubmit={handleSubmit}>
      {error && <div style={authStyles.errorBox}>{error}</div>}
      {info && <div style={authStyles.successBox}>{info}</div>}
      <div style={authStyles.fieldGroup}>
        <label style={authStyles.fieldLabel}>Work Email</label>
        <input style={authStyles.fieldInput} type="email" placeholder="you@company.com.my" value={form.email} onChange={e => set('email', e.target.value)} autoComplete="email"/>
      </div>
      <div style={authStyles.fieldGroup}>
        <label style={authStyles.fieldLabel}>Password</label>
        <input style={authStyles.fieldInput} type="password" placeholder="Enter your password" value={form.password} onChange={e => set('password', e.target.value)} autoComplete="current-password"/>
        <div style={{ fontSize: 11, color: '#0D9488', marginTop: 5, cursor: 'pointer', textAlign: 'right' }} onClick={handleForgotPassword}>Forgot password?</div>
      </div>
      <button type="submit" style={{ ...authStyles.submitBtn, background: loading ? '#94A3B8' : '#0D9488' }} disabled={loading}>
        {loading ? 'Signing in…' : 'Sign In'}
      </button>
    </form>
  );
}

// ── Register Form ───────────────────────────────────────────────────────────
function RegisterForm({ onLogin, onSwitchToLogin }) {
  const [form, setForm] = React.useState({ company: '', name: '', email: '', phone: '', password: '', plan: 'pilot' });
  const [step, setStep] = React.useState(1);
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [needsConfirmation, setNeedsConfirmation] = React.useState(false);
  const set = (k, v) => { setForm(f => ({ ...f, [k]: v })); setError(''); };
  const valid1 = form.company && form.name && form.email && form.password && form.password.length >= 8;

  const handleNext = async () => {
    setError('');

    if (step === 1) {
      if (!valid1) { setError('Please fill in all fields. Password must be at least 8 characters.'); return; }
      setStep(2);
      return;
    }

    if (step === 2) {
      setLoading(true);
      try {
        const sb = window.supabaseClient;
        if (!sb) throw new Error('Supabase not initialised — check console.');

        // 1. Create Supabase Auth account
        const { data: signUpData, error: signUpError } = await sb.auth.signUp({
          email: form.email.trim().toLowerCase(),
          password: form.password,
          options: {
            data: {
              name: form.name,
              company: form.company,
              phone: form.phone,
            },
          },
        });
        if (signUpError) throw signUpError;

        // Detect "email already registered" — Supabase returns a fake user with empty identities
        if (signUpData.user && Array.isArray(signUpData.user.identities) && signUpData.user.identities.length === 0) {
          throw new Error('An account with this email already exists. Please sign in instead.');
        }

        const newUserId = signUpData.user?.id;

        // 2. If we got a user ID, insert profile row into public.users
        if (newUserId) {
          const { error: profileError } = await sb.from('users').insert({
            id:        newUserId,
            email:     form.email.trim().toLowerCase(),
            name:      form.name,
            phone:     form.phone || null,
            whatsapp:  form.phone || null,
            company:   form.company,
            role:      'Safety Officer',
            tier:      'pilot',
            pilot_used: true,
            created_by: 'self',
          });
          if (profileError && !/duplicate key/i.test(profileError.message)) {
            console.warn('[AuthScreen] Profile insert failed:', profileError);
            // don't block — the trigger or admin can create the profile later
          }
        }

        // 3. If no active session → email confirmation is required
        if (!signUpData.session) {
          setNeedsConfirmation(true);
          setLoading(false);
          return;
        }

        // 4. We have a session — log in immediately
        const profile = await fetchUserProfile(newUserId);
        setLoading(false);
        setStep(3);
        setTimeout(() => onLogin(profile), 1500);
      } catch (err) {
        console.error('[AuthScreen] Register error:', err);
        setError(friendlyAuthError(err));
        setLoading(false);
      }
    }
  };

  if (needsConfirmation) return (
    <div style={{ textAlign: 'center', padding: '16px 0' }}>
      <div style={{ width: 56, height: 56, borderRadius: '50%', background: '#F0FDFA', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 14px' }}>
        <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#0D9488" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
      </div>
      <div style={{ fontFamily: "'Helvetica',Arial,sans-serif", fontSize: 17, fontWeight: 700, color: '#0F172A', marginBottom: 6 }}>Confirm Your Email</div>
      <div style={{ fontSize: 13, color: '#64748B', marginBottom: 4 }}>We've sent a confirmation link to:</div>
      <div style={{ fontSize: 13, fontWeight: 600, color: '#0D9488', marginBottom: 16 }}>{form.email}</div>
      <div style={{ fontSize: 12, color: '#94A3B8', marginBottom: 18, lineHeight: 1.6 }}>
        Click the link in the email to activate your account, then return here to sign in.
      </div>
      <button style={{ ...authStyles.submitBtn, marginTop: 0 }} onClick={onSwitchToLogin}>
        Back to Sign In →
      </button>
    </div>
  );

  if (step === 3) return (
    <div style={{ textAlign: 'center', padding: '16px 0' }}>
      <div style={{ width: 56, height: 56, borderRadius: '50%', background: '#F0FDF4', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 14px' }}>
        <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#16A34A" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
      </div>
      <div style={{ fontFamily: "'Helvetica',Arial,sans-serif", fontSize: 17, fontWeight: 700, color: '#0F172A', marginBottom: 6 }}>Account Created!</div>
      <div style={{ fontSize: 13, color: '#64748B', marginBottom: 4 }}>Welcome, <strong>{form.name}</strong>. Your 14-day pilot starts now.</div>
      <div style={{ fontSize: 12, color: '#94A3B8', marginBottom: 18 }}>Signing you in…</div>
    </div>
  );

  return (
    <div>
      {/* Step indicator */}
      <div style={{ display: 'flex', gap: 6, marginBottom: 18, alignItems: 'center' }}>
        {['Company Details', 'Select Plan'].map((s, i) => (
          <React.Fragment key={i}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <div style={{ width: 22, height: 22, borderRadius: '50%', background: step > i + 1 ? '#16A34A' : step === i + 1 ? '#0D9488' : '#E2E8F0', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700, color: step >= i + 1 ? 'white' : '#94A3B8', flexShrink: 0 }}>
                {step > i + 1 ? '✓' : i + 1}
              </div>
              <span style={{ fontSize: 11, fontWeight: 600, color: step === i + 1 ? '#0F172A' : '#94A3B8' }}>{s}</span>
            </div>
            {i === 0 && <div style={{ flex: 1, height: 1, background: step > 1 ? '#0D9488' : '#E2E8F0' }}/>}
          </React.Fragment>
        ))}
      </div>

      {error && <div style={authStyles.errorBox}>{error}</div>}

      {step === 1 && (
        <>
          <div style={authStyles.pilotBox}>
            <strong>14-Day Free Pilot</strong> — Full system access, no credit card. Starts immediately on registration. Each email address can only be used once.
          </div>
          <div style={authStyles.fieldGroup}>
            <label style={authStyles.fieldLabel}>Company Name *</label>
            <input style={authStyles.fieldInput} placeholder="e.g. Petronas Chemicals Bhd" value={form.company} onChange={e => set('company', e.target.value)}/>
          </div>
          <div style={authStyles.grid2}>
            <div style={authStyles.fieldGroup}>
              <label style={authStyles.fieldLabel}>Your Name *</label>
              <input style={authStyles.fieldInput} placeholder="Full name" value={form.name} onChange={e => set('name', e.target.value)}/>
            </div>
            <div style={authStyles.fieldGroup}>
              <label style={authStyles.fieldLabel}>Phone</label>
              <input style={authStyles.fieldInput} placeholder="+60 12-xxx xxxx" value={form.phone} onChange={e => set('phone', e.target.value)}/>
            </div>
          </div>
          <div style={authStyles.fieldGroup}>
            <label style={authStyles.fieldLabel}>Work Email *</label>
            <input style={authStyles.fieldInput} type="email" placeholder="you@company.com.my" value={form.email} onChange={e => set('email', e.target.value)}/>
          </div>
          <div style={authStyles.fieldGroup}>
            <label style={authStyles.fieldLabel}>Password * <span style={{ color: '#94A3B8', fontWeight: 400 }}>(min 8 characters)</span></label>
            <input style={authStyles.fieldInput} type="password" placeholder="Create a strong password" value={form.password} onChange={e => set('password', e.target.value)}/>
          </div>
        </>
      )}

      {step === 2 && (
        <>
          <div style={{ fontSize: 13, fontWeight: 600, color: '#334155', marginBottom: 12 }}>What plan would you like after the pilot?</div>
          <div style={authStyles.planSelect}>
            {PLANS.map(p => (
              <div key={p.id} style={{ ...authStyles.planOption, ...(form.plan === p.id ? authStyles.planOptionSelected : {}) }} onClick={() => set('plan', p.id)}>
                <div style={authStyles.planName}>{p.name}</div>
                <div style={{ ...authStyles.planPrice, color: form.plan === p.id ? '#0D9488' : '#64748B', fontWeight: 600 }}>{p.price}</div>
                <div style={{ fontSize: 10, color: '#94A3B8', marginTop: 2 }}>{p.desc}</div>
              </div>
            ))}
          </div>
          <div style={{ fontSize: 11, color: '#94A3B8', marginBottom: 10, lineHeight: 1.6 }}>
            You will not be charged during the 14-day pilot. After the trial, you will be contacted to arrange payment based on your selected plan.
          </div>
        </>
      )}

      <button
        style={{ ...authStyles.submitBtn, background: (step === 1 && !valid1) || loading ? '#CBD5E1' : '#0D9488', cursor: (step === 1 && !valid1) ? 'not-allowed' : 'pointer' }}
        disabled={(step === 1 && !valid1) || loading}
        onClick={handleNext}
      >
        {loading ? 'Creating account…' : step === 1 ? 'Continue →' : 'Create Account & Start Pilot'}
      </button>
      {step === 2 && (
        <div style={{ textAlign: 'center', marginTop: 10 }}>
          <span style={{ fontSize: 12, color: '#0D9488', cursor: 'pointer' }} onClick={() => setStep(1)}>← Back</span>
        </div>
      )}
    </div>
  );
}

// ── Auth Shell ──────────────────────────────────────────────────────────────
function AuthScreen({ onLogin }) {
  const [tab, setTab] = React.useState('login');
  return (
    <div style={authStyles.shell}>
      <div style={authStyles.card}>
        <div style={authStyles.header}>
          <div style={authStyles.logo}>
            <img src="../../assets/logo-aegisfeld.png"
              style={{ width: 36, height: 36, objectFit: 'contain' }}
              alt="AegisComply"
              onError={e => { e.target.style.display = 'none'; }}
            />
            <span style={authStyles.logoText}>Aegis<span style={authStyles.logoAccent}>Comply</span></span>
          </div>
          <div style={authStyles.headerSub}>Industrial Compliance Management Platform</div>
          <div style={authStyles.tabs}>
            <button style={{ ...authStyles.tab, ...(tab === 'login' ? authStyles.tabActive : {}) }} onClick={() => setTab('login')}>Sign In</button>
            <button style={{ ...authStyles.tab, ...(tab === 'register' ? authStyles.tabActive : {}) }} onClick={() => setTab('register')}>Create Account</button>
          </div>
        </div>
        <div style={authStyles.body}>
          {tab === 'login'
            ? <LoginForm onLogin={onLogin}/>
            : <RegisterForm onLogin={onLogin} onSwitchToLogin={() => setTab('login')}/>
          }
        </div>
        <div style={authStyles.footer}>
          By continuing, you agree to AegisComply's Terms of Service and Privacy Policy.<br/>
          © 2026 AegisComply Sdn Bhd · All rights reserved.
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AuthScreen });
