// Auth gate — wraps the Home Hub app and only renders it once the user has a
// Supabase session. Handles magic-link sign-in, the email-callback redirect,
// and sign-out. Themed to match the Home Hub aesthetic.

function AuthGate({ children }) {
  // status: 'checking' | 'signed-out' | 'loading' | 'ready' | 'error'
  const [status, setStatus] = React.useState('checking');
  const [errorMsg, setErrorMsg] = React.useState('');
  const [, force] = React.useReducer(x => x + 1, 0);

  React.useEffect(() => {
    let mounted = true;
    if (!window.SB) { setStatus('error'); setErrorMsg('Supabase not loaded.'); return; }

    async function handleSession(session) {
      if (!mounted) return;
      if (!session) {
        if (window.Cloud) window.Cloud.setUser(null);
        setStatus('signed-out');
        return;
      }
      setStatus('loading');
      try {
        if (window.Cloud) {
          window.Cloud.setUser(session.user);
          await window.Cloud.loadState();
        }
        if (mounted) setStatus('ready');
      } catch (e) {
        console.error(e);
        if (mounted) { setStatus('error'); setErrorMsg(String(e && e.message || e)); }
      }
    }

    window.SB.auth.getSession().then(({ data }) => handleSession(data.session));

    const { data: sub } = window.SB.auth.onAuthStateChange((event, session) => {
      if (event === 'SIGNED_IN')      handleSession(session);
      else if (event === 'SIGNED_OUT') {
        if (window.Cloud) { window.Cloud.setUser(null); window.Cloud.clearLocal(); }
        setStatus('signed-out');
        force();
      }
      else if (event === 'TOKEN_REFRESHED' && session && window.Cloud) {
        window.Cloud.setUser(session.user);
      }
    });

    return () => { mounted = false; sub.subscription.unsubscribe(); };
  }, []);

  if (status === 'ready')        return children;
  if (status === 'checking')     return <AuthSplash msg="Loading…"/>;
  if (status === 'loading')      return <AuthSplash msg="Loading your home hub…"/>;
  if (status === 'error')        return <AuthSplash msg={`Something went wrong: ${errorMsg}`}/>;
  return <LoginScreen/>;
}

// ---------- Login screen ----------

function LoginScreen() {
  const [email, setEmail] = React.useState('');
  const [sending, setSending] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  const [error, setError] = React.useState('');

  async function submit(e) {
    e.preventDefault();
    if (!email.trim()) return;
    setSending(true); setError('');
    try {
      const { error } = await window.SB.auth.signInWithOtp({
        email: email.trim(),
        options: {
          emailRedirectTo: window.location.origin + window.location.pathname,
          shouldCreateUser: false, // signups are off — only existing users
        },
      });
      if (error) setError(error.message);
      else setSent(true);
    } catch (err) {
      setError(String(err && err.message || err));
    } finally {
      setSending(false);
    }
  }

  const sage = '#a3b18a';
  const ink  = '#2a2a26';

  return (
    <div style={{
      minHeight: '100vh', width: '100vw',
      background: '#f3f1ec',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 20, fontFamily: "'Geist', system-ui, sans-serif",
    }}>
      <div style={{
        width: '100%', maxWidth: 420,
        background: '#fff',
        border: '1px solid #e7e3d8',
        borderRadius: 18,
        boxShadow: '0 24px 60px rgba(20,18,12,0.08)',
        padding: '36px 32px 30px',
      }}>
        <div style={{
          width: 44, height: 44, borderRadius: 11,
          background: `linear-gradient(135deg, ${sage} 0%, #6b8e4e 100%)`,
          color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 20, fontWeight: 600, marginBottom: 18,
        }}>K</div>

        <h1 style={{
          fontSize: 26, fontWeight: 600, color: ink, margin: 0,
          letterSpacing: -0.4, lineHeight: 1.15,
        }}>Kingsleigh Home Hub</h1>
        <p style={{ fontSize: 14, color: '#6b6a64', marginTop: 8, marginBottom: 26, lineHeight: 1.5 }}>
          {sent
            ? "Check your email for a sign-in link. You can close this tab — opening the link signs you in."
            : "Sign in with a magic link sent to your email."}
        </p>

        {!sent && (
          <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <span style={{ fontSize: 12, color: '#6b6a64', fontWeight: 500 }}>Email</span>
              <input
                type="email" autoFocus required
                value={email} onChange={(e) => setEmail(e.target.value)}
                placeholder="you@gmail.com"
                style={{
                  padding: '11px 13px',
                  fontSize: 15, fontFamily: 'inherit',
                  background: '#f7f5ef',
                  border: '1px solid #e0dccf',
                  borderRadius: 10,
                  color: ink, outline: 'none',
                }}
              />
            </label>
            {error && (
              <div style={{
                fontSize: 13, color: '#8a3a2a',
                background: '#fbeae4', border: '1px solid #f0c8b8',
                padding: '9px 11px', borderRadius: 9,
              }}>{error}</div>
            )}
            <button
              type="submit" disabled={sending || !email.trim()}
              style={{
                marginTop: 4, padding: '12px 14px',
                fontSize: 14.5, fontWeight: 600, fontFamily: 'inherit',
                background: ink, color: '#f3f1ec',
                border: 'none', borderRadius: 10, cursor: sending ? 'default' : 'pointer',
                opacity: sending || !email.trim() ? 0.6 : 1,
                transition: 'opacity 0.15s ease',
              }}>
              {sending ? 'Sending…' : 'Send sign-in link'}
            </button>
          </form>
        )}

        {sent && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 4 }}>
            <div style={{
              fontSize: 13, color: '#3d5a28',
              background: '#eef3e4', border: '1px solid #c9d7b2',
              padding: '11px 13px', borderRadius: 10,
            }}>
              Link sent to <strong>{email}</strong>.
            </div>
            <button
              onClick={() => { setSent(false); setError(''); }}
              style={{
                background: 'transparent', border: 'none', cursor: 'pointer',
                color: '#6b6a64', fontSize: 13, padding: 4, textAlign: 'left',
              }}>
              Use a different email
            </button>
          </div>
        )}

        <div style={{
          marginTop: 28, paddingTop: 18, borderTop: '1px solid #ecead0',
          fontSize: 12, color: '#9a9890', lineHeight: 1.5,
        }}>
          Access is limited to the household owner. Only an existing account can sign in.
        </div>
      </div>
    </div>
  );
}

function AuthSplash({ msg }) {
  return (
    <div style={{
      minHeight: '100vh', width: '100vw',
      background: '#f3f1ec',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: "'Geist', system-ui, sans-serif",
      color: '#6b6a64', fontSize: 14,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <span style={{
          width: 18, height: 18, borderRadius: '50%',
          border: '2px solid #d6d3ca', borderTopColor: '#6b8e4e',
          animation: 'hh-spin 0.8s linear infinite',
          display: 'inline-block',
        }}/>
        <span>{msg}</span>
      </div>
    </div>
  );
}

// Sign-out helper used by the Profile screen button.
async function signOutOfHub() {
  try { if (window.SB) await window.SB.auth.signOut(); } catch (e) {}
}

Object.assign(window, { AuthGate, LoginScreen, AuthSplash, signOutOfHub });
