// ═══════════════════════════════════════════════════════════════
//  Google Sign-In — OAuth 2.0 / Google Identity Services
//
//  Production flow:
//    1. Admin sets GOOGLE_CLIENT_ID in Settings (state.branding.googleClientId)
//    2. We load https://accounts.google.com/gsi/client
//    3. Render google.accounts.id.renderButton(...)
//    4. Callback receives a JWT ID token. We decode (no verify here —
//       real verification happens on the backend when it lands).
//    5. Extract email, match against state.users.
//    6. If matched & user.activated → log in.
//       If invitation token exists for this email → activate + log in.
//       Else → show friendly "not authorized" error.
//
//  Demo mode (default):
//    If no GOOGLE_CLIENT_ID configured, we show a demo button that
//    opens a modal listing every demo user's email — the admin picks
//    and we "pretend" that user signed in via Google. The whole thing
//    is clearly labeled demo so no one is fooled.
//
//  To enable real Google Sign-In:
//    1. Create a Client ID at https://console.cloud.google.com/
//       (type: Web application, authorized origins: your domain)
//    2. Paste into Settings → Branding → Google Client ID
//    3. Reload. The real button appears instead of the demo one.
// ═══════════════════════════════════════════════════════════════

const { useState: uSGL, useEffect: uEGL, useRef: uRGL } = React;

// Decode a JWT ID token without verifying signature (verification is
// a backend responsibility). Returns null on malformed input.
window.decodeGoogleJWT = function(jwt) {
  try {
    const [, payload] = jwt.split('.');
    const json = atob(payload.replace(/-/g, '+').replace(/_/g, '/'));
    return JSON.parse(decodeURIComponent(
      json.split('').map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join('')
    ));
  } catch { return null; }
};

// ───────────────────────────────────────────────
//  The main Google sign-in button (real OR demo)
// ───────────────────────────────────────────────
window.GoogleSignInButton = function GoogleSignInButton() {
  const { state, login, activateInvitation } = window.useApp();
  const toast = window.useToast();
  const [demoOpen, setDemoOpen] = uSGL(false);
  const [pendingError, setPendingError] = uSGL(null);
  const realBtnRef = uRGL(null);

  const clientId = state.branding?.googleClientId || '';
  const hasRealOAuth = !!clientId;

  // Handle the result of any Google login (real or demo) uniformly
  const handleGoogleUser = async ({ email, name, picture }) => {
    if (!email) { setPendingError('לא התקבלה כתובת דוא"ל מ-Google'); return; }
    const normalized = email.toLowerCase().trim();
    // Match by email against existing users
    let user = (state.users || []).find(u => (u.email || '').toLowerCase() === normalized);

    // If pending invitation, activate it using Google profile
    if (user && !user.activated && user.inviteToken) {
      try {
        // Auto-generate a long random password (user can change later in My Account)
        const autoPwd = Array.from(crypto.getRandomValues(new Uint8Array(12))).map(b => b.toString(16).padStart(2, '0')).join('');
        await activateInvitation(user.inviteToken, { newPassword: autoPwd, email: normalized, name: name || user.name });
        toast.push({ type: 'success', title: 'ברוך/ה הבא/ה!', message: 'ההזמנה הופעלה אוטומטית דרך Google' });
        login(user.id);
        return;
      } catch (e) {
        setPendingError(e.message || 'שגיאה בהפעלה אוטומטית');
        return;
      }
    }

    if (!user) {
      setPendingError(`הכתובת ${normalized} לא קיימת במערכת. פנה אל הרכז המנהל שיזמין אותך.`);
      return;
    }
    // SECURITY: defense in depth — verify the user is activated and has
    // credentials before logging in, even though OAuth already authenticated
    // them. Prevents logging in as an invited-but-not-activated user.
    if (window.userCanLogin && !window.userCanLogin(user) && !(user.activated === false && user.inviteToken)) {
      setPendingError('חשבון זה אינו מוגדר לכניסה. פנה אל המנהל.');
      return;
    }
    setPendingError(null);
    login(user.id);
    toast.push({ type: 'success', title: 'ברוך/ה הבא/ה', message: `התחברת כ-${user.name}` });
  };

  // Load GSI SDK once + render the real button when configured
  uEGL(() => {
    if (!hasRealOAuth) return;
    let cancelled = false;
    const ready = () => {
      if (cancelled || !window.google?.accounts?.id) return;
      window.google.accounts.id.initialize({
        client_id: clientId,
        callback: (response) => {
          const profile = window.decodeGoogleJWT(response.credential);
          if (!profile) { setPendingError('JWT שגוי'); return; }
          handleGoogleUser({ email: profile.email, name: profile.name, picture: profile.picture });
        },
        auto_select: false,
        context: 'signin'
      });
      if (realBtnRef.current) {
        window.google.accounts.id.renderButton(realBtnRef.current, {
          type: 'standard', theme: 'outline', size: 'large', shape: 'rectangular',
          text: 'signin_with', locale: 'he', width: 360
        });
      }
    };
    if (window.google?.accounts?.id) ready();
    else {
      const script = document.createElement('script');
      script.src = 'https://accounts.google.com/gsi/client';
      script.async = true;
      script.defer = true;
      script.onload = ready;
      document.head.appendChild(script);
    }
    return () => { cancelled = true; };
  }, [hasRealOAuth, clientId]);

  if (hasRealOAuth) {
    return (
      <div className="flex flex-col items-center gap-2">
        <div ref={realBtnRef}/>
        {pendingError && (
          <div className="text-xs text-red-700 bg-red-50 border border-red-200 rounded-lg px-3 py-2 mt-1 max-w-sm text-center">
            {pendingError}
          </div>
        )}
      </div>
    );
  }

  // SECURITY: When no real OAuth is configured, we render NOTHING on the
  // public login page. The previous demo picker allowed anyone opening the
  // site to log in as any user (including admin) without a password — that
  // was only safe in a private dev environment, absolutely not on an
  // internet-facing deployment. Admins can still test the UI by going to
  // Settings → Google OAuth and pasting a real Client ID.
  return null;
};

// ───────────────────────────────────────────────
//  Demo picker modal — lists existing users so the "Google account"
//  can be simulated for demo purposes.
// ───────────────────────────────────────────────
window.GoogleDemoPicker = function GoogleDemoPicker({ onClose, onPick }) {
  const { state } = window.useApp();
  const [q, setQ] = uSGL('');
  const users = (state.users || []).filter(u => u.email && (
    u.name.toLowerCase().includes(q.toLowerCase()) ||
    u.email.toLowerCase().includes(q.toLowerCase())
  ));

  return ReactDOM.createPortal(
    <div className="fixed inset-0 z-[150] bg-slate-900/60 flex items-center justify-center p-4 animate-fade-in" onClick={onClose} role="dialog" aria-modal="true">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md max-h-[80vh] overflow-hidden flex flex-col" onClick={e => e.stopPropagation()}>
        <div className="p-5 border-b border-slate-100">
          <div className="flex items-start justify-between mb-2">
            <div>
              <div className="flex items-center gap-2 mb-1">
                <svg width="18" height="18" viewBox="0 0 48 48">
                  <path fill="#FFC107" d="M43.61 20.08H42V20H24v8h11.3c-1.65 4.66-6.08 8-11.3 8-6.63 0-12-5.37-12-12s5.37-12 12-12c3.06 0 5.84 1.15 7.96 3.04l5.66-5.66C34.05 6.05 29.27 4 24 4 12.96 4 4 12.96 4 24s8.96 20 20 20 20-8.96 20-20c0-1.34-.14-2.65-.39-3.92z"/>
                  <path fill="#FF3D00" d="M6.31 14.69l6.57 4.82C14.66 15.11 18.96 12 24 12c3.06 0 5.84 1.15 7.96 3.04l5.66-5.66C34.05 6.05 29.27 4 24 4 16.32 4 9.66 8.34 6.31 14.69z"/>
                  <path fill="#4CAF50" d="M24 44c5.17 0 9.86-1.98 13.41-5.2l-6.19-5.24C29.2 35.09 26.74 36 24 36c-5.2 0-9.62-3.32-11.28-7.95l-6.52 5.02C9.53 39.56 16.22 44 24 44z"/>
                  <path fill="#1976D2" d="M43.61 20.08H42V20H24v8h11.3c-.79 2.24-2.23 4.16-4.09 5.57l.01-.01 6.19 5.24C37.04 39.09 44 34 44 24c0-1.34-.14-2.65-.39-3.92z"/>
                </svg>
                <h2 className="font-display font-black text-lg">כניסה עם Google</h2>
                <span className="text-[10px] bg-amber-100 text-amber-800 px-1.5 py-0.5 rounded font-bold">DEMO</span>
              </div>
              <p className="text-xs text-slate-500">בחר חשבון Google לדמו. בפרודקשן יופיע כאן popup אמיתי של Google.</p>
            </div>
            <button onClick={onClose} aria-label="סגור" className="w-8 h-8 rounded-lg hover:bg-slate-100 flex items-center justify-center">
              <window.Icon.X size={16}/>
            </button>
          </div>
          <div className="mt-3 relative">
            <window.Icon.Sparkles size={14} className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400"/>
            <input
              type="search"
              value={q}
              onChange={e => setQ(e.target.value)}
              placeholder="חיפוש לפי שם או דוא״ל..."
              className="input pr-9"
              autoFocus
            />
          </div>
        </div>

        <div className="flex-1 overflow-y-auto p-2">
          {users.length === 0 && (
            <div className="py-10 text-center text-sm text-slate-400">
              לא נמצאו משתמשים
            </div>
          )}
          {users.map(u => {
            const auth = u.authorityId ? state.authorities.find(a => a.id === u.authorityId) : null;
            const roleLabel = { local: 'רכז מקומי', national: 'רכז ארצי', admin: 'מנהל מערכת', audit: 'בקרה' }[u.role] || u.role;
            return (
              <button
                key={u.id}
                onClick={() => onPick(u.email)}
                className="w-full flex items-center gap-3 p-3 rounded-lg hover:bg-slate-50 border border-slate-100 mb-1 text-right focus-visible:ring-2 focus-visible:ring-brand-500"
              >
                <window.Avatar name={u.name} size={36}/>
                <div className="flex-1 min-w-0">
                  <div className="font-bold text-sm">{u.name}</div>
                  <div className="text-[11px] text-slate-500 ltr-num" dir="ltr">{u.email}</div>
                </div>
                <div className="text-[10px] text-right shrink-0">
                  <div className="font-bold text-brand-700">{roleLabel}</div>
                  {auth && <div className="text-slate-500 text-[9px]">{auth.name}</div>}
                </div>
              </button>
            );
          })}
        </div>

        <div className="p-3 border-t border-slate-100 text-[10px] text-slate-500 text-center">
          💡 בכניסה אמיתית: לחיצה פותחת popup של Google, המשתמש נותן הרשאה, ואנחנו מקבלים את פרטיו מהדומיין.
        </div>
      </div>
    </div>,
    document.body
  );
};

// ───────────────────────────────────────────────
//  Settings field for Google Client ID — embedded in SettingsPageV2
// ───────────────────────────────────────────────
window.GoogleClientIdField = function GoogleClientIdField() {
  const { state, setState } = window.useApp();
  const toast = window.useToast();
  const current = state.branding?.googleClientId || '';
  const [val, setVal] = uSGL(current);

  const save = () => {
    setState(s => ({ ...s, branding: { ...(s.branding || {}), googleClientId: val.trim() || null } }));
    toast.push({ type: 'success', title: val.trim() ? 'Google OAuth הופעל' : 'Google OAuth כובה', message: val.trim() ? 'לחצן כניסה אמיתי יופיע בעמוד הבית' : 'חוזר למצב demo' });
  };

  return (
    <div className="surface p-5 mt-5">
      <div className="flex items-start gap-3 mb-3">
        <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-blue-500 to-red-500 text-white flex items-center justify-center shrink-0">
          <svg width="18" height="18" viewBox="0 0 48 48">
            <path fill="#fff" d="M24 24v6h11.3c-1.65 4.66-6.08 8-11.3 8-6.63 0-12-5.37-12-12s5.37-12 12-12c3.06 0 5.84 1.15 7.96 3.04l4.24-4.24C32.4 8.55 28.52 7 24 7 14.06 7 6 15.06 6 25s8.06 18 18 18 18-8.06 18-18c0-1.14-.14-2.26-.33-3.34H24v4.34z"/>
          </svg>
        </div>
        <div>
          <h3 className="font-display font-bold text-sm">Google OAuth (כניסה עם Google)</h3>
          <p className="text-xs text-slate-500">הזן Client ID כדי להפעיל כניסה אמיתית מול Google</p>
        </div>
      </div>
      <window.Field label="Google Client ID" help="נוצר בחשבון Google Cloud Console · Web application">
        <input
          value={val}
          onChange={e => setVal(e.target.value)}
          className="input"
          placeholder="1234567890-abc...apps.googleusercontent.com"
          dir="ltr"
        />
      </window.Field>
      <div className="flex items-center justify-between mt-3">
        <div className="text-[10px] text-slate-500">
          {current ? '✓ OAuth אמיתי מופעל' : '⚠ מופעל מצב demo'}
        </div>
        <window.Button variant="primary" size="sm" onClick={save}>שמור</window.Button>
      </div>
      <div className="mt-3 p-3 rounded-lg bg-brand-50 border border-brand-200 text-[11px] text-brand-900 leading-relaxed">
        <strong>איך מגדירים:</strong> <a href="https://console.cloud.google.com/apis/credentials" target="_blank" rel="noopener noreferrer" className="underline">Google Cloud Console</a> → Credentials → Create OAuth Client ID → Web application → Authorized JavaScript origins: הוסף את <code dir="ltr">https://haredim.91-99-172-21.nip.io</code> (או הדומיין הקבוע שלך).
      </div>
    </div>
  );
};
