// THINKLAB · Auth + Permissions (frontend-only via Google Sign-In)
// Setup: replace TLAB_GOOGLE_CLIENT_ID below with your Google OAuth Client ID
// Get one at: https://console.cloud.google.com/apis/credentials

const TLAB_GOOGLE_CLIENT_ID = window.TLAB_GOOGLE_CLIENT_ID || '__REPLACE_ME__.apps.googleusercontent.com';

// Email allowlist — only these emails can read private articles
// Edit this list to grant access. Wildcard pattern *@domain.com supported.
window.TLAB_ALLOWLIST = window.TLAB_ALLOWLIST || [
  'max770104@gmail.com',
  'tzuyiarch@gmail.com',
  // Add more emails or domains here, e.g. '*@thinklab.studio'
];

// Decode a JWT (does NOT verify signature — frontend-only trust model)
function decodeJWT(token) {
  try {
    const parts = token.split('.');
    if (parts.length !== 3) return null;
    const payload = JSON.parse(atob(parts[1].replace(/-/g, '+').replace(/_/g, '/')));
    return payload;
  } catch (e) {
    return null;
  }
}

// Check if email matches the allowlist (supports *@domain.com wildcards)
function isEmailAllowed(email) {
  if (!email) return false;
  const list = window.TLAB_ALLOWLIST || [];
  return list.some(rule => {
    if (rule.startsWith('*@')) {
      return email.toLowerCase().endsWith(rule.slice(1).toLowerCase());
    }
    return rule.toLowerCase() === email.toLowerCase();
  });
}

// Auth state hook — provides { user, signIn, signOut, isAllowed }
function useAuth() {
  const { useState, useEffect } = React;
  const [user, setUser] = useState(() => {
    try {
      const cached = localStorage.getItem('tlab_auth');
      if (!cached) return null;
      const parsed = JSON.parse(cached);
      // Check expiry (Google JWTs have 'exp' in seconds since epoch)
      if (parsed.exp && parsed.exp * 1000 < Date.now()) {
        localStorage.removeItem('tlab_auth');
        return null;
      }
      return parsed;
    } catch (e) {
      return null;
    }
  });

  const signIn = (token) => {
    const payload = decodeJWT(token);
    if (!payload || !payload.email) return false;
    const u = {
      email: payload.email,
      name: payload.name || payload.email,
      picture: payload.picture || null,
      exp: payload.exp,
    };
    localStorage.setItem('tlab_auth', JSON.stringify(u));
    setUser(u);
    return true;
  };

  const signOut = () => {
    localStorage.removeItem('tlab_auth');
    setUser(null);
    if (window.google?.accounts?.id?.disableAutoSelect) {
      window.google.accounts.id.disableAutoSelect();
    }
  };

  return {
    user,
    signIn,
    signOut,
    isAllowed: user ? isEmailAllowed(user.email) : false,
  };
}

// Google Sign-In button — initialises GSI when mounted
function GoogleSignInButton({ onSuccess }) {
  const { useEffect, useRef } = React;
  const ref = useRef(null);

  useEffect(() => {
    const init = () => {
      if (!window.google?.accounts?.id) {
        setTimeout(init, 200);
        return;
      }
      try {
        window.google.accounts.id.initialize({
          client_id: TLAB_GOOGLE_CLIENT_ID,
          callback: (resp) => {
            if (resp.credential) onSuccess(resp.credential);
          },
          auto_select: false,
        });
        if (ref.current) {
          window.google.accounts.id.renderButton(ref.current, {
            theme: 'outline',
            size: 'large',
            type: 'standard',
            text: 'signin_with',
            shape: 'rectangular',
            logo_alignment: 'left',
            width: 280,
          });
        }
      } catch (e) {
        console.error('GSI init failed:', e);
      }
    };
    init();
  }, [onSuccess]);

  if (TLAB_GOOGLE_CLIENT_ID.startsWith('__REPLACE_ME__')) {
    return (
      <div style={{padding:24, border:'1px dashed var(--tl-line)', background:'var(--tl-bone)', fontSize:13, lineHeight:1.6}}>
        <b>⚙ Setup required</b><br/>
        Set <code>TLAB_GOOGLE_CLIENT_ID</code> in <code>auth.jsx</code> with your Google OAuth Client ID.<br/>
        <a href="https://console.cloud.google.com/apis/credentials" target="_blank" style={{color:'var(--tl-accent)', textDecoration:'underline'}}>Get one here →</a>
      </div>
    );
  }
  return <div ref={ref}></div>;
}

// Login gate — shown when user tries to view a private article
function LoginGate({ articleTitle }) {
  const { user, signIn, isAllowed, signOut } = useAuth();

  if (user && isAllowed) {
    // Should not reach here normally; parent should have unlocked
    return null;
  }

  return (
    <section style={{
      maxWidth: 560,
      margin: '128px auto',
      padding: '64px 48px',
      border: '1px solid var(--tl-line)',
      background: 'var(--tl-bone)',
      textAlign: 'center'
    }}>
      <div style={{fontFamily:'var(--tl-font-mono)', fontSize:11, letterSpacing:'.22em', textTransform:'uppercase', color:'var(--tl-stone)', marginBottom:16}}>
        🔒 § PRIVATE RESEARCH
      </div>
      <h2 style={{fontSize:32, fontWeight:300, marginBottom:8, letterSpacing:'-.015em'}}>
        Authentication required
      </h2>
      <h2 className="cjk" style={{fontSize:18, fontWeight:300, color:'var(--tl-stone)', marginBottom:32}}>
        此研究內容受權限保護
      </h2>
      <p style={{fontSize:15, lineHeight:1.7, color:'var(--tl-graphite)', marginBottom:32, maxWidth:'40ch', margin:'0 auto 32px'}}>
        {articleTitle ? <>To read <b>{articleTitle}</b>, please sign in.</> : 'To read this article, please sign in.'}<br/>
        <span className="cjk" style={{fontSize:14, color:'var(--tl-stone)'}}>請登入以閱讀此研究內容。</span>
      </p>

      {!user ? (
        <div style={{display:'flex', justifyContent:'center'}}>
          <GoogleSignInButton onSuccess={(token) => signIn(token)} />
        </div>
      ) : (
        <div>
          <p style={{fontSize:13, color:'var(--tl-graphite)', marginBottom:16}}>
            Signed in as <b>{user.email}</b><br/>
            <span style={{color:'var(--tl-stone)'}}>This account does not have access to private research.</span>
          </p>
          <button
            onClick={signOut}
            style={{padding:'8px 16px', border:'1px solid var(--tl-line)', background:'var(--tl-paper)', fontFamily:'var(--tl-font-mono)', fontSize:11, letterSpacing:'.18em', textTransform:'uppercase', cursor:'pointer'}}>
            Sign out
          </button>
        </div>
      )}

      <div style={{marginTop:48, paddingTop:24, borderTop:'1px solid var(--tl-line)', fontFamily:'var(--tl-font-mono)', fontSize:10, letterSpacing:'.12em', color:'var(--tl-stone)', textTransform:'uppercase'}}>
        Access requests · LK@tlabarc.com
      </div>
    </section>
  );
}

// Compact auth status badge for the topbar (optional)
function AuthBadge() {
  const { user, signOut, isAllowed } = useAuth();
  if (!user) return null;
  return (
    <span
      title={`${user.email}${isAllowed ? ' · authorized' : ''}`}
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: 8,
        padding: '4px 10px',
        border: '1px solid currentColor',
        opacity: 0.55,
        fontFamily: 'var(--tl-font-mono)',
        fontSize: 10,
        letterSpacing: '.12em',
        textTransform: 'uppercase',
        cursor: 'pointer',
      }}
      onClick={signOut}>
      {isAllowed ? '🔓' : '🔒'} {user.email.split('@')[0].slice(0, 12)}
    </span>
  );
}

Object.assign(window, { useAuth, GoogleSignInButton, LoginGate, AuthBadge, isEmailAllowed });
