// MaxAMove — Authentication gate
//
// Defines two things on the global window:
//   - window.AuthScreen : the login / signup form
//   - window.AppRoot    : the wrapper that decides whether to show the
//                          login form or the main CRM (window.App)
//
// MaxAMove App.html mounts <AppRoot /> instead of <App /> directly.

const { useState, useEffect } = React;

// ---------------------------------------------------------------------------
// AuthScreen — the login / signup form
// ---------------------------------------------------------------------------
function AuthScreen() {
  const [mode, setMode] = useState('signin');   // 'signin' or 'signup'
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [fullName, setFullName] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  const [info, setInfo] = useState('');

  async function handleSubmit(e) {
    e.preventDefault();
    setError('');
    setInfo('');
    setBusy(true);
    try {
      if (mode === 'signin') {
        const { error } = await window.sb.auth.signInWithPassword({ email, password });
        if (error) throw error;
        // On success, AppRoot's auth listener will swap us out for <App />.
      } else {
        const { error } = await window.sb.auth.signUp({
          email,
          password,
          options: {
            data: { full_name: fullName || email.split('@')[0] }
          }
        });
        if (error) throw error;
        setInfo('Account created — signing you in…');
      }
    } catch (err) {
      setError(err.message || 'Something went wrong. Please try again.');
    } finally {
      setBusy(false);
    }
  }

  return (
    <div style={styles.page}>
      <div style={styles.pageInner}>
        <div style={styles.card}>
          {/* Dark gradient "header band" inside the card.
              Contained, intentional, so the logo's teal/green has high contrast
              against the dark — without coloring the entire page. */}
          <div style={styles.cardHeader}>
            <div style={styles.cardHeaderGlow} aria-hidden="true" />
            <img
              src="uploads/logo_color.png"
              alt="MaxAMove Moving Solutions"
              style={styles.logoImg}
              onError={e => { e.currentTarget.style.display = 'none'; e.currentTarget.nextElementSibling.style.display = 'flex'; }}
            />
            <div style={{ ...styles.logoMark, display: 'none' }}>MAXA</div>
          </div>

          <div style={styles.cardBody}>

        <div style={styles.tabs}>
          <button
            type="button"
            style={{ ...styles.tab, ...(mode === 'signin' ? styles.tabActive : {}) }}
            onClick={() => { setMode('signin'); setError(''); setInfo(''); }}
          >
            Sign in
          </button>
          <button
            type="button"
            style={{ ...styles.tab, ...(mode === 'signup' ? styles.tabActive : {}) }}
            onClick={() => { setMode('signup'); setError(''); setInfo(''); }}
          >
            Create account
          </button>
        </div>

        <form onSubmit={handleSubmit} style={styles.form}>
          {mode === 'signup' && (
            <label style={styles.label}>
              <span style={styles.labelText}>Your name</span>
              <input
                type="text"
                value={fullName}
                onChange={e => setFullName(e.target.value)}
                placeholder="Gavin Hetzel"
                style={styles.input}
                autoComplete="name"
                disabled={busy}
              />
            </label>
          )}

          <label style={styles.label}>
            <span style={styles.labelText}>Email</span>
            <input
              type="email"
              required
              value={email}
              onChange={e => setEmail(e.target.value)}
              placeholder="you@example.com"
              style={styles.input}
              autoComplete="email"
              disabled={busy}
            />
          </label>

          <label style={styles.label}>
            <span style={styles.labelText}>Password</span>
            <input
              type="password"
              required
              minLength={6}
              value={password}
              onChange={e => setPassword(e.target.value)}
              placeholder={mode === 'signup' ? 'At least 6 characters' : 'Your password'}
              style={styles.input}
              autoComplete={mode === 'signup' ? 'new-password' : 'current-password'}
              disabled={busy}
            />
          </label>

          {error && <div style={styles.errorBox}>{error}</div>}
          {info && <div style={styles.infoBox}>{info}</div>}

          <button type="submit" style={styles.primaryBtn} disabled={busy}>
            {busy ? 'Working…' : mode === 'signin' ? 'Sign in' : 'Create account'}
          </button>
        </form>

        <div style={styles.divider}>
          <span style={styles.dividerLine} />
          <span style={styles.dividerText}>or</span>
          <span style={styles.dividerLine} />
        </div>

        <button type="button" style={styles.googleBtn} disabled title="Google sign-in coming soon">
          <span style={{ fontWeight: 700 }}>G</span>
          <span>Continue with Google</span>
          <span style={styles.soonBadge}>Soon</span>
        </button>

        <div style={styles.footer}>
          {mode === 'signin'
            ? <>New here? <a href="#" onClick={e => { e.preventDefault(); setMode('signup'); }} style={styles.link}>Create an account</a></>
            : <>Already have an account? <a href="#" onClick={e => { e.preventDefault(); setMode('signin'); }} style={styles.link}>Sign in</a></>
          }
        </div>
          </div>{/* /cardBody */}
        </div>{/* /card */}

        <div style={styles.smallPrint}>
          MaxAMove Moving Solutions · Powered by your private CRM
        </div>
      </div>{/* /pageInner */}
    </div>
  );
}

// ---------------------------------------------------------------------------
// AppRoot — the gate
//   1. On mount, asks Supabase "is anyone logged in?"
//   2. Subscribes to auth changes (login / logout)
//   3. Renders <App /> if signed in, <AuthScreen /> if not
// ---------------------------------------------------------------------------
function AppRoot() {
  const [session, setSession] = useState(null);
  const [checking, setChecking] = useState(true);

  useEffect(() => {
    let cancelled = false;

    window.sb.auth.getSession().then(({ data }) => {
      if (cancelled) return;
      setSession(data.session);
      setChecking(false);
    });

    const { data: sub } = window.sb.auth.onAuthStateChange((_event, newSession) => {
      setSession(newSession);
      setChecking(false);
    });

    return () => {
      cancelled = true;
      sub.subscription.unsubscribe();
    };
  }, []);

  if (checking) {
    return (
      <div style={styles.page}>
        <div style={{ color: '#64748b', fontFamily: "'DM Sans', sans-serif" }}>Loading…</div>
      </div>
    );
  }

  if (!session) {
    return React.createElement(AuthScreen);
  }

  // Stash the session/user where any other file can read it.
  window.currentSession = session;
  window.currentUser = session.user;

  if (typeof window.App !== 'function') {
    return (
      <div style={styles.page}>
        <div style={styles.card}>
          <div style={{ color: '#dc2626', fontFamily: "'DM Sans', sans-serif" }}>
            App component failed to load. Check the browser console.
          </div>
        </div>
      </div>
    );
  }

  return React.createElement(window.App);
}

// Helper for any module that wants a "Sign out" button.
window.signOut = async function signOut() {
  await window.sb.auth.signOut();
};

window.AuthScreen = AuthScreen;
window.AppRoot = AppRoot;

// ---------------------------------------------------------------------------
// Styles — inline so this file is self-contained.
// Uses the same teal/green palette as the rest of the app.
// ---------------------------------------------------------------------------
const styles = {
  // Outer scroll container: covers viewport regardless of host overflow.
  // Uses position:fixed inset:0 to override the host's `html,body { overflow: hidden }`
  // so the auth screen always scrolls when content is taller than the viewport.
  page: {
    position: 'fixed',
    top: 0, left: 0, right: 0, bottom: 0,
    overflowY: 'auto',
    overflowX: 'hidden',
    background: '#f7fafc',  // soft near-white
    fontFamily: "'DM Sans', sans-serif",
    WebkitOverflowScrolling: 'touch',
  },
  // Inner wrapper: at least viewport height, centers content vertically when it fits,
  // expands and lets the outer container scroll when it doesn't.
  pageInner: {
    minHeight: '100%',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    padding: '32px 16px',
    boxSizing: 'border-box',
  },
  card: {
    width: '100%',
    maxWidth: '420px',
    background: '#fff',
    borderRadius: '20px',
    border: '1px solid #e2e8f0',
    // Soft layered shadow — feels grounded but not heavy
    boxShadow: '0 24px 48px rgba(15, 23, 42, 0.10), 0 8px 16px rgba(15, 23, 42, 0.04)',
    overflow: 'hidden',  // keeps the gradient header's rounded corners crisp
  },
  // Dark gradient header band inside the card — contained and intentional
  cardHeader: {
    background: 'radial-gradient(ellipse at 50% 30%, #0f4341 0%, #0c2826 50%, #06141a 100%)',
    padding: '38px 28px 34px',
    textAlign: 'center',
    position: 'relative',
    overflow: 'hidden',
  },
  // Subtle inner bloom — gives the dark area depth, makes it feel lit
  cardHeaderGlow: {
    position: 'absolute',
    top: '-30%',
    left: '50%',
    transform: 'translateX(-50%)',
    width: '380px',
    height: '380px',
    background: 'radial-gradient(circle, rgba(20, 198, 191, 0.20) 0%, rgba(61, 204, 126, 0.08) 35%, transparent 70%)',
    pointerEvents: 'none',
    filter: 'blur(8px)',
  },
  logoImg: {
    width: '240px',
    maxWidth: '85%',
    height: 'auto',
    objectFit: 'contain',
    position: 'relative',
    zIndex: 2,
    filter: 'drop-shadow(0 2px 12px rgba(20, 198, 191, 0.3))',
  },
  // Fallback wordmark if image fails
  logoMark: {
    padding: '14px 24px',
    borderRadius: '12px',
    background: 'linear-gradient(135deg,#14C6BF,#3DCC7E)',
    color: '#fff',
    fontFamily: "'Poppins', sans-serif",
    fontWeight: 800,
    fontSize: '24px',
    letterSpacing: '0.04em',
    position: 'relative',
    zIndex: 2,
  },
  // White form area inside the card
  cardBody: {
    padding: '32px 32px 28px',
  },
  tabs: {
    display: 'flex',
    background: '#f1f5f9',
    borderRadius: '10px',
    padding: '4px',
    marginBottom: '20px',
    gap: '4px',
  },
  tab: {
    flex: 1,
    padding: '8px 12px',
    border: 'none',
    background: 'transparent',
    color: '#64748b',
    fontSize: '13px',
    fontWeight: 600,
    borderRadius: '7px',
    cursor: 'pointer',
    fontFamily: "'DM Sans', sans-serif",
  },
  tabActive: {
    background: '#fff',
    color: '#0f172a',
    boxShadow: '0 1px 3px rgba(0,0,0,0.08)',
  },
  form: {
    display: 'flex',
    flexDirection: 'column',
    gap: '14px',
  },
  label: {
    display: 'flex',
    flexDirection: 'column',
    gap: '6px',
  },
  labelText: {
    fontSize: '12px',
    fontWeight: 600,
    color: '#475569',
    letterSpacing: '0.01em',
  },
  input: {
    padding: '11px 13px',
    border: '1px solid #e2e8f0',
    borderRadius: '9px',
    fontSize: '14px',
    background: '#f8fafc',
    color: '#0f172a',
    fontFamily: "'DM Sans', sans-serif",
    outline: 'none',
    transition: 'border-color 0.15s, background 0.15s',
  },
  errorBox: {
    background: '#fef2f2',
    border: '1px solid #fecaca',
    color: '#b91c1c',
    padding: '10px 12px',
    borderRadius: '8px',
    fontSize: '13px',
  },
  infoBox: {
    background: '#f0fdfb',
    border: '1px solid #99f6e4',
    color: '#0f766e',
    padding: '10px 12px',
    borderRadius: '8px',
    fontSize: '13px',
  },
  primaryBtn: {
    marginTop: '6px',
    padding: '12px 16px',
    background: 'linear-gradient(135deg,#14C6BF,#3DCC7E)',
    color: '#fff',
    border: 'none',
    borderRadius: '10px',
    fontSize: '14px',
    fontWeight: 700,
    cursor: 'pointer',
    fontFamily: "'DM Sans', sans-serif",
    transition: 'opacity 0.15s, transform 0.15s',
  },
  divider: {
    display: 'flex',
    alignItems: 'center',
    gap: '10px',
    margin: '20px 0 14px',
  },
  dividerLine: {
    flex: 1,
    height: '1px',
    background: '#e2e8f0',
  },
  dividerText: {
    fontSize: '11px',
    color: '#94a3b8',
    fontWeight: 600,
    letterSpacing: '0.08em',
    textTransform: 'uppercase',
  },
  googleBtn: {
    width: '100%',
    padding: '11px 14px',
    background: '#fff',
    border: '1px solid #e2e8f0',
    borderRadius: '10px',
    fontSize: '13.5px',
    fontWeight: 600,
    color: '#475569',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    gap: '10px',
    cursor: 'not-allowed',
    opacity: 0.6,
    fontFamily: "'DM Sans', sans-serif",
  },
  soonBadge: {
    marginLeft: 'auto',
    background: '#f1f5f9',
    color: '#64748b',
    fontSize: '10px',
    fontWeight: 700,
    padding: '2px 7px',
    borderRadius: '4px',
    letterSpacing: '0.05em',
    textTransform: 'uppercase',
  },
  footer: {
    marginTop: '20px',
    textAlign: 'center',
    fontSize: '13px',
    color: '#64748b',
  },
  link: {
    color: '#0a9e98',
    textDecoration: 'none',
    fontWeight: 600,
  },
  smallPrint: {
    marginTop: '20px',
    fontSize: '11px',
    color: '#94a3b8',
    letterSpacing: '0.06em',
    textAlign: 'center',
  },
};
