// auth.jsx — Google SSO + Session + Role management (YBP APP)

const YBP_USERS = [
  { id: 'u1', name: 'יובל בן פורת',    email: 'yuval@ybprojects.com',  role: 'admin', avatar: 'יב', projects: '*' },
  { id: 'u2', name: 'Nathan Warshavsky', email: 'nathan@ybprojects.com', role: 'admin', avatar: 'נו', projects: '*' },
  { id: 'u3', name: 'ברק',              email: 'barak@ybprojects.com',  role: 'admin', avatar: 'בר', projects: '*' },
];

const ROLE_LABELS = { admin: 'מנהל ראשי', pm: 'מנהל פרויקט', viewer: 'צופה' };
const ROLE_COLORS = { admin: '#1a2c4a', pm: '#0369a1', viewer: '#6b7280' };

const AUTH_KEY = 'ybp_auth_session';
const USER_ROLES_KEY = 'ybp_user_roles';
const KNOWN_USERS_KEY = 'ybp_known_users';
const SUPER_ADMIN = 'yuval@ybprojects.com';

function getUserRole(email) {
  if (email === SUPER_ADMIN) return 'admin';
  try {
    const roles = JSON.parse(localStorage.getItem(USER_ROLES_KEY) || '{}');
    if (roles[email]) return roles[email];
  } catch {}
  const defaultUser = YBP_USERS.find(u => u.email === email);
  return defaultUser?.role || 'pm';
}

function setUserRole(email, role) {
  if (email === SUPER_ADMIN) return;
  try {
    const roles = JSON.parse(localStorage.getItem(USER_ROLES_KEY) || '{}');
    roles[email] = role;
    localStorage.setItem(USER_ROLES_KEY, JSON.stringify(roles));
    appendAuditEvent({ action: 'edit', actor: getSession()?.name || 'Admin', detail: `עדכון הרשאה: ${email} → ${ROLE_LABELS[role] || role}` });
  } catch {}
}

function registerKnownUser(user) {
  try {
    const users = JSON.parse(localStorage.getItem(KNOWN_USERS_KEY) || '[]');
    const idx = users.findIndex(u => u.email === user.email);
    const entry = { email: user.email, name: user.name, avatar: user.avatar, lastLogin: new Date().toISOString() };
    if (idx >= 0) users[idx] = entry;
    else users.push(entry);
    localStorage.setItem(KNOWN_USERS_KEY, JSON.stringify(users));
  } catch {}
}

function getKnownUsers() {
  try { return JSON.parse(localStorage.getItem(KNOWN_USERS_KEY) || '[]'); }
  catch { return []; }
}

function getSession() {
  try {
    const s = localStorage.getItem(AUTH_KEY);
    if (!s) return null;
    const session = JSON.parse(s);
    if (session.expiresAt && Date.now() > session.expiresAt) {
      localStorage.removeItem(AUTH_KEY);
      return null;
    }
    return session;
  } catch { return null; }
}

function setSession(user) {
  const session = {
    ...user,
    loggedInAt: Date.now(),
    expiresAt: Date.now() + 8 * 60 * 60 * 1000, // 8 שעות
  };
  localStorage.setItem(AUTH_KEY, JSON.stringify(session));
  // Audit
  appendAuditEvent({ action: 'login', actor: user.name, detail: `כניסה מוצלחת (${user.email})` });
  return session;
}

function clearSession() {
  const s = getSession();
  if (s) appendAuditEvent({ action: 'logout', actor: s.name, detail: 'יציאה מהמערכת' });
  localStorage.removeItem(AUTH_KEY);
}

// ── Audit Log ──────────────────────────────────────────────────────────────
const AUDIT_KEY = 'ybp_audit_log';

function getAuditLog() {
  try { return JSON.parse(localStorage.getItem(AUDIT_KEY) || '[]'); } catch { return []; }
}

function appendAuditEvent(ev) {
  const log = getAuditLog();
  log.unshift({
    id: `audit-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,
    ts: new Date().toISOString(),
    ...ev,
  });
  localStorage.setItem(AUDIT_KEY, JSON.stringify(log.slice(0, 200)));
}

window.YBP_AUTH = { getSession, setSession, clearSession, appendAuditEvent, getAuditLog, YBP_USERS, ROLE_LABELS, ROLE_COLORS, getUserRole, setUserRole, registerKnownUser, getKnownUsers };

// ── Supabase Auth helpers ─────────────────────────────────────────────────

// יצירת רשומת profiles אוטומטית בכניסה ראשונה (auth.users נוצר ע"י Google SSO — profiles לא)
async function ensureProfile(sb, u) {
  try {
    const { data: existing } = await sb.from('profiles').select('id').eq('id', u.id).maybeSingle();
    if (existing) return;
    const fullName = u.user_metadata?.full_name || u.user_metadata?.name || u.email;
    const { error } = await sb.from('profiles').upsert({
      id:        u.id,
      email:     u.email,
      full_name: fullName,
      role:      'pm',
      pm_name:   fullName,
    }, { onConflict: 'id' });
    if (error) console.warn('[YBP Auth] ensureProfile upsert failed:', error.message);
    else console.log('[YBP Auth] profile created for', u.email);
  } catch (e) {
    console.warn('[YBP Auth] ensureProfile failed:', e.message);
  }
}

async function checkSupabaseSession(onLogin) {
  if (!window.YBP_SUPABASE) return null;
  try {
    const sb = await window.YBP_SUPABASE.getClient();
    const { data: { session } } = await sb.auth.getSession();
    if (!session?.user) return null;
    const u = session.user;
    if (!u.email?.endsWith('@ybprojects.com')) return null;
    await ensureProfile(sb, u);   // יצירת רשומת profiles בכניסה ראשונה
    const role = getUserRole(u.email);
    let name = u.user_metadata?.full_name || u.email;
    // v79 — עדיפות לשם מ-profiles ב-Supabase (מקור אמת, תואם Drive) על פני Google metadata
    try {
      const { data: prof } = await sb.from('profiles').select('full_name').eq('id', u.id).maybeSingle();
      if (prof?.full_name) name = prof.full_name;
    } catch {}
    try {
      const locked = JSON.parse(localStorage.getItem('ybp_name_locked') || 'null');
      if (locked && locked.userId === u.id && locked.name) name = locked.name;
    } catch {}
    const user = {
      id:          u.id,
      name,
      email:       u.email,
      avatar:      name.split(' ').filter(Boolean).map(n => n[0]).join('').slice(0, 2).toUpperCase(),
      picture:     u.user_metadata?.avatar_url || null,
      role,
      projects:    '*',
      supabaseId:  u.id,
    };
    window.YBP_USER = { id: u.id, email: u.email, name };
    registerKnownUser(user);
    if (window.syncReportsFromSupabase) window.syncReportsFromSupabase().catch(() => {});
    if (window.syncTasksFromSupabase)   window.syncTasksFromSupabase().catch(() => {});
    if (onLogin) onLogin(setSession(user));
    return user;
  } catch (e) {
    console.warn('[YBP Auth] Supabase session check failed:', e.message);
    return null;
  }
}

async function loginWithSupabase() {
  if (!window.YBP_SUPABASE) return;
  try {
    const sb = await window.YBP_SUPABASE.getClient();
    const { error } = await sb.auth.signInWithOAuth({
      provider: 'google',
      options:  { redirectTo: window.location.origin },
    });
    if (error) throw error;
  } catch (e) {
    console.error('[YBP Auth] Supabase login failed:', e.message);
    throw e;
  }
}

async function logoutSupabase() {
  if (!window.YBP_SUPABASE) return;
  try {
    const sb = await window.YBP_SUPABASE.getClient();
    await sb.auth.signOut();
  } catch (e) {
    console.warn('[YBP Auth] Supabase signOut failed:', e.message);
  }
}

window.YBP_AUTH.checkSupabaseSession = checkSupabaseSession;
window.YBP_AUTH.loginWithSupabase    = loginWithSupabase;
window.YBP_AUTH.logoutSupabase       = logoutSupabase;

// ── Google OAuth helpers ──────────────────────────────────────────────────
const DEFAULT_GOOGLE_CLIENT_ID = '40648614185-quk0dilq1difn209jdrrfqi2nq5lif2k.apps.googleusercontent.com';

function getGoogleClientId() {
  try {
    const s = JSON.parse(localStorage.getItem('ybp_settings') || '{}');
    return s.googleClientId || DEFAULT_GOOGLE_CLIENT_ID;
  } catch { return DEFAULT_GOOGLE_CLIENT_ID; }
}

// ── Google SSO Login Screen ────────────────────────────────────────────────
function GoogleSSOLogin({ onLogin }) {
  const [step, setStep] = React.useState('idle');
  // idle | loading | success | no-client-id | wrong-domain | error
  // client-entry | contractor-entry | client-success | contractor-success
  const [selectedUser, setSelectedUser] = React.useState(null);
  const [accessLink, setAccessLink] = React.useState('');
  const [linkError, setLinkError] = React.useState('');
  const [lang, setLang] = React.useState('he'); // he | en

  // On mount: check if returning from Supabase OAuth redirect
  React.useEffect(() => {
    checkSupabaseSession(onLogin).then(user => {
      if (user) { setSelectedUser(user); setStep('success'); }
    });
  }, []);

  const T = {
    he: {
      tagline: 'ניהול פרויקטים בבנייה',
      title: 'כניסה למערכת',
      subtitle: 'הכניסה מוגבלת לחשבונות @ybprojects.com',
      googleBtn: 'המשך עם Google',
      clientBtn: 'כניסת לקוח',
      contractorBtn: 'כניסת קבלן',
      securityNote: 'Google OAuth 2.0 · HTTPS בלבד · session 8 שעות',
      pickAccount: 'בחר חשבון',
      demoNote: 'הדגמה בלבד — בייצור יפנה ל-Google',
      back: 'חזרה',
      welcome: (name) => `ברוך הבא, ${name}!`,
      preparing: 'מכין את הסביבה שלך...',
      clientTitle: 'כניסת לקוח',
      clientSubtitle: 'הדבק את הלינק שקיבלת ממנהל הפרויקט',
      contractorTitle: 'כניסת קבלן',
      contractorSubtitle: 'הדבק את הלינק שקיבלת ממנהל הפרויקט',
      linkPlaceholder: 'הדבק לינק כאן...',
      enterBtn: 'כניסה',
      linkError: 'לינק לא תקין — פנה למנהל הפרויקט',
      demoLink: 'לצורך הדגמה: הזן כל טקסט ולחץ כניסה',
      clientWelcome: 'ברוך הבא, לקוח!',
      contractorWelcome: 'ברוך הבא, קבלן!',
      loadingClient: 'פותח את פורטל הלקוח...',
      loadingContractor: 'פותח את לוח הקבלן...',
      footer: '© 2026 YBPROJECTS · כל הזכויות שמורות',
    },
    en: {
      tagline: 'Construction Project Management',
      title: 'Sign In',
      subtitle: 'Access restricted to @ybprojects.com accounts',
      googleBtn: 'Continue with Google',
      clientBtn: 'Client Access',
      contractorBtn: 'Contractor Access',
      securityNote: 'Google OAuth 2.0 · HTTPS only · 8h session',
      pickAccount: 'Choose account',
      demoNote: 'Demo only — production redirects to Google',
      back: 'Back',
      welcome: (name) => `Welcome, ${name}!`,
      preparing: 'Preparing your workspace...',
      clientTitle: 'Client Access',
      clientSubtitle: 'Paste the link sent to you by your project manager',
      contractorTitle: 'Contractor Access',
      contractorSubtitle: 'Paste the link sent to you by your project manager',
      linkPlaceholder: 'Paste link here...',
      enterBtn: 'Enter',
      linkError: 'Invalid link — contact your project manager',
      demoLink: 'For demo: enter any text and click Enter',
      clientWelcome: 'Welcome, Client!',
      contractorWelcome: 'Welcome, Contractor!',
      loadingClient: 'Opening client portal...',
      loadingContractor: 'Opening contractor board...',
      footer: '© 2026 YBPROJECTS · All rights reserved',
    },
  };
  const t = T[lang];

  const handleGoogleClick = () => {
    // Primary: Supabase OAuth redirect (Phase 1B+)
    if (window.YBP_SUPABASE) {
      setStep('loading');
      loginWithSupabase().catch(() => {
        // Fallback to GSI popup if Supabase redirect fails
        setStep('idle');
        _handleGoogleGSI();
      });
      return;
    }
    _handleGoogleGSI();
  };

  const _handleGoogleGSI = () => {
    const clientId = getGoogleClientId();
    if (!clientId) { setStep('no-client-id'); return; }
    if (!window.google?.accounts?.oauth2) { setStep('gis-not-loaded'); return; }

    setStep('loading');

    const tokenClient = window.google.accounts.oauth2.initTokenClient({
      client_id: clientId,
      scope: 'openid email profile',
      callback: async (tokenResp) => {
        if (tokenResp.error) { setStep('error'); setTimeout(() => setStep('idle'), 3000); return; }
        try {
          const resp = await fetch(`https://www.googleapis.com/oauth2/v3/userinfo?access_token=${tokenResp.access_token}`);
          const info = await resp.json();
          if (!info.email?.endsWith('@ybprojects.com')) {
            setStep('wrong-domain'); setTimeout(() => setStep('idle'), 4000); return;
          }
          const role = getUserRole(info.email);
          const existingProfile = (() => { try { return JSON.parse(localStorage.getItem('ybp_settings') || '{}').profile || {}; } catch(_) { return {}; } })();
          const finalName = (existingProfile.nameLocked && existingProfile.name) ? existingProfile.name : info.name;
          const user = {
            id: info.sub,
            name: finalName,
            email: info.email,
            avatar: (info.name || '').split(' ').filter(Boolean).map(n => n[0]).join('').slice(0, 2).toUpperCase(),
            picture: info.picture || null,
            role,
            projects: '*',
          };
          registerKnownUser(user);
          setSelectedUser(user);
          setStep('success');
          setTimeout(() => onLogin(setSession(user)), 1200);
        } catch(e) {
          console.error('[YBP Auth]', e);
          setStep('error'); setTimeout(() => setStep('idle'), 3000);
        }
      },
    });
    tokenClient.requestAccessToken({ prompt: 'select_account' });
  };

  // v3.9.0.45 — אימות אמיתי של לינק שהודבק: לקוח לפי ?p, קבלן לפי ?t (verifyAccessToken).
  const handleAccessLink = async (role) => {
    if (!accessLink.trim()) { setLinkError(t.linkError); return; }
    setLinkError('');

    // נתח כ-URL; fall-back: טקסט גולמי = projectId (לקוח) או token (קבלן)
    let token = '', projectId = '';
    try {
      const u = new URL(accessLink.trim(), window.location.origin);
      token = u.searchParams.get('t') || '';
      projectId = u.searchParams.get('p') || '';
    } catch {
      if (role === 'client') projectId = accessLink.trim();
      else token = accessLink.trim();
    }

    if (role === 'client') {
      if (!projectId) { setLinkError(t.linkError); return; }
      const session = setSession({ id:'link-client', name:'לקוח', email:'', role:'client',
        projectId, avatar:'לק' });
      setStep('client-success');
      setTimeout(() => onLogin(session), 1000);
    } else {
      if (!token) { setLinkError(t.linkError); return; }
      const v = (window.YBP_AUTH && window.YBP_AUTH.verifyAccessToken)
        ? await window.YBP_AUTH.verifyAccessToken(token)
        : { valid:false, reason:'no-verifier' };
      if (!v.valid) { setLinkError(t.linkError); return; }
      const session = setSession({ id:'link-contractor', name: v.sub || 'קבלן', email:'',
        role:'contractor', projectId: v.pid, avatar:'קב' });
      setStep('contractor-success');
      setTimeout(() => onLogin(session), 1000);
    }
  };

  // ── background ───────────────────────────────────────────────────────────
  const bgStyle = {
    minHeight: '100vh',
    background: 'linear-gradient(160deg, #0b1628 0%, #1a2c4a 55%, #1e3460 100%)',
    display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
    fontFamily: 'Assistant, sans-serif', direction: lang === 'he' ? 'rtl' : 'ltr',
    position: 'relative', overflow: 'hidden',
  };

  const cardStyle = {
    background: '#fff', borderRadius: 18, padding: '36px 32px',
    width: 380, maxWidth: '92vw',
    boxShadow: '0 32px 80px rgba(0,0,0,0.45)',
    position: 'relative', zIndex: 1,
  };

  return (
    <div style={bgStyle}>

      {/* Decorative circles */}
      <div style={{
        position: 'absolute', width: 500, height: 500, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(181,168,130,0.08) 0%, transparent 70%)',
        top: -150, right: -150, pointerEvents: 'none',
      }} />
      <div style={{
        position: 'absolute', width: 400, height: 400, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(29,78,216,0.07) 0%, transparent 70%)',
        bottom: -100, left: -100, pointerEvents: 'none',
      }} />

      {/* Lang toggle */}
      <div style={{ position: 'absolute', top: 16, left: 16, zIndex: 2 }}>
        <button onClick={() => setLang(l => l === 'he' ? 'en' : 'he')} style={{
          background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.2)',
          color: '#fff', padding: '5px 12px', borderRadius: 6,
          fontSize: 12, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
          letterSpacing: 0.5,
        }}>
          {lang === 'he' ? 'EN' : 'עב'}
        </button>
      </div>

      {/* Logo + tagline */}
      <div style={{ textAlign: 'center', marginBottom: 32, zIndex: 1 }}>
        <img src="assets/ybp-logo-new.png" alt="YBP APP"
          style={{ height: 76, objectFit: 'contain', marginBottom: 14 }} />
        <div style={{
          color: '#b5a882', fontSize: 12, letterSpacing: 2.5,
          fontWeight: 700, textTransform: 'uppercase',
        }}>{t.tagline}</div>
      </div>

      {/* Card */}
      <div style={cardStyle}>

        {/* ── IDLE ── */}
        {step === 'idle' && (
          <>
            <h2 style={{ margin: '0 0 4px', fontSize: 22, fontWeight: 800, color: '#111827', textAlign: 'center' }}>
              {t.title}
            </h2>
            <p style={{ margin: '0 0 26px', fontSize: 12.5, color: '#6b7280', textAlign: 'center', lineHeight: 1.5 }}>
              {t.subtitle}
            </p>

            {/* Google button */}
            <button onClick={handleGoogleClick} style={{
              width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
              padding: '13px 20px', borderRadius: 10, border: '1.5px solid #e5e7eb', background: '#fff',
              cursor: 'pointer', fontSize: 15, fontWeight: 700, color: '#111827', fontFamily: 'inherit',
              boxShadow: '0 2px 8px rgba(0,0,0,0.06)', transition: 'all 0.15s', marginBottom: 16,
            }}
              onMouseEnter={e => { e.currentTarget.style.boxShadow = '0 4px 16px rgba(0,0,0,0.14)'; e.currentTarget.style.borderColor = '#d1d5db'; }}
              onMouseLeave={e => { e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.06)'; e.currentTarget.style.borderColor = '#e5e7eb'; }}
            >
              <GoogleIcon size={20} />
              {t.googleBtn}
            </button>

            {/* Divider */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '4px 0 16px' }}>
              <div style={{ flex: 1, height: 1, background: '#f3f4f6' }} />
              <span style={{ fontSize: 11, color: '#9ca3af', fontWeight: 600 }}>
                {lang === 'he' ? 'או' : 'or'}
              </span>
              <div style={{ flex: 1, height: 1, background: '#f3f4f6' }} />
            </div>

            {/* Client + Contractor buttons */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 20 }}>
              <button onClick={() => { setStep('client-entry'); setAccessLink(''); setLinkError(''); }} style={{
                padding: '11px 10px', borderRadius: 10,
                border: '1.5px solid #e5e7eb', background: '#fafbfc',
                cursor: 'pointer', fontFamily: 'inherit',
                fontSize: 13, fontWeight: 700, color: '#374151',
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5,
                transition: 'all 0.15s',
              }}
                onMouseEnter={e => { e.currentTarget.style.borderColor = '#1a2c4a'; e.currentTarget.style.background = '#eff6ff'; }}
                onMouseLeave={e => { e.currentTarget.style.borderColor = '#e5e7eb'; e.currentTarget.style.background = '#fafbfc'; }}
              >
                <span style={{ fontSize: 22 }}>🏢</span>
                <span>{t.clientBtn}</span>
              </button>
              <button onClick={() => { setStep('contractor-entry'); setAccessLink(''); setLinkError(''); }} style={{
                padding: '11px 10px', borderRadius: 10,
                border: '1.5px solid #e5e7eb', background: '#fafbfc',
                cursor: 'pointer', fontFamily: 'inherit',
                fontSize: 13, fontWeight: 700, color: '#374151',
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5,
                transition: 'all 0.15s',
              }}
                onMouseEnter={e => { e.currentTarget.style.borderColor = '#1a2c4a'; e.currentTarget.style.background = '#eff6ff'; }}
                onMouseLeave={e => { e.currentTarget.style.borderColor = '#e5e7eb'; e.currentTarget.style.background = '#fafbfc'; }}
              >
                <span style={{ fontSize: 22 }}>🦺</span>
                <span>{t.contractorBtn}</span>
              </button>
            </div>

            {/* Security note */}
            <div style={{ padding: '10px 12px', background: '#f0f9ff', borderRadius: 8, border: '1px solid #bae6fd' }}>
              <div style={{ fontSize: 11, color: '#0369a1', display: 'flex', gap: 6, alignItems: 'center' }}>
                <span>🔒</span>
                <span>{t.securityNote}</span>
              </div>
            </div>

            {/* PWA install tip */}
            <div style={{ padding: '9px 12px', background: '#f0fdf4', borderRadius: 8, border: '1px solid #bbf7d0', textAlign: 'center' }}>
              <div style={{ fontSize: 11, color: '#16a34a', lineHeight: 1.5 }}>
                📲 להתקנה כאפליקציה: Chrome תפריט <strong>⋮</strong> ← <strong>הוסף למסך הבית</strong>
              </div>
            </div>
          </>
        )}


        {/* ── LOADING ── */}
        {step === 'loading' && (
          <div style={{ textAlign: 'center', padding: '24px 0' }}>
            <div style={{ width: 44, height: 44, border: '3px solid #e5e7eb', borderTopColor: '#1a2c4a', borderRadius: '50%', animation: 'ybpSpin 0.8s linear infinite', margin: '0 auto 16px' }} />
            <div style={{ fontSize: 15, fontWeight: 700, color: '#111827' }}>מתחבר ל-Google...</div>
            <style>{`@keyframes ybpSpin { to { transform: rotate(360deg); } }`}</style>
          </div>
        )}

        {/* ── NO CLIENT ID ── */}
        {(step === 'no-client-id' || step === 'gis-not-loaded') && (
          <div style={{ textAlign: 'center', padding: '16px 0' }}>
            <div style={{ fontSize: 40, marginBottom: 12 }}>⚙️</div>
            <div style={{ fontSize: 15, fontWeight: 700, color: '#111827', marginBottom: 8 }}>Google OAuth לא מוגדר</div>
            <div style={{ fontSize: 12, color: '#6b7280', marginBottom: 16, lineHeight: 1.6 }}>
              {step === 'no-client-id'
                ? 'יש להגדיר Google Client ID בהגדרות האפליקציה → Google OAuth'
                : 'ספריית Google לא נטענה — רענן את הדף ונסה שוב'}
            </div>
            <button onClick={() => setStep('idle')} style={{ padding: '8px 20px', borderRadius: 8, border: '1px solid #e5e7eb', background: '#f9fafb', cursor: 'pointer', fontSize: 13, fontWeight: 600, fontFamily: 'inherit' }}>
              חזרה
            </button>
          </div>
        )}

        {/* ── WRONG DOMAIN ── */}
        {step === 'wrong-domain' && (
          <div style={{ textAlign: 'center', padding: '16px 0' }}>
            <div style={{ fontSize: 40, marginBottom: 12 }}>🚫</div>
            <div style={{ fontSize: 15, fontWeight: 700, color: '#dc2626', marginBottom: 8 }}>חשבון לא מורשה</div>
            <div style={{ fontSize: 12, color: '#6b7280', lineHeight: 1.6 }}>הגישה מוגבלת לחשבונות @ybprojects.com בלבד</div>
          </div>
        )}

        {/* ── ERROR ── */}
        {step === 'error' && (
          <div style={{ textAlign: 'center', padding: '16px 0' }}>
            <div style={{ fontSize: 40, marginBottom: 12 }}>⚠️</div>
            <div style={{ fontSize: 15, fontWeight: 700, color: '#dc2626', marginBottom: 8 }}>אירעה שגיאה</div>
            <div style={{ fontSize: 12, color: '#6b7280' }}>נסה שוב או פנה למנהל המערכת</div>
          </div>
        )}

        {/* ── CLIENT / CONTRACTOR ENTRY ── */}
        {(step === 'client-entry' || step === 'contractor-entry') && (() => {
          const isClient = step === 'client-entry';
          return (
            <>
              <div style={{ textAlign: 'center', marginBottom: 22 }}>
                <div style={{ fontSize: 28, marginBottom: 8 }}>{isClient ? '🏢' : '🦺'}</div>
                <div style={{ fontSize: 19, fontWeight: 800, color: '#111827', marginBottom: 4 }}>
                  {isClient ? t.clientTitle : t.contractorTitle}
                </div>
                <div style={{ fontSize: 12.5, color: '#6b7280', lineHeight: 1.5 }}>
                  {isClient ? t.clientSubtitle : t.contractorSubtitle}
                </div>
              </div>

              <div style={{ marginBottom: 12 }}>
                <input
                  value={accessLink}
                  onChange={e => { setAccessLink(e.target.value); setLinkError(''); }}
                  onKeyDown={e => e.key === 'Enter' && handleAccessLink(isClient ? 'client' : 'contractor')}
                  placeholder={t.linkPlaceholder}
                  dir="ltr"
                  style={{
                    width: '100%', padding: '11px 14px', borderRadius: 9, boxSizing: 'border-box',
                    border: `1.5px solid ${linkError ? '#ef4444' : '#e5e7eb'}`,
                    fontSize: 13, fontFamily: 'monospace', outline: 'none',
                    color: '#374151', background: '#fafbfc',
                  }}
                />
                {linkError && (
                  <div style={{ fontSize: 11, color: '#ef4444', marginTop: 5 }}>{linkError}</div>
                )}
                <div style={{ fontSize: 11, color: '#9ca3af', marginTop: 5 }}>{t.demoLink}</div>
              </div>

              <button onClick={() => handleAccessLink(isClient ? 'client' : 'contractor')} style={{
                width: '100%', padding: '12px', borderRadius: 9,
                background: '#1a2c4a', color: '#fff', border: 'none',
                fontSize: 15, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
                marginBottom: 12,
              }}>
                {t.enterBtn}
              </button>

              <button onClick={() => setStep('idle')} style={{
                width: '100%', background: 'none', border: 'none',
                color: '#9ca3af', fontSize: 12, cursor: 'pointer', fontFamily: 'inherit',
              }}>{t.back}</button>
            </>
          );
        })()}

        {/* ── SUCCESS (PM) ── */}
        {step === 'success' && selectedUser && (
          <div style={{ textAlign: 'center', padding: '16px 0' }}>
            <div style={{ fontSize: 44, marginBottom: 10 }}>✅</div>
            <div style={{ fontSize: 17, fontWeight: 800, color: '#111827', marginBottom: 4 }}>
              {t.welcome(selectedUser.name.split(' ')[0])}
            </div>
            <div style={{ fontSize: 12, color: '#6b7280', marginBottom: 20 }}>{t.preparing}</div>
            <div style={{ height: 4, background: '#f3f4f6', borderRadius: 2, overflow: 'hidden' }}>
              <div style={{ height: '100%', background: '#1a2c4a', borderRadius: 2, animation: 'ybpProgress 1.1s linear forwards' }} />
            </div>
            <style>{`@keyframes ybpProgress { from { width: 0% } to { width: 100% } }`}</style>
          </div>
        )}

        {/* ── SUCCESS (CLIENT) ── */}
        {step === 'client-success' && (
          <div style={{ textAlign: 'center', padding: '16px 0' }}>
            <div style={{ fontSize: 44, marginBottom: 10 }}>🏢</div>
            <div style={{ fontSize: 17, fontWeight: 800, color: '#111827', marginBottom: 4 }}>{t.clientWelcome}</div>
            <div style={{ fontSize: 12, color: '#6b7280', marginBottom: 20 }}>{t.loadingClient}</div>
            <div style={{ height: 4, background: '#f3f4f6', borderRadius: 2, overflow: 'hidden' }}>
              <div style={{ height: '100%', background: '#b5a882', borderRadius: 2, animation: 'ybpProgress 1.3s linear forwards' }} />
            </div>
          </div>
        )}

        {/* ── SUCCESS (CONTRACTOR) ── */}
        {step === 'contractor-success' && (
          <div style={{ textAlign: 'center', padding: '16px 0' }}>
            <div style={{ fontSize: 44, marginBottom: 10 }}>🦺</div>
            <div style={{ fontSize: 17, fontWeight: 800, color: '#111827', marginBottom: 4 }}>{t.contractorWelcome}</div>
            <div style={{ fontSize: 12, color: '#6b7280', marginBottom: 20 }}>{t.loadingContractor}</div>
            <div style={{ height: 4, background: '#f3f4f6', borderRadius: 2, overflow: 'hidden' }}>
              <div style={{ height: '100%', background: '#1a2c4a', borderRadius: 2, animation: 'ybpProgress 1.3s linear forwards' }} />
            </div>
          </div>
        )}

      </div>

      <div style={{ marginTop: 24, fontSize: 11, color: 'rgba(255,255,255,0.25)', zIndex: 1 }}>
        {t.footer}
      </div>
    </div>
  );
}

function GoogleIcon({ size = 20 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24">
      <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
      <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
      <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/>
      <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
    </svg>
  );
}

// ── Session Bar (top of app) ──────────────────────────────────────────────
function SessionBar({ session, onLogout, onOpenAudit, onOpenCRM, onOpenTenders, onOpenProtocols, onOpenDashboard, onNavigate, onOpenSettings, theme, onThemeToggle }) {
  const [open, setOpen] = React.useState(false);
  const [canInstall, setCanInstall] = React.useState(false);
  const [deferredPrompt, setDeferredPrompt] = React.useState(null);
  const role = session?.role || 'viewer';
  const isDark = theme === 'dark';

  React.useEffect(() => {
    const handler = (e) => {
      e.preventDefault();
      setDeferredPrompt(e);
      setCanInstall(true);
    };
    window.addEventListener('beforeinstallprompt', handler);
    window.addEventListener('appinstalled', () => { setCanInstall(false); setDeferredPrompt(null); });
    return () => window.removeEventListener('beforeinstallprompt', handler);
  }, []);

  const handleInstall = async () => {
    if (!deferredPrompt) { window.ybpInstallPWA && window.ybpInstallPWA(); return; }
    deferredPrompt.prompt();
    const { outcome } = await deferredPrompt.userChoice;
    if (outcome === 'accepted') { setCanInstall(false); setDeferredPrompt(null); }
  };

  return (
    <div style={{
      position: 'fixed', top: 0, left: 0, right: 0, height: 44, zIndex: 8000,
      background: '#0f1e35', display: 'flex', alignItems: 'center',
      padding: '0 16px', gap: 8, fontFamily: 'Assistant, sans-serif', direction: 'rtl',
    }}>
      {/* Logo */}
      <div style={{ width:74, height:44, overflow:'hidden', background:'#fff', flexShrink:0, display:'flex', alignItems:'center', justifyContent:'center' }}>
        <div style={{ width:68, height:29, overflow:'hidden', flexShrink:0 }}>
          <img src="assets/ybp-logo-new.png" alt="YBP APP" style={{ width:68, display:'block' }}/>
        </div>
      </div>
      <div style={{ flex:1 }}></div>

      {/* AI Agent button */}
      <button
        onClick={() => window.openAiAgent && window.openAiAgent()}
        title="AI Agent"
        style={{
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          width: 44, height: 44, background: 'transparent',
          border: 'none', borderRadius: 8, cursor: 'pointer',
          flexShrink: 0, transition: 'background 0.15s', position: 'relative',
        }}
        onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.1)'}
        onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
      >
        <span style={{ fontSize: 20, lineHeight: 1 }}>⛑️</span>
      </button>

      {/* Theme toggle */}
      <button
        onClick={onThemeToggle}
        title={isDark ? 'עבור למצב בהיר' : 'עבור למצב כהה'}        style={{
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          width: 44, height: 44, background: 'transparent',
          border: 'none', borderRadius: 8, cursor: 'pointer',
          fontSize: 18, lineHeight: 1, flexShrink: 0,
          transition: 'background 0.15s',
        }}
        onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.1)'}
        onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
      >
        {isDark ? '☀️' : '🌙'}
      </button>

      {/* Notifications Bell */}
      {typeof NotificationsBell !== 'undefined' && (
        <NotificationsBell onNavigate={(screen, projectId) => {
          if (onNavigate) onNavigate(screen, projectId);
        }} />
      )}

      {/* Global Search */}
      {typeof GlobalSearchTrigger !== 'undefined' && (
        <GlobalSearchTrigger onNavigate={(screen, projectId, item) => {
          if (onNavigate) onNavigate(screen, projectId, item);
        }} />
      )}

      {/* PWA Install button — visible only when browser fires beforeinstallprompt */}
      {canInstall && (
        <button
          onClick={handleInstall}
          title="התקן כאפליקציה"
          style={{
            display: 'flex', alignItems: 'center', gap: 5,
            padding: '4px 10px', borderRadius: 7,
            background: 'rgba(59,130,246,0.25)', border: '1px solid rgba(59,130,246,0.5)',
            color: '#93c5fd', fontSize: 12, fontWeight: 700, cursor: 'pointer',
            fontFamily: 'inherit', flexShrink: 0,
          }}
        >
          <span>📲</span><span style={{ display: 'none' }}>התקן</span>
        </button>
      )}

      {/* Security badge */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 5, background: 'rgba(255,255,255,0.06)', borderRadius: 6, padding: '3px 8px' }}>
        <span style={{ fontSize: 11 }}>🔒</span>
        <span style={{ fontSize: 10, color: 'rgba(255,255,255,0.4)', fontWeight: 600, letterSpacing: 0.5 }}>HTTPS · OAuth 2.0</span>
      </div>
      <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.25)', fontWeight: 600, letterSpacing: 0.5, padding: '3px 6px' }}>
        {window.YBP_VERSION || 'v3.9.0.47'}
      </div>

      {/* User chip */}
      <div style={{ position: 'relative' }}>
        <button onClick={() => setOpen(o => !o)} style={{
          display: 'flex', alignItems: 'center', gap: 8, background: 'rgba(255,255,255,0.08)',
          border: '1px solid rgba(255,255,255,0.12)', borderRadius: 8, padding: '4px 10px 4px 6px',
          cursor: 'pointer', fontFamily: 'inherit',
        }}>
          <div style={{
            width: 26, height: 26, borderRadius: '50%', background: ROLE_COLORS[role],
            display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 700, color: '#fff',
          }}>{session?.avatar || '?'}</div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: '#fff', lineHeight: 1.2 }}>{session?.name?.split(' ')[0]}</div>
            <div style={{ fontSize: 9, color: ROLE_COLORS[role] === '#1a2c4a' ? '#b5a882' : ROLE_COLORS[role], letterSpacing: 0.3 }}>{ROLE_LABELS[role]}</div>
          </div>
          <span style={{ color: 'rgba(255,255,255,0.4)', fontSize: 10, marginRight: 2 }}>▼</span>
        </button>

        {open && (
          <div style={{
            position: 'absolute', top: 40, left: 0, background: '#fff', borderRadius: 10,
            boxShadow: '0 10px 40px rgba(0,0,0,0.2)', minWidth: 220, border: '1px solid #e5e7eb', overflow: 'hidden',
            zIndex: 9999,
          }}>
            {/* User info */}
            <div style={{ padding: '14px 16px', background: '#f8fafc', borderBottom: '1px solid #e5e7eb' }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: '#111827' }}>{session?.name}</div>
              <div style={{ fontSize: 11, color: '#6b7280', marginTop: 2 }}>{session?.email}</div>
              <div style={{ marginTop: 6, display: 'inline-flex', alignItems: 'center', gap: 5, background: ROLE_COLORS[role] + '14', borderRadius: 5, padding: '2px 8px' }}>
                <span style={{ fontSize: 10, color: ROLE_COLORS[role], fontWeight: 700 }}>{ROLE_LABELS[role]}</span>
              </div>
            </div>
            {/* Session info */}
            <div style={{ padding: '10px 16px', borderBottom: '1px solid #f3f4f6' }}>
              <div style={{ fontSize: 10, color: '#9ca3af', fontWeight: 600, marginBottom: 4, letterSpacing: 0.5 }}>SESSION</div>
              <SessionTimer loggedInAt={session?.loggedInAt} expiresAt={session?.expiresAt}/>
            </div>
            {/* Actions */}
            <div style={{ padding: 6 }}>
              <MenuBtn icon="📊" label="לוח בקרה" onClick={() => { setOpen(false); onOpenDashboard && onOpenDashboard(); }}/>
              <MenuBtn icon="👥" label="CRM — לקוחות ובעלי מקצוע" onClick={() => { setOpen(false); onOpenCRM && onOpenCRM(); }}/>
              <MenuBtn icon="📋" label="מכרזים" onClick={() => { setOpen(false); onOpenTenders && onOpenTenders(); }}/>
              <MenuBtn icon="📝" label="פרוטוקולים" onClick={() => { setOpen(false); onOpenProtocols && onOpenProtocols(); }}/>
              <MenuBtn icon="📋" label="יומן פעולות (Audit Log)" onClick={() => { setOpen(false); onOpenAudit && onOpenAudit(); }}/>
              <MenuBtn icon="📲" label={canInstall ? 'התקן כאפליקציה ✓' : 'התקן כאפליקציה'} onClick={() => { setOpen(false); handleInstall(); }}/>
              <MenuBtn icon="⚙️" label="הגדרות" onClick={() => { setOpen(false); onOpenSettings && onOpenSettings(); }}/>
              <MenuBtn icon="🚪" label="התנתקות" onClick={() => { setOpen(false); logoutSupabase(); onLogout(); }} danger/>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function SessionTimer({ loggedInAt, expiresAt }) {
  const [now, setNow] = React.useState(Date.now());
  React.useEffect(() => {
    const t = setInterval(() => setNow(Date.now()), 10000);
    return () => clearInterval(t);
  }, []);

  const elapsed = Math.floor((now - loggedInAt) / 60000);
  const remaining = Math.floor((expiresAt - now) / 60000);
  const pct = Math.max(0, Math.min(100, (now - loggedInAt) / (expiresAt - loggedInAt) * 100));

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: '#6b7280', marginBottom: 4 }}>
        <span>מחובר {elapsed < 1 ? 'כרגע' : `${elapsed} דק'`}</span>
        <span>פג תוקף בעוד {remaining} דק'</span>
      </div>
      <div style={{ height: 3, background: '#f3f4f6', borderRadius: 2 }}>
        <div style={{ height: '100%', width: `${pct}%`, background: pct > 80 ? '#ef4444' : '#22c55e', borderRadius: 2, transition: 'width 0.5s' }}></div>
      </div>
    </div>
  );
}

function MenuBtn({ icon, label, onClick, danger }) {
  return (
    <button onClick={onClick} style={{
      width: '100%', display: 'flex', alignItems: 'center', gap: 8, padding: '8px 10px',
      borderRadius: 6, border: 'none', background: 'transparent', cursor: 'pointer',
      fontSize: 13, color: danger ? '#dc2626' : '#374151', fontFamily: 'inherit', textAlign: 'right',
    }}
      onMouseEnter={e => e.currentTarget.style.background = danger ? '#fef2f2' : '#f8fafc'}
      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
    >
      <span>{icon}</span>
      <span style={{ fontWeight: 600 }}>{label}</span>
    </button>
  );
}

// ── JWT Token Generator — HMAC-SHA256 (Web Crypto API) ───────────────────
async function generateContractorToken(contractorName, projectId) {
  const b64url = (str) => btoa(str).replace(/\+/g,'-').replace(/\//g,'_').replace(/=/g,'');
  const b64urlBuf = (buf) => btoa(String.fromCharCode(...new Uint8Array(buf))).replace(/\+/g,'-').replace(/\//g,'_').replace(/=/g,'');

  const header  = b64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }));
  const payload = b64url(JSON.stringify({
    sub: contractorName,
    pid: projectId,
    role: 'contractor',
    iat: Math.floor(Date.now() / 1000),
    exp: Math.floor(Date.now() / 1000) + 7 * 24 * 3600,
  }));
  const signingInput = header + '.' + payload;

  // קבל secret מהגדרות — נדרש ב-settings.jwtSecret (מוגדר ב-Settings Screen)
  let secret = '';
  try {
    const s = JSON.parse(localStorage.getItem('ybp_settings') || '{}');
    secret = s.jwtSecret || s.supabaseAnonKey || '';
  } catch (_) {}
  if (!secret) {
    // fallback: pseudo-signature (ללא secret)
    const pseudo = b64url(`pseudo_${Math.random().toString(36).slice(2,10)}_${signingInput.slice(-8)}`);
    return `${signingInput}.${pseudo}`;
  }

  // HMAC-SHA256 אמיתי עם Web Crypto API
  const enc = new TextEncoder();
  const key = await crypto.subtle.importKey(
    'raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']
  );
  const sig = await crypto.subtle.sign('HMAC', key, enc.encode(signingInput));
  return `${signingInput}.${b64urlBuf(sig)}`;
}

window.YBP_AUTH.generateContractorToken = generateContractorToken;

// ── verifyAccessToken (v3.9.0.45) — אימות JWT שהופק ע"י generateContractorToken ─
async function verifyAccessToken(token) {
  if (typeof token !== 'string') return { valid:false, reason:'malformed' };
  const parts = token.split('.');
  if (parts.length !== 3) return { valid:false, reason:'malformed' };

  // base64url-decode
  const b64decode = (s) => {
    const b = s.replace(/-/g,'+').replace(/_/g,'/');
    const pad = '='.repeat((4 - b.length % 4) % 4);
    return atob(b + pad);
  };
  let payload;
  try { payload = JSON.parse(b64decode(parts[1])); }
  catch { return { valid:false, reason:'malformed' }; }

  const nowSec = Math.floor(Date.now() / 1000);
  if (payload.exp && payload.exp < nowSec) return { valid:false, reason:'expired' };

  // אימות חתימה רק אם secret מוגדר (כפי שמתנהג generateContractorToken)
  let secret = '';
  try { secret = (JSON.parse(localStorage.getItem('ybp_settings') || '{}').jwtSecret || ''); } catch {}
  if (secret) {
    try {
      const enc = new TextEncoder();
      const key = await crypto.subtle.importKey('raw', enc.encode(secret),
        { name:'HMAC', hash:'SHA-256' }, false, ['verify']);
      const sigBin = b64decode(parts[2]);
      const sigBytes = Uint8Array.from(sigBin, c => c.charCodeAt(0));
      const ok = await crypto.subtle.verify('HMAC', key, sigBytes, enc.encode(parts[0]+'.'+parts[1]));
      if (!ok) return { valid:false, reason:'bad-signature' };
    } catch { return { valid:false, reason:'bad-signature' }; }
  }
  return { valid:true, sub: payload.sub || '', pid: payload.pid || '', role: payload.role || '' };
}
window.YBP_AUTH.verifyAccessToken = verifyAccessToken;

// ── Role Permission Check ──────────────────────────────────────────────────
function canDo(session, action) {
  const role = session?.role || 'viewer';
  const perms = {
    admin:  ['view', 'edit', 'delete', 'invite', 'audit', 'budget', 'settings'],
    pm:     ['view', 'edit', 'delete', 'budget'],
    viewer: ['view'],
  };
  return (perms[role] || []).includes(action);
}

window.YBP_AUTH.canDo = canDo;

// ── Restore Button ────────────────────────────────────────────────────────
function RestoreButton({ ev, onRestored }) {
  const [status, setStatus] = React.useState('idle'); // idle | done | exists

  const handleRestore = () => {
    try {
      const item = JSON.parse(ev.snapshot);
      const storeRaw = localStorage.getItem('ybp_sync_store');
      const store = storeRaw ? JSON.parse(storeRaw) : {};
      store.reports = store.reports || [];
      const exists = store.reports.find(r => r.id === item.id);
      if (exists) { setStatus('exists'); return; }
      store.reports.unshift(item);
      localStorage.setItem('ybp_sync_store', JSON.stringify(store));
      // רשום שחזור ב-Audit Log
      appendAuditEvent({
        action: 'create',
        actor: getSession()?.name || 'Admin',
        detail: `שוחזר דוח ${item.id} — "${item.title}"`,
      });
      window.dispatchEvent(new CustomEvent('ybp-sync-change', { detail: store }));
      setStatus('done');
      setTimeout(() => { setStatus('idle'); onRestored && onRestored(); }, 1500);
    } catch(e) {
      alert('שגיאה בשחזור: ' + e.message);
    }
  };

  if (status === 'done') return <span style={{ fontSize: 10, color: '#16a34a', fontWeight: 700 }}>✅ שוחזר!</span>;
  if (status === 'exists') return <span style={{ fontSize: 10, color: '#f59e0b', fontWeight: 700 }}>⚠️ כבר קיים</span>;
  return (
    <button onClick={handleRestore} style={{
      fontSize: 10, padding: '3px 9px', borderRadius: 5, border: '1px solid #bbf7d0',
      background: '#f0fdf4', color: '#16a34a', fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
      whiteSpace: 'nowrap',
    }}>↩ שחזר</button>
  );
}

// ── Audit Log Screen ──────────────────────────────────────────────────────
const ACTION_META = {
  login:    { icon: '🔑', color: '#22c55e', label: 'כניסה' },
  logout:   { icon: '🚪', color: '#6b7280', label: 'יציאה' },
  create:   { icon: '✅', color: '#3b82f6', label: 'יצירה' },
  edit:     { icon: '✏️', color: '#f59e0b', label: 'עריכה' },
  delete:   { icon: '🗑️', color: '#ef4444', label: 'מחיקה' },
  send:     { icon: '📤', color: '#8b5cf6', label: 'שליחה' },
  view:     { icon: '👁️', color: '#0ea5e9', label: 'צפייה' },
  approve:  { icon: '✔️', color: '#10b981', label: 'אישור' },
  generate: { icon: '🔗', color: '#b5a882', label: 'קישור' },
};

function AuditLogScreen({ onBack }) {
  const [log, setLog] = React.useState(getAuditLog);
  const [filter, setFilter] = React.useState('all');
  const [search, setSearch] = React.useState('');
  const currentSession = getSession();

  React.useEffect(() => {
    // Add a few seed events if empty
    if (log.length === 0) {
      const seeds = [
        { action: 'login', actor: 'יובל בן פורת', detail: 'כניסה מוצלחת (yuval@ybprojects.com)' },
        { action: 'edit', actor: 'נתן ורשבסקי', detail: 'עדכן גאנט — קיסו רחובות' },
        { action: 'create', actor: 'נתן ורשבסקי', detail: 'דוח יומי חדש — RN-2026-014' },
        { action: 'send', actor: 'יובל בן פורת', detail: 'שלח דוח שבועי ללקוח + WhatsApp' },
        { action: 'generate', actor: 'יובל בן פורת', detail: 'קישור JWT לקבלן אבי כהן (7 ימים)' },
        { action: 'view', actor: 'רינת כהן', detail: 'פורטל לקוח — קיסו רחובות' },
        { action: 'delete', actor: 'יובל בן פורת', detail: 'מחק דוח REJ-2026-003' },
        { action: 'approve', actor: 'יובל בן פורת', detail: 'אישר ריג\'קט — חדר שרתים' },
      ];
      const now = Date.now();
      seeds.forEach((s, i) => {
        appendAuditEvent({ ...s, ts: new Date(now - (seeds.length - i) * 1800000).toISOString() });
      });
      setLog(getAuditLog());
    }
  }, []);

  const actions = Object.keys(ACTION_META);
  const filtered = log.filter(e => {
    const matchFilter = filter === 'all' || e.action === filter;
    const matchSearch = !search || e.actor?.includes(search) || e.detail?.includes(search);
    return matchFilter && matchSearch;
  });

  return (
    <div style={{ minHeight: '100vh', background: '#f6f7f9', fontFamily: 'Assistant, sans-serif', direction: 'rtl' }}>
      {/* Header */}
      <div style={{ background: '#1a2c4a', color: '#fff', padding: '16px 20px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <button onClick={onBack} style={{ background: 'rgba(255,255,255,0.12)', border: 'none', color: '#fff', borderRadius: 8, padding: '6px 12px', cursor: 'pointer', fontSize: 13, fontFamily: 'inherit', fontWeight: 600 }}>→ חזרה</button>
        <div>
          <div style={{ fontSize: 17, fontWeight: 800 }}>📋 יומן פעולות — Audit Log</div>
          <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)', marginTop: 1 }}>{log.length} אירועים מוקלטים</div>
        </div>
      </div>

      {/* Filters */}
      <div style={{ padding: '14px 16px', background: '#fff', borderBottom: '1px solid #e5e7eb', display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
        <input value={search} onChange={e => setSearch(e.target.value)} placeholder="חיפוש לפי שם / פעולה..."
          style={{ padding: '7px 12px', borderRadius: 7, border: '1px solid #e5e7eb', fontSize: 13, fontFamily: 'inherit', outline: 'none', flex: 1, minWidth: 160 }}/>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {['all', ...actions].map(a => (
            <button key={a} onClick={() => setFilter(a)} style={{
              padding: '5px 10px', borderRadius: 6, fontSize: 11, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
              background: filter === a ? '#1a2c4a' : '#f3f4f6',
              color: filter === a ? '#fff' : '#374151',
              border: filter === a ? '1px solid #1a2c4a' : '1px solid #e5e7eb',
            }}>
              {a === 'all' ? 'הכל' : (ACTION_META[a]?.label || a)}
            </button>
          ))}
        </div>
      </div>

      {/* Log list */}
      <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 8 }}>
        {filtered.length === 0 && (
          <div style={{ textAlign: 'center', padding: 60, color: '#9ca3af', fontSize: 14 }}>אין אירועים להצגה</div>
        )}
        {filtered.map(ev => {
          const meta = ACTION_META[ev.action] || { icon: '•', color: '#9ca3af', label: ev.action };
          const d = new Date(ev.ts);
          const dateStr = `${d.getDate().toString().padStart(2,'0')}/${(d.getMonth()+1).toString().padStart(2,'0')}/${d.getFullYear()}`;
          const timeStr = `${d.getHours().toString().padStart(2,'0')}:${d.getMinutes().toString().padStart(2,'0')}`;
          return (
            <div key={ev.id} style={{
              background: '#fff', borderRadius: 10, padding: '12px 16px',
              border: '1px solid #e5e7eb', display: 'flex', alignItems: 'center', gap: 14,
            }}>
              <div style={{
                width: 36, height: 36, borderRadius: '50%', background: meta.color + '18',
                display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, flexShrink: 0,
              }}>{meta.icon}</div>
              <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                  <span style={{ fontSize: 13, fontWeight: 700, color: '#111827' }}>{ev.actor}</span>
                  <span style={{ fontSize: 10, padding: '2px 7px', borderRadius: 4, background: meta.color + '18', color: meta.color, fontWeight: 700 }}>{meta.label}</span>
                </div>
                <div style={{ fontSize: 12, color: '#6b7280', marginTop: 2 }}>{ev.detail}</div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4, flexShrink: 0 }}>
                <div style={{ textAlign: 'left' }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: '#374151' }}>{timeStr}</div>
                  <div style={{ fontSize: 10, color: '#9ca3af' }}>{dateStr}</div>
                </div>
                {ev.action === 'delete' && ev.snapshot && currentSession?.role === 'admin' && (
                  <RestoreButton ev={ev} onRestored={() => setLog(getAuditLog())}/>
                )}
              </div>
            </div>
          );
        })}
      </div>

      {/* Security summary */}
      <div style={{ margin: '0 16px 32px', background: '#fff', borderRadius: 12, padding: 16, border: '1px solid #e5e7eb' }}>
        <div style={{ fontSize: 12, fontWeight: 700, color: '#1a2c4a', marginBottom: 12 }}>🔒 מדיניות אבטחה פעילה</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          {[
            ['Google OAuth 2.0', 'כניסה דרך @ybprojects.com בלבד'],
            ['Session Timeout', '8 שעות מכניסה אחרונה'],
            ['JWT Contractor Links', 'תוקף 7 ימים + חתימת HMAC'],
            ['Supabase RLS', 'Row-level security לפי תפקיד'],
            ['HTTPS Only', 'Vercel + Cloudflare, TLS 1.3'],
            ['Audit Log', 'כל פעולה מוקלטת ל-200 אירועים'],
          ].map(([title, sub]) => (
            <div key={title} style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
              <span style={{ color: '#22c55e', fontSize: 14, flexShrink: 0 }}>✓</span>
              <div>
                <div style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>{title}</div>
                <div style={{ fontSize: 11, color: '#9ca3af' }}>{sub}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ── Contractor Link Modal ─────────────────────────────────────────────────
function ContractorLinkModal({ contractorName, projectId, onClose }) {
  const [token, setToken] = React.useState('מייצר...');
  const [copied, setCopied] = React.useState(false);
  // v3.9.0.45 — origin דינמי, פורמט שורש (?t=) — תואם לפענוח ב-index.html boot
  const baseUrl = window.location.origin || '';
  const parts = token.split('.');
  const link = token === 'מייצר...' ? '...' : `${baseUrl}/?t=${parts[0]}…`;
  const fullLink = `${baseUrl}/?t=${token}`;

  React.useEffect(() => {
    generateContractorToken(contractorName, projectId).then(setToken);
  }, [contractorName, projectId]);

  const handleCopy = () => {
    navigator.clipboard?.writeText(fullLink).catch(() => {});
    setCopied(true);
    appendAuditEvent({ action: 'generate', actor: window.YBP_AUTH.getSession()?.name || 'מנהל', detail: `קישור JWT לקבלן ${contractorName} (7 ימים)` });
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 9999,
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
      fontFamily: 'Assistant, sans-serif', direction: 'rtl',
    }} onClick={e => e.target === e.currentTarget && onClose()}>
      <div style={{ background: '#fff', borderRadius: 16, padding: 28, maxWidth: 480, width: '100%', boxShadow: '0 20px 60px rgba(0,0,0,0.25)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
          <div style={{ fontSize: 17, fontWeight: 800, color: '#1a2c4a' }}>🔗 קישור מאובטח לקבלן</div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 20, cursor: 'pointer', color: '#9ca3af' }}>✕</button>
        </div>

        <div style={{ background: '#f0fdf4', border: '1px solid #bbf7d0', borderRadius: 10, padding: 14, marginBottom: 16 }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: '#16a34a', marginBottom: 6 }}>✅ JWT Token נוצר בהצלחה</div>
          <div style={{ fontSize: 11, color: '#16a34a' }}>הקישור חתום ב-HMAC · תוקף 7 ימים · גישה לפרויקט {projectId} בלבד</div>
        </div>

        <div style={{ marginBottom: 16 }}>
          <label style={{ fontSize: 11, fontWeight: 700, color: '#6b7280', letterSpacing: 0.5, display: 'block', marginBottom: 6 }}>קישור לקבלן: {contractorName}</label>
          <div style={{ background: '#f8fafc', border: '1px solid #e5e7eb', borderRadius: 8, padding: '10px 12px', fontSize: 11, color: '#374151', wordBreak: 'break-all', direction: 'ltr', textAlign: 'left', fontFamily: 'monospace' }}>
            {link}
          </div>
        </div>

        <div style={{ marginBottom: 20 }}>
          <label style={{ fontSize: 11, fontWeight: 700, color: '#6b7280', letterSpacing: 0.5, display: 'block', marginBottom: 6 }}>JWT Token</label>
          <div style={{ background: '#1e293b', borderRadius: 8, padding: '10px 12px', fontSize: 9, color: '#94a3b8', wordBreak: 'break-all', direction: 'ltr', textAlign: 'left', fontFamily: 'monospace', lineHeight: 1.6 }}>
            <span style={{ color: '#60a5fa' }}>{token.split('.')[0]}</span>
            <span style={{ color: '#fff' }}>.</span>
            <span style={{ color: '#34d399' }}>{token.split('.')[1]}</span>
            <span style={{ color: '#fff' }}>.</span>
            <span style={{ color: '#f472b6' }}>{token.split('.')[2]}</span>
          </div>
        </div>

        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={handleCopy} style={{
            flex: 1, padding: '11px', borderRadius: 9, border: 'none',
            background: copied ? '#16a34a' : '#1a2c4a', color: '#fff',
            fontWeight: 700, fontSize: 14, cursor: 'pointer', fontFamily: 'inherit', transition: 'background 0.2s',
          }}>{copied ? '✅ הועתק!' : '📋 העתק קישור'}</button>
          <button onClick={onClose} style={{
            padding: '11px 18px', borderRadius: 9, border: '1px solid #e5e7eb',
            background: '#fff', color: '#374151', fontWeight: 600, fontSize: 14, cursor: 'pointer', fontFamily: 'inherit',
          }}>סגור</button>
        </div>
      </div>
    </div>
  );
}

// ── getCurrentUser — unified profile helper ──────────────────────────────────
// Always returns a complete user object. Prefers cloud profile (settings.profile)
// over the Google OAuth session, so the Hebrew name from Settings appears everywhere.
window.YBP_AUTH.getCurrentUser = function() {
  const session = (function() {
    try {
      const s = JSON.parse(localStorage.getItem('ybp_auth_session') || 'null');
      return (s && s.expiresAt > Date.now()) ? s : {};
    } catch(_) { return {}; }
  })();
  // Read from ybp_settings.profile (set in Settings → פרופיל)
  const profile = (function() {
    try {
      const settings = JSON.parse(localStorage.getItem('ybp_settings') || '{}');
      return settings.profile || {};
    } catch(_) { return {}; }
  })();
  const raw = profile.name || session.name || 'מנהל פרויקט';
  return {
    name:           raw,
    title:          profile.title          || session.role  || '',
    role:           profile.role           || session.role  || 'pm',
    email:          profile.email          || session.email || '',
    signature:      profile.signature      || '',
    signatureImage: profile.signatureImage || '',
    initials:  raw.split(' ').map(function(w){ return w[0] || ''; }).join('').slice(0, 2).toUpperCase(),
  };
};

// Export to window
Object.assign(window, { GoogleSSOLogin, SessionBar, AuditLogScreen, ContractorLinkModal });
