/**
 * Settings Screen — הגדרות YBP APP
 * סקציות: פרופיל / חתימת מייל / Make Webhooks / הגדרות חברה / התראות / Drive
 * הרשאות: Admin — הכל, PM — פרופיל + חתימה בלבד
 * נשמר ב: localStorage key ybp_settings
 */
(function () {

const { useState, useEffect, useCallback, useRef } = React;

// ── Storage — cloud-hybrid (localStorage cache + cloudSave/cloudLoad) ─────────
const SETTINGS_KEY       = 'ybp_settings';
const SETTINGS_CLOUD_KEY = 'app_settings';

function loadSettings() {
  try { return JSON.parse(localStorage.getItem(SETTINGS_KEY) || 'null') || {}; }
  catch { return {}; }
}

// Deep merge — local שדות מנצחים, שדות שקיימים רק ב-remote נשמרים
function deepMergeSettings(local, remote) {
  if (!remote || typeof remote !== 'object') return local || {};
  if (!local  || typeof local  !== 'object') return remote || {};
  const result = { ...remote };
  for (const key of Object.keys(local)) {
    const lv = local[key];
    const rv = remote[key];
    if (lv && typeof lv === 'object' && !Array.isArray(lv) && rv && typeof rv === 'object' && !Array.isArray(rv)) {
      result[key] = { ...rv, ...lv }; // local wins per-field, remote fills gaps
    } else if (lv !== undefined && lv !== null && lv !== '') {
      result[key] = lv; // local value beats remote
    }
    // else: keeps remote[key] already in result
  }
  return result;
}

function saveSettings(data) {
  // 1. localStorage — cache מיידי (sync)
  try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(data)); } catch(e) {}
  // 2. Cloud — fire-and-forget
  if (typeof window.cloudSave === 'function') {
    window.cloudSave(SETTINGS_CLOUD_KEY, data).catch(e =>
      console.warn('[Settings] cloudSave failed:', e)
    );
  }
  window.dispatchEvent(new CustomEvent('ybp-settings-changed', { detail: data }));
}

// טעינה ראשונה מהענן + migration של ybp_drive_* keys ישנים
function initSettingsCloudLoad() {
  // Migration: ybp_drive_${projId} → settings.driveFolders
  try {
    const existing = loadSettings();
    const hasFolders = existing.driveFolders && Object.keys(existing.driveFolders).length > 0;
    if (!hasFolders) {
      const migrated = {};
      Object.keys(localStorage).forEach(k => {
        const m = k.match(/^ybp_drive_(.+)$/);
        if (!m) return;
        try {
          const raw = localStorage.getItem(k) || '';
          const fid = JSON.parse(raw)?.folderId || raw;
          if (fid) migrated[m[1]] = fid;
          localStorage.removeItem(k);
        } catch (_) {}
      });
      if (Object.keys(migrated).length > 0) {
        const merged = { ...existing, driveFolders: migrated };
        localStorage.setItem(SETTINGS_KEY, JSON.stringify(merged));
      }
    }
  } catch(_) {}

  // Migration: ybp_user_roles → settings.userRoles
  try {
    const existing = loadSettings();
    if (!existing.userRoles) {
      const rolesRaw = localStorage.getItem('ybp_user_roles');
      if (rolesRaw) {
        const roles = JSON.parse(rolesRaw);
        if (Object.keys(roles).length > 0) {
          const merged = { ...existing, userRoles: roles };
          localStorage.setItem(SETTINGS_KEY, JSON.stringify(merged));
        }
      }
    }
  } catch(_) {}

  if (typeof window.cloudLoad !== 'function') return;
  window.cloudLoad(SETTINGS_CLOUD_KEY, null).then(remote => {
    const local = loadSettings();
    const localHasData  = Object.keys(local).length > 0;
    const remoteHasData = remote && typeof remote === 'object' && Object.keys(remote).length > 0;

    if (!remoteHasData && localHasData) {
      // cloud ריק, יש מקומי — push
      window.cloudSave(SETTINGS_CLOUD_KEY, local).catch(() => {});
      return;
    }
    if (remoteHasData && !localHasData) {
      // cloud מלא, מקומי ריק — pull
      try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(remote)); } catch(_) {}
      if (remote.userRoles) {
        try { localStorage.setItem('ybp_user_roles', JSON.stringify(remote.userRoles)); } catch(_) {}
      }
      window.dispatchEvent(new CustomEvent('ybp-settings-changed', { detail: remote }));
      return;
    }
    if (remoteHasData && localHasData) {
      // שניהם יש נתונים — deep merge (local מנצח per-field)
      const merged     = deepMergeSettings(local, remote);
      const mergedJson = JSON.stringify(merged);
      if (mergedJson !== JSON.stringify(local)) {
        try { localStorage.setItem(SETTINGS_KEY, mergedJson); } catch(_) {}
        if (merged.userRoles) {
          try { localStorage.setItem('ybp_user_roles', JSON.stringify(merged.userRoles)); } catch(_) {}
        }
        window.dispatchEvent(new CustomEvent('ybp-settings-changed', { detail: merged }));
      }
      // אם merged שונה מ-remote — push כדי לאחד את הענן
      if (mergedJson !== JSON.stringify(remote)) {
        window.cloudSave(SETTINGS_CLOUD_KEY, merged).catch(() => {});
      }
    }
  }).catch(e => console.warn('[Settings] initCloudLoad error:', e));
}

// Settings sync — every 5 minutes when tab visible
function startSettingsPolling() {
  if (window.__ybpSettingsPolling) return;
  window.__ybpSettingsPolling = true;
  const pollFn = function() {
    if (typeof window.cloudLoad !== 'function') return;
    window.cloudLoad(SETTINGS_CLOUD_KEY, null).then(function(remote) {
      if (!remote || typeof remote !== 'object' || !Object.keys(remote).length) return;
      const local = loadSettings();
      const merged     = deepMergeSettings(local, remote);
      const mergedJson = JSON.stringify(merged);
      if (mergedJson !== JSON.stringify(local)) {
        try { localStorage.setItem(SETTINGS_KEY, mergedJson); } catch(_) {}
        if (merged.userRoles) {
          try { localStorage.setItem('ybp_user_roles', JSON.stringify(merged.userRoles)); } catch(_) {}
        }
        window.dispatchEvent(new CustomEvent('ybp-settings-changed', { detail: merged }));
      }
      if (mergedJson !== JSON.stringify(remote)) {
        window.cloudSave(SETTINGS_CLOUD_KEY, merged).catch(function(){});
      }
    }).catch(function(){});
  };
  if (typeof window.createSmartPoll === 'function') {
    window.createSmartPoll(pollFn, 5 * 60 * 1000);
  } else {
    setInterval(function() { if (document.visibilityState === 'visible') pollFn(); }, 5 * 60 * 1000);
  }
}

initSettingsCloudLoad();
startSettingsPolling();

// ── Webhook definitions ──────────────────────────────────────────────────────
const WEBHOOKS = [
  { key: 'PLACEHOLDER_VOICE_FORM_EU2',         label: 'קלט קולי → Claude Haiku',            cat: 'דוחות',    desc: 'מעבד הקלטה קצרה → ממלא שדות בטופס', file: 'voice-input.jsx' },
  { key: 'PLACEHOLDER_MEETING_RECORDING_EU2',  label: 'הקלטת פגישה → Whisper → Sonnet',     cat: 'דוחות',    desc: 'MP3 → תמלול → משימות → Drive', file: 'meeting-recorder.jsx' },
  { key: 'PLACEHOLDER_LIST_PROJECTS',      label: 'רשימת פרויקטים',                      cat: 'דוחות',    desc: 'מחזיר רשימת פרויקטים פעילים לבחירה', file: 'meeting-recorder.jsx' },
  { key: 'PLACEHOLDER_UPLOAD_PHOTO',       label: 'העלאת תמונה → Drive',                 cat: 'תמונות',   desc: 'Base64 → Google Drive → URL', file: 'photo-upload.jsx' },
  { key: 'PLACEHOLDER_UPLOAD_GANTT_PDF',   label: 'שמירת גאנט PDF → Drive',              cat: 'PDF',      desc: 'PDF גאנט → תיקיית הפרויקט ב-Drive', file: 'gantt-screen.jsx' },
  { key: 'PLACEHOLDER_UPLOAD_REPORT_PDF',  label: 'שמירת דוח PDF → Drive',               cat: 'PDF',      desc: 'PDF דוח → תיקיית הפרויקט ב-Drive', file: 'report-viewer.jsx' },
  { key: 'PLACEHOLDER_UPLOAD_BUDGET_PDF',  label: 'שמירת תקציב PDF → Drive',             cat: 'PDF',      desc: 'PDF תקציב → תיקיית הפרויקט ב-Drive', file: 'budget.jsx' },
  { key: 'PLACEHOLDER_UPLOAD_PLAN',        label: 'העלאת תוכנית → Drive',                cat: 'תוכניות',  desc: 'PDF/JPG תוכנית → Drive → תיוג AI', file: 'plans.jsx' },
  { key: 'PLACEHOLDER_EXTRACT_QUOTE_FILE', label: 'חילוץ הצעת מחיר מקובץ',              cat: 'מכרזים',   desc: 'PDF/JPG הצעה → Claude Vision → שדות', file: 'tenders-screen.jsx' },
  { key: 'PLACEHOLDER_NEW_PROJECT_SETUP',  label: 'הקמת פרויקט חדש → Drive',             cat: 'פרויקטים', desc: 'יצירת תיקיית Drive + הגדרות ראשוניות', file: 'new-project-wizard.jsx' },
  { key: 'PLACEHOLDER_LOAD_CONTACTS',   label: 'טעינת אנשי קשר מ-YBP DB',  cat: 'אנשי קשר', desc: 'Google Sheets YBP DB → מאגר אנשי קשר', file: 'contacts.jsx' },
  { key: 'PLACEHOLDER_SAVE_CONTACT',   label: 'שמירת איש קשר חדש',        cat: 'אנשי קשר', desc: 'הוספת איש קשר חדש ל-Google Sheets YBP DB', file: 'contacts.jsx' },
  { key: 'PLACEHOLDER_UPDATE_CONTACT', label: 'עדכון איש קשר',             cat: 'אנשי קשר', desc: 'עדכון פרטי איש קשר קיים ב-Google Sheets', file: 'contacts.jsx' },
  { key: 'PLACEHOLDER_DELETE_CONTACT', label: 'מחיקת איש קשר',             cat: 'אנשי קשר', desc: 'מחיקת איש קשר מ-Google Sheets YBP DB', file: 'contacts.jsx' },
  { key: 'PLACEHOLDER_PENDING_REJECTS_INBOX', label: '📥 קליטת ריג\'קטים מבחוץ', cat: "ריג'קטים", desc: 'POST מ-Claude/WhatsApp/curl → Haiku → DataStore', file: 'field-capture.jsx' },
  { key: 'PLACEHOLDER_LIST_PENDING_REJECTS',  label: '📋 רשימת ממתינים לאישור',  cat: "ריג'קטים", desc: 'GET — האפליקציה שואבת batches ממתינים', file: 'field-capture.jsx' },
  { key: 'PLACEHOLDER_APPROVE_PENDING_BATCH', label: '✓ אישור / דחיית batch',    cat: "ריג'קטים", desc: 'POST — approve/reject batch מהמגירה', file: 'field-capture.jsx' },
];

const WEBHOOK_CATS = [...new Set(WEBHOOKS.map(w => w.cat))];
const CAT_ICONS = { 'דוחות': '📋', 'תמונות': '📷', 'PDF': '📄', 'תוכניות': '🗺️', 'מכרזים': '📬', 'פרויקטים': '🏗️', 'אנשי קשר': '👥', "ריג'קטים": '🚫' };

// ── Sidebar sections ─────────────────────────────────────────────────────────
const SECTIONS_ADMIN = [
  { id: 'profile',      icon: '👤', label: 'פרופיל משתמש' },
  { id: 'signature',    icon: '✉️', label: 'חתימת מייל' },
  { id: 'company',      icon: '🏢', label: 'הגדרות חברה' },
  { id: 'access',       icon: '🔑', label: 'קישורי גישה' },
  { id: 'webhooks',     icon: '🔗', label: 'Make Webhooks' },
  { id: 'sync',         icon: '🔄', label: 'סנכרון' },
  { id: 'notifications',icon: '🔔', label: 'התראות' },
  { id: 'drive',        icon: '☁️', label: 'Google Drive' },
  { id: 'auth',         icon: '🔐', label: 'Google OAuth' },
  { id: 'users',        icon: '👥', label: 'ניהול משתמשים' },
];

const SECTIONS_PM = [
  { id: 'profile',   icon: '👤', label: 'פרופיל משתמש' },
  { id: 'signature', icon: '✉️', label: 'חתימת מייל' },
  { id: 'access',    icon: '🔑', label: 'קישורי גישה' },
];

// ── Shared input style ───────────────────────────────────────────────────────
const inp = {
  width: '100%', padding: '10px 12px', borderRadius: 8,
  border: '1.5px solid var(--ybp-border,#e5e7eb)',
  fontSize: 15, fontFamily: 'Assistant, sans-serif',
  background: 'var(--ybp-input-bg,#fff)', color: 'var(--ybp-ink,#111827)',
  outline: 'none', boxSizing: 'border-box', direction: 'rtl',
};

const Field = ({ label, hint, children }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
    <label style={{ fontSize: 12, fontWeight: 700, color: 'var(--ybp-ink-soft,#374151)', letterSpacing: 0.3 }}>{label}</label>
    {children}
    {hint && <span style={{ fontSize: 11, color: 'var(--ybp-ink-faint,#9ca3af)' }}>{hint}</span>}
  </div>
);

const SaveBtn = ({ onClick, saved }) => (
  <button onClick={onClick} style={{
    padding: '10px 28px', borderRadius: 8, border: 'none', cursor: 'pointer',
    background: saved ? '#16a34a' : '#1a2c4a', color: '#fff',
    fontSize: 14, fontWeight: 700, fontFamily: 'Assistant, sans-serif',
    transition: 'background .3s', display: 'flex', alignItems: 'center', gap: 8,
  }}>
    {saved ? '✓ נשמר' : 'שמור שינויים'}
  </button>
);

// ── SignaturePad ─────────────────────────────────────────────────────────────
function SignaturePad({ value, onChange: onChangeSig }) {
  const canvasRef = useRef(null);
  const [isDrawing, setIsDrawing] = useState(false);
  const [mode, setMode] = useState('draw');
  const fileRef = useRef(null);
  const lastPos = useRef(null);

  const getPos = (e) => {
    const canvas = canvasRef.current;
    const rect = canvas.getBoundingClientRect();
    const src = e.touches ? e.touches[0] : e;
    return {
      x: (src.clientX - rect.left) * (canvas.width / rect.width),
      y: (src.clientY - rect.top)  * (canvas.height / rect.height),
    };
  };

  const startDraw = (e) => {
    e.preventDefault();
    const pos = getPos(e);
    lastPos.current = pos;
    setIsDrawing(true);
  };

  const draw = (e) => {
    if (!isDrawing) return;
    e.preventDefault();
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    const pos = getPos(e);
    ctx.strokeStyle = '#1a2c4a';
    ctx.lineWidth = 2.5;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
    ctx.beginPath();
    ctx.moveTo(lastPos.current.x, lastPos.current.y);
    ctx.lineTo(pos.x, pos.y);
    ctx.stroke();
    lastPos.current = pos;
  };

  const stopDraw = () => {
    if (!isDrawing) return;
    setIsDrawing(false);
    onChangeSig(canvasRef.current.toDataURL('image/png'));
  };

  const clearCanvas = () => {
    const canvas = canvasRef.current;
    canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
    onChangeSig('');
  };

  const handleFile = (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => onChangeSig(ev.target.result);
    reader.readAsDataURL(file);
  };

  const tabSt = (active) => ({
    padding: '5px 14px', borderRadius: 6, border: 'none', cursor: 'pointer',
    fontSize: 12, fontWeight: 700, fontFamily: 'Assistant, sans-serif',
    background: active ? '#1a2c4a' : '#f3f4f6', color: active ? '#fff' : '#374151',
  });

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      <div style={{ display: 'flex', gap: 6 }}>
        <button type="button" style={tabSt(mode === 'draw')}   onClick={() => setMode('draw')}>✍️ ציור</button>
        <button type="button" style={tabSt(mode === 'upload')} onClick={() => setMode('upload')}>📁 העלאה</button>
      </div>

      {mode === 'draw' ? (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          <canvas
            ref={canvasRef}
            width={480} height={120}
            style={{ width: '100%', height: 120, border: '1.5px solid #e5e7eb', borderRadius: 8, cursor: 'crosshair', background: '#fff', touchAction: 'none' }}
            onMouseDown={startDraw} onMouseMove={draw} onMouseUp={stopDraw} onMouseLeave={stopDraw}
            onTouchStart={startDraw} onTouchMove={draw} onTouchEnd={stopDraw}
          />
          <button type="button" onClick={clearCanvas} style={{ alignSelf: 'flex-start', fontSize: 11, color: '#dc2626', background: 'none', border: 'none', cursor: 'pointer', padding: 0, fontFamily: 'inherit' }}>
            נקה
          </button>
        </div>
      ) : (
        <div>
          <input ref={fileRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={handleFile} />
          <button type="button" onClick={() => fileRef.current && fileRef.current.click()} style={{
            width: '100%', padding: 14, border: '2px dashed #e5e7eb', borderRadius: 8,
            background: '#f9fafb', cursor: 'pointer', fontSize: 13, color: '#6b7280', fontFamily: 'inherit',
          }}>
            📁 בחר תמונת חתימה מהמכשיר
          </button>
        </div>
      )}

      {value && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <img src={value} alt="חתימה" style={{ height: 48, maxWidth: 200, objectFit: 'contain', border: '1px solid #e5e7eb', borderRadius: 6, padding: 4, background: '#fff' }} />
          <span style={{ fontSize: 12, color: '#10b981' }}>✓ חתימה שמורה</span>
        </div>
      )}
    </div>
  );
}

// ── Section: פרופיל ──────────────────────────────────────────────────────────
function ProfileSection({ settings, onChange, session }) {
  const [saved, setSaved] = useState(false);
  const p = settings.profile || {};
  const { isMobile } = useViewport();

  const set = (k, v) => onChange('profile', { ...p, [k]: v });

  const handleSave = () => {
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
    window.toastSuccess && window.toastSuccess('פרופיל נשמר ✓');
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <SectionHeader icon="👤" title="פרופיל משתמש" subtitle="הפרטים שלך מופיעים בדוחות ובחתימת מייל" />

      {/* Avatar */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
        <div style={{
          width: 64, height: 64, borderRadius: '50%',
          background: 'linear-gradient(135deg, #1a2c4a, #2563eb)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 22, fontWeight: 700, color: '#fff', flexShrink: 0,
        }}>
          {(p.name || session?.name || '?').split(' ').map(w => w[0]).join('').slice(0,2)}
        </div>
        <div>
          <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>{p.name || session?.name || ''}</div>
          <div style={{ fontSize: 13, color: 'var(--ybp-ink-faint,#6b7280)' }}>{p.email || session?.email || ''}</div>
          <div style={{ fontSize: 12, marginTop: 2, padding: '2px 8px', borderRadius: 99, background: '#eff6ff', color: '#2563eb', display: 'inline-block', fontWeight: 600 }}>
            {session?.role === 'admin' ? 'מנהל ראשי' : session?.role === 'pm' ? 'מנהל פרויקט' : 'צופה'}
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 14 }}>
        <Field label="שם מלא">
          <input style={inp} value={p.name || session?.name || ''} onChange={e => onChange('profile', { ...p, name: e.target.value, nameLocked: true })} placeholder="שם מלא" />
        </Field>
        <Field label="תפקיד">
          <input style={inp} value={p.title || ''} onChange={e => set('title', e.target.value)} placeholder="מנהל פרויקטים" />
        </Field>
        <Field label="טלפון">
          <input style={inp} value={p.phone || ''} onChange={e => set('phone', e.target.value)} placeholder="050-0000000" dir="ltr" />
        </Field>
        <Field label="מייל">
          <input style={inp} value={p.email || session?.email || ''} onChange={e => set('email', e.target.value)} placeholder="email@ybprojects.com" dir="ltr" />
        </Field>
      </div>
      <Field label="ביו קצר (אופציונלי)">
        <textarea style={{ ...inp, minHeight: 72, resize: 'vertical' }} value={p.bio || ''} onChange={e => set('bio', e.target.value)} placeholder="כמה מילים על עצמך..." />
      </Field>

      <Field label="חתימה גרפית" hint="מופיעה בדוחות ובתצוגת PDF — ציור עם האצבע/עכבר או העלאת תמונה">
        <SignaturePad value={p.signatureImage || ''} onChange={v => set('signatureImage', v)} />
      </Field>

      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <SaveBtn onClick={handleSave} saved={saved} />
      </div>
    </div>
  );
}

// ── Section: חתימת מייל ──────────────────────────────────────────────────────
function SignatureSection({ settings, onChange }) {
  const [saved, setSaved] = useState(false);
  const [previewMode, setPreviewMode] = useState(false);
  const { isMobile } = useViewport();
  const s = settings.signature || {};
  const p = settings.profile || {};

  const set = (k, v) => onChange('signature', { ...s, [k]: v });

  const handleSave = () => {
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
    window.toastSuccess && window.toastSuccess('חתימת מייל נשמרה ✓');
  };

  const name  = s.name  || p.name  || 'שמך המלא';
  const title = s.title || p.title || 'מנהל פרויקטים';
  const phone = s.phone || p.phone || '050-0000000';
  const email = s.email || p.email || 'email@ybprojects.com';
  const showLogo = s.showLogo !== false;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <SectionHeader icon="✉️" title="חתימת מייל" subtitle="מופיעה בכל מייל שנשלח מהמערכת (Gmail)" />

      {/* Preview toggle */}
      <div style={{ display: 'flex', gap: 8 }}>
        <TabBtn active={!previewMode} onClick={() => setPreviewMode(false)}>עריכה</TabBtn>
        <TabBtn active={previewMode}  onClick={() => setPreviewMode(true)}>תצוגה מקדימה</TabBtn>
      </div>

      {previewMode ? (
        <SignaturePreview name={name} title={title} phone={phone} email={email} showLogo={showLogo} extra={s.extra} />
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 14 }}>
            <Field label="שם בחתימה">
              <input style={inp} value={s.name || ''} onChange={e => set('name', e.target.value)} placeholder={p.name || 'שמך'} />
            </Field>
            <Field label="תפקיד בחתימה">
              <input style={inp} value={s.title || ''} onChange={e => set('title', e.target.value)} placeholder={p.title || 'תפקידך'} />
            </Field>
            <Field label="טלפון בחתימה">
              <input style={inp} value={s.phone || ''} onChange={e => set('phone', e.target.value)} placeholder={p.phone || '050-0000000'} dir="ltr" />
            </Field>
            <Field label="מייל בחתימה">
              <input style={inp} value={s.email || ''} onChange={e => set('email', e.target.value)} placeholder={p.email || 'email@ybprojects.com'} dir="ltr" />
            </Field>
          </div>
          <Field label="טקסט נוסף (אופציונלי)" hint="שורה נוספת בחתימה — לדוגמה: 'זמינות: א׳-ה׳, 8:00-18:00'">
            <input style={inp} value={s.extra || ''} onChange={e => set('extra', e.target.value)} placeholder="זמינות / אתר / עוד..." />
          </Field>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <ToggleSwitch checked={showLogo} onChange={v => set('showLogo', v)} />
            <span style={{ fontSize: 14, color: 'var(--ybp-ink,#111827)' }}>הצג לוגו YBP בחתימה</span>
          </div>
        </div>
      )}

      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <SaveBtn onClick={handleSave} saved={saved} />
      </div>
    </div>
  );
}

// חתימה preview
function SignaturePreview({ name, title, phone, email, showLogo, extra }) {
  return (
    <div style={{
      border: '1.5px solid var(--ybp-border,#e5e7eb)', borderRadius: 10,
      padding: 20, background: 'var(--ybp-panel,#fff)',
      fontFamily: 'Assistant, sans-serif', direction: 'rtl',
    }}>
      <div style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#9ca3af)', marginBottom: 12, fontWeight: 600, letterSpacing: 0.5 }}>תצוגה מקדימה של חתימה</div>
      <div style={{ borderTop: '1.5px solid #e5e7eb', paddingTop: 14, display: 'flex', gap: 16, alignItems: 'flex-start' }}>
        {showLogo && (
          <div style={{ width: 48, height: 48, background: '#0f1e35', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, overflow: 'hidden' }}>
            <img src="assets/ybp-logo-new.png" alt="YBP" style={{ width: 42 }} />
          </div>
        )}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
          <div style={{ fontSize: 15, fontWeight: 700, color: '#111827' }}>{name}</div>
          <div style={{ fontSize: 13, color: '#1a2c4a', fontWeight: 600 }}>{title}</div>
          <div style={{ fontSize: 12, color: '#6b7280' }}>{phone} · {email}</div>
          {extra && <div style={{ fontSize: 12, color: '#6b7280' }}>{extra}</div>}
          <div style={{ fontSize: 12, color: '#b5a882', fontWeight: 700, marginTop: 2 }}>YBPROJECTS · ניהול פרויקטים בבנייה</div>
        </div>
      </div>
    </div>
  );
}

// ── Section: הגדרות חברה ──────────────────────────────────────────────────────
function CompanySection({ settings, onChange }) {
  const { isMobile } = useViewport();
  const [saved, setSaved] = useState(false);
  const c = settings.company || {};
  const set = (k, v) => onChange('company', { ...c, [k]: v });

  const handleSave = () => {
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
    window.toastSuccess && window.toastSuccess('הגדרות חברה נשמרו ✓');
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <SectionHeader icon="🏢" title="הגדרות חברה" subtitle="פרטי החברה מופיעים בנייר המכתבים ובדוחות PDF" />
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 14 }}>
        <Field label="שם החברה">
          <input style={inp} value={c.name || 'YBPROJECTS'} onChange={e => set('name', e.target.value)} />
        </Field>
        <Field label="ח.פ. / ע.מ.">
          <input style={inp} value={c.taxId || ''} onChange={e => set('taxId', e.target.value)} placeholder="514XXXXXXX" dir="ltr" />
        </Field>
        <Field label="כתובת">
          <input style={inp} value={c.address || 'זרחין 10, רעננה'} onChange={e => set('address', e.target.value)} />
        </Field>
        <Field label="טלפון משרד">
          <input style={inp} value={c.officePhone || ''} onChange={e => set('officePhone', e.target.value)} placeholder="09-0000000" dir="ltr" />
        </Field>
        <Field label="מייל כללי">
          <input style={inp} value={c.email || 'office@ybprojects.com'} onChange={e => set('email', e.target.value)} dir="ltr" />
        </Field>
        <Field label="אתר אינטרנט">
          <input style={inp} value={c.website || ''} onChange={e => set('website', e.target.value)} placeholder="https://ybprojects.com" dir="ltr" />
        </Field>
      </div>
      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <SaveBtn onClick={handleSave} saved={saved} />
      </div>
    </div>
  );
}

// ── Section: Make Webhooks ────────────────────────────────────────────────────
function SyncSection() {
  const [syncing, setSyncing] = React.useState(false);
  const handleSync = async () => {
    setSyncing(true);
    try {
      const loader = window.loadProjectsFromSupabase;
      if (!loader) { window.toastError && window.toastError('loadProjectsFromSupabase לא זמין — יש לרענן'); setSyncing(false); return; }
      const projs = await loader();
      if (projs && projs.length) {
        localStorage.setItem('ybp_user_projects', JSON.stringify(projs));
        window.toastSuccess && window.toastSuccess(`נטענו ${projs.length} פרויקטים מ-Supabase. רענן את הדף.`);
      } else {
        window.toastError && window.toastError('לא הצליח לטעון פרויקטים — בדוק חיבור לSupabase');
      }
    } catch (e) {
      window.toastError && window.toastError('שגיאה: ' + e.message);
    } finally { setSyncing(false); }
  };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <SectionHeader icon="🔄" title="סנכרון פרויקטים" subtitle="טעינה ידנית של פרויקטים מ-Supabase (גיבוי אם הטעינה האוטומטית נכשלת)" />
      <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
        <button onClick={handleSync} disabled={syncing} style={{
          padding: '10px 22px', borderRadius: 8, border: 'none', cursor: syncing ? 'not-allowed' : 'pointer',
          background: syncing ? '#9ca3af' : '#2563eb', color: '#fff', fontSize: 14, fontWeight: 700,
          fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 8,
        }}>
          {syncing ? 'מסנכרן...' : '🔄 סנכרן פרויקטים מ-Supabase'}
        </button>
        <span style={{ fontSize: 12, color: '#6b7280' }}>
          לאחר הסנכרון יש לרענן את הדף (Ctrl+F5)
        </span>
      </div>
    </div>
  );
}

function WebhooksSection({ settings, onChange }) {
  const [saved, setSaved] = useState(null); // key of saved webhook
  const [secretSaved, setSecretSaved] = useState(false);
  const w = settings.webhooks || {};

  const setUrl = (key, url) => {
    onChange('webhooks', { ...w, [key]: url });
  };

  const handleSave = (key) => {
    setSaved(key);
    setTimeout(() => setSaved(null), 2000);
    window.toastSuccess && window.toastSuccess('Webhook נשמר ✓');
  };

  const handleSecretSave = () => {
    setSecretSaved(true);
    setTimeout(() => setSecretSaved(false), 2000);
    window.toastSuccess && window.toastSuccess('מפתח אבטחה נשמר ✓');
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <SectionHeader icon="🔗" title="Make Webhooks" subtitle="הכנס את ה-URLs מ-Make.com — כל webhook מחבר פיצ'ר לאוטומציה" />

      <div style={{
        padding: '12px 16px', borderRadius: 8,
        background: '#fffbeb', border: '1px solid #fde68a',
        fontSize: 13, color: '#92400e', display: 'flex', gap: 8, alignItems: 'flex-start',
      }}>
        <span style={{ fontSize: 16, flexShrink: 0 }}>⚡</span>
        <div>
          <strong>איך מחברים?</strong> ב-Make.com — צור Scenario → הוסף Webhook trigger → העתק URL והדבק כאן.
          הקבצים שצריך לחבר מצוינים ליד כל webhook.
        </div>
      </div>

      {/* Security Key */}
      <div style={{ background: '#f0fdf4', border: '1.5px solid #bbf7d0', borderRadius: 10, padding: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontSize: 18 }}>🔒</span>
          <div>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#14532d' }}>מפתח אבטחה</div>
            <div style={{ fontSize: 11, color: '#16a34a' }}>נשלח עם כל בקשה ל-Make — חייב להתאים לפילטר ב-Scenarios</div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <input
            style={{ ...inp, fontSize: 12, flex: 1, direction: 'ltr', fontFamily: 'monospace', padding: '8px 10px' }}
            type="password"
            value={w._securityKey || ''}
            onChange={e => onChange('webhooks', { ...w, _securityKey: e.target.value })}
            placeholder="הכנס מפתח אבטחה מ-Make..."
          />
          <button onClick={handleSecretSave} style={{
            padding: '8px 14px', borderRadius: 7, border: 'none', cursor: 'pointer',
            background: secretSaved ? '#16a34a' : '#15803d',
            color: '#fff', fontSize: 12, fontWeight: 700, fontFamily: 'Assistant, sans-serif',
            transition: 'background .3s', whiteSpace: 'nowrap', flexShrink: 0,
          }}>
            {secretSaved ? '✓' : 'שמור'}
          </button>
        </div>
      </div>

      {WEBHOOK_CATS.map(cat => (
        <div key={cat} style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8,
            paddingBottom: 8, borderBottom: '1.5px solid var(--ybp-border,#e5e7eb)',
          }}>
            <span style={{ fontSize: 18 }}>{CAT_ICONS[cat]}</span>
            <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>{cat}</span>
          </div>
          {WEBHOOKS.filter(wh => wh.cat === cat).map(wh => (
            <div key={wh.key} style={{
              background: 'var(--ybp-row-hover,#f9fafb)', borderRadius: 8, padding: 12,
              border: '1px solid var(--ybp-border,#e5e7eb)',
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 8 }}>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>{wh.label}</div>
                  <div style={{ fontSize: 11, color: 'var(--ybp-ink-faint,#6b7280)', marginTop: 2 }}>{wh.desc}</div>
                </div>
                <span style={{
                  fontSize: 10, padding: '2px 7px', borderRadius: 99, fontWeight: 600,
                  background: w[wh.key] ? '#f0fdf4' : '#f9fafb',
                  color: w[wh.key] ? '#16a34a' : '#9ca3af',
                  border: `1px solid ${w[wh.key] ? '#bbf7d0' : '#e5e7eb'}`,
                  whiteSpace: 'nowrap', flexShrink: 0,
                }}>
                  {w[wh.key] ? '● מחובר' : '○ לא מחובר'}
                </span>
              </div>
              <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                <input
                  style={{ ...inp, fontSize: 12, flex: 1, direction: 'ltr', fontFamily: 'monospace', padding: '8px 10px' }}
                  value={w[wh.key] || ''}
                  onChange={e => setUrl(wh.key, e.target.value)}
                  placeholder={`https://hook.eu1.make.com/...`}
                />
                <button onClick={() => handleSave(wh.key)} style={{
                  padding: '8px 14px', borderRadius: 7, border: 'none', cursor: 'pointer',
                  background: saved === wh.key ? '#16a34a' : '#1a2c4a',
                  color: '#fff', fontSize: 12, fontWeight: 700, fontFamily: 'Assistant, sans-serif',
                  transition: 'background .3s', whiteSpace: 'nowrap', flexShrink: 0,
                }}>
                  {saved === wh.key ? '✓' : 'שמור'}
                </button>
              </div>
              <div style={{ fontSize: 10, color: '#9ca3af', marginTop: 5 }}>
                קובץ: <code style={{ background: '#f3f4f6', padding: '1px 5px', borderRadius: 3 }}>{wh.file}</code>
              </div>
            </div>
          ))}
        </div>
      ))}
    </div>
  );
}

// ── Section: התראות ──────────────────────────────────────────────────────────
function NotificationsSection({ settings, onChange }) {
  const [saved, setSaved] = useState(false);
  const n = settings.notifications || {};
  const set = (k, v) => onChange('notifications', { ...n, [k]: v });

  const handleSave = () => {
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
    window.toastSuccess && window.toastSuccess('הגדרות התראות נשמרו ✓');
  };

  const rows = [
    { key: 'taskDue',         label: 'תזכורת משימה קרובה',      sub: '24 שעות לפני תאריך יעד' },
    { key: 'rejectNew',       label: 'ריג׳קט חדש נוצר',          sub: 'בזמן אמת' },
    { key: 'quotePending',    label: 'הצעת מחיר ממתינה לאישור',  sub: 'מהרגע שמוגשת' },
    { key: 'paymentApproved', label: 'תשלום אושר ע"י לקוח',      sub: 'בזמן אמת' },
    { key: 'protocolNew',     label: 'פרוטוקול פגישה חדש',       sub: 'לאחר יצירה' },
    { key: 'tenderUpdate',    label: 'עדכון מכרז',               sub: 'שינוי סטטוס / הצעה חדשה' },
    { key: 'distOverdue',     label: 'תוכניות לא הופצו',         sub: 'תזכורת שבועית' },
  ];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <SectionHeader icon="🔔" title="התראות" subtitle="בחר אילו אירועים ישלחו התראה" />

      <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        {rows.map((r, i) => (
          <div key={r.key} style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '12px 14px', borderRadius: 8,
            background: i % 2 === 0 ? 'var(--ybp-row-hover,#f9fafb)' : 'transparent',
          }}>
            <div>
              <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ybp-ink,#111827)' }}>{r.label}</div>
              <div style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)' }}>{r.sub}</div>
            </div>
            <ToggleSwitch checked={n[r.key] !== false} onChange={v => set(r.key, v)} />
          </div>
        ))}
      </div>

      <div style={{ padding: '12px 16px', borderRadius: 8, background: '#eff6ff', border: '1px solid #bfdbfe', fontSize: 13, color: '#1e40af' }}>
        🔔 <strong>Push Notifications</strong> יופעלו בייצור — Supabase Real-time + Service Worker
      </div>

      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <SaveBtn onClick={handleSave} saved={saved} />
      </div>
    </div>
  );
}

// ── Section: קישורי גישה ──────────────────────────────────────────────────────
function AccessSection({ settings, onChange }) {
  const projects = (() => {
    const ybp = (window.YBP_DATA && Array.isArray(window.YBP_DATA.projects)) ? window.YBP_DATA.projects : [];
    if (ybp.length) return ybp;
    const sync = window.SyncStore?.get?.()?.projects;
    if (Array.isArray(sync) && sync.length) return sync;
    try { const u = JSON.parse(localStorage.getItem('ybp_user_projects') || '[]'); if (Array.isArray(u) && u.length) return u; } catch {}
    return [];
  })();
  const [selectedProject, setSelectedProject] = useState(projects[0]?.id || '');
  const [clientCopied, setClientCopied] = useState(false);
  const [contractorName, setContractorName] = useState('');
  const [generatedLink, setGeneratedLink] = useState(null);
  const [contractorCopied, setContractorCopied] = useState(false);

  // v3.9.0.45 — origin דינמי במקום domain קשיח, וקישורים על השורש (?p / ?t)
  const baseUrl = window.location.origin;

  // לינק לקוח — קבוע לפי פרויקט
  const clientLink = `${baseUrl}/?p=${selectedProject}`;

  const copyClient = () => {
    navigator.clipboard?.writeText(clientLink).catch(() => {});
    setClientCopied(true);
    setTimeout(() => setClientCopied(false), 2000);
  };

  // לינק קבלן — JWT (async HMAC-SHA256)
  const generateContractor = async () => {
    if (!contractorName.trim()) return;
    setGeneratedLink('מייצר...');
    try {
      const token = await window.YBP_AUTH.generateContractorToken(contractorName.trim(), selectedProject);
      setGeneratedLink(`${baseUrl}/?t=${token}`);
    } catch (_) {
      // v3.9.0.45 — payload תואם ל-generateContractorToken: pid (לא p), role, iat/exp בשניות
      const nowSec = Math.floor(Date.now() / 1000);
      const fakeToken = btoa(JSON.stringify({
        sub: contractorName, pid: selectedProject, role: 'contractor',
        iat: nowSec, exp: nowSec + 7 * 24 * 3600,
      }));
      setGeneratedLink(`${baseUrl}/?t=${fakeToken}`);
    }
  };

  const copyContractor = () => {
    if (!generatedLink) return;
    navigator.clipboard?.writeText(generatedLink).catch(() => {});
    setContractorCopied(true);
    setTimeout(() => setContractorCopied(false), 2000);
  };

  const resetContractor = () => {
    setGeneratedLink(null);
    setContractorName('');
    setContractorCopied(false);
  };

  const cardStyle = {
    background: 'var(--ybp-card-bg,#fff)',
    border: '1px solid var(--ybp-border,#e5e7eb)',
    borderRadius: 12, padding: 20, marginBottom: 16,
  };
  const labelSt = { fontSize: 12, fontWeight: 700, color: 'var(--ybp-ink-soft,#374151)', letterSpacing: 0.3, display: 'block', marginBottom: 6 };
  const inpSt = { width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid var(--ybp-border,#e5e7eb)', fontSize: 14, fontFamily: 'Assistant, sans-serif', background: 'var(--ybp-input-bg,#fff)', color: 'var(--ybp-ink,#111827)', outline: 'none', boxSizing: 'border-box', direction: 'rtl' };

  return (
    <div>
      <h2 style={{ margin: '0 0 6px', fontSize: 20, fontWeight: 800, color: 'var(--ybp-ink,#111827)' }}>🔑 קישורי גישה</h2>
      <p style={{ margin: '0 0 20px', fontSize: 14, color: 'var(--ybp-ink-soft,#6b7280)' }}>
        צור לינקים ללקוחות וקבלנים — כל לינק מאפשר גישה לפרויקט ספציפי בלבד
      </p>

      {/* JWT Secret */}
      <div style={{ ...cardStyle, background: 'var(--ybp-bg,#f6f7f9)', border: '1.5px solid #1a2c4a22' }}>
        <label style={{ ...labelSt, color: '#1a2c4a' }}>🔐 JWT Secret (לחתימת קישורי קבלן)</label>
        <input
          type="password"
          value={settings.jwtSecret || ''}
          onChange={e => onChange && onChange('jwtSecret', e.target.value)}
          placeholder="הכנס Supabase JWT Secret — נשמר רק בדפדפן"
          style={{ ...inpSt, marginBottom: 4, letterSpacing: settings.jwtSecret ? 2 : 0 }}
        />
        <div style={{ fontSize: 11, color: '#6b7280' }}>
          {settings.jwtSecret
            ? '✅ Secret מוגדר — קישורים יחתמו ב-HMAC-SHA256 אמיתי'
            : '⚠️ ללא secret — קישורים לא יהיו מאובטחים לייצור'}
        </div>
      </div>

      {/* בחירת פרויקט */}
      <div style={cardStyle}>
        <label style={labelSt}>פרויקט</label>
        <select value={selectedProject} onChange={e => { setSelectedProject(e.target.value); setGeneratedLink(null); }} style={{ ...inpSt, cursor: 'pointer' }}>
          {projects.map(p => (
            <option key={p.id} value={p.id}>{p.name}</option>
          ))}
        </select>
      </div>

      {/* לינק לקוח */}
      <div style={cardStyle}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
          <div>
            <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>🏢 לינק פורטל לקוח</div>
            <div style={{ fontSize: 12, color: 'var(--ybp-ink-soft,#6b7280)', marginTop: 2 }}>קישור קבוע — הלקוח רואה דוחות, תשלומים והתקדמות</div>
          </div>
        </div>
        <div style={{ background: 'var(--ybp-bg,#f6f7f9)', border: '1px solid var(--ybp-border,#e5e7eb)', borderRadius: 8, padding: '10px 14px', fontSize: 12, color: 'var(--ybp-ink-soft,#374151)', wordBreak: 'break-all', direction: 'ltr', textAlign: 'left', fontFamily: 'monospace', marginBottom: 10 }}>
          {clientLink}
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={copyClient} style={{
            padding: '9px 18px', borderRadius: 8, border: 'none', cursor: 'pointer',
            background: clientCopied ? '#16a34a' : '#1a2c4a', color: '#fff',
            fontSize: 13, fontWeight: 700, fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            {clientCopied ? '✓ הועתק!' : '📋 העתק לינק'}
          </button>
          <button onClick={() => window.open(clientLink, '_blank')} style={{
            padding: '9px 14px', borderRadius: 8, border: '1px solid var(--ybp-border,#e5e7eb)',
            background: 'transparent', color: 'var(--ybp-ink,#374151)',
            fontSize: 13, cursor: 'pointer', fontFamily: 'inherit',
          }}>
            🔗 פתח
          </button>
        </div>
      </div>

      {/* לינק קבלן */}
      <div style={cardStyle}>
        <div style={{ marginBottom: 12 }}>
          <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>🦺 לינק לוח קבלן</div>
          <div style={{ fontSize: 12, color: 'var(--ybp-ink-soft,#6b7280)', marginTop: 2 }}>לינק מאובטח עם JWT — תוקף 7 ימים — הקבלן רואה משימות וריג׳קטים שלו</div>
        </div>

        {!generatedLink ? (
          <div>
            <label style={labelSt}>שם הקבלן</label>
            <div style={{ display: 'flex', gap: 8 }}>
              <input
                value={contractorName}
                onChange={e => setContractorName(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && generateContractor()}
                placeholder="לדוגמה: אבי כהן"
                style={{ ...inpSt, flex: 1 }}
              />
              <button onClick={generateContractor} disabled={!contractorName.trim()} style={{
                padding: '10px 18px', borderRadius: 8, border: 'none',
                background: contractorName.trim() ? '#1a2c4a' : '#e5e7eb',
                color: contractorName.trim() ? '#fff' : '#9ca3af',
                fontSize: 13, fontWeight: 700, cursor: contractorName.trim() ? 'pointer' : 'not-allowed',
                fontFamily: 'inherit', flexShrink: 0,
              }}>
                🔑 צור לינק
              </button>
            </div>
          </div>
        ) : (
          <div>
            <div style={{ background: '#f0fdf4', border: '1px solid #bbf7d0', borderRadius: 8, padding: '10px 14px', marginBottom: 10 }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: '#16a34a', marginBottom: 4 }}>✅ לינק נוצר — תוקף 7 ימים</div>
              <div style={{ fontSize: 11, color: '#15803d' }}>קבלן: {contractorName} | פרויקט: {projects.find(p=>p.id===selectedProject)?.name}</div>
            </div>
            <div style={{ background: 'var(--ybp-bg,#f6f7f9)', border: '1px solid var(--ybp-border,#e5e7eb)', borderRadius: 8, padding: '10px 14px', fontSize: 11, color: 'var(--ybp-ink-soft,#374151)', wordBreak: 'break-all', direction: 'ltr', textAlign: 'left', fontFamily: 'monospace', marginBottom: 10 }}>
              {generatedLink.slice(0, 60)}…
            </div>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              <button onClick={copyContractor} style={{
                padding: '9px 18px', borderRadius: 8, border: 'none', cursor: 'pointer',
                background: contractorCopied ? '#16a34a' : '#1a2c4a', color: '#fff',
                fontSize: 13, fontWeight: 700, fontFamily: 'inherit',
              }}>
                {contractorCopied ? '✓ הועתק!' : '📋 העתק לינק'}
              </button>
              <button onClick={resetContractor} style={{
                padding: '9px 14px', borderRadius: 8, border: '1px solid #fca5a5',
                background: '#fff', color: '#dc2626',
                fontSize: 13, cursor: 'pointer', fontFamily: 'inherit',
              }}>
                🔄 חדש לינק
              </button>
              <button onClick={() => {
                const wa = `https://wa.me/?text=${encodeURIComponent(`שלום ${contractorName},\nהנה הלינק שלך ללוח הקבלן:\n${generatedLink}\n\nתוקף: 7 ימים`)}`;
                window.open(wa, '_blank');
              }} style={{
                padding: '9px 14px', borderRadius: 8, border: '1px solid #e5e7eb',
                background: '#fff', color: '#16a34a',
                fontSize: 13, cursor: 'pointer', fontFamily: 'inherit',
              }}>
                📱 שלח ב-WhatsApp
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ── Section: Google Drive ──────────────────────────────────────────────────────
function DriveSection({ settings, onChange, session }) {
  const { isMobile } = useViewport();
  const [saved, setSaved] = useState(false);
  const d = settings.drive || {};
  const set = (k, v) => onChange('drive', { ...d, [k]: v });

  const handleSave = () => {
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
    window.toastSuccess && window.toastSuccess('הגדרות Drive נשמרו ✓');
  };

  // טען folder IDs — עם fallback לSyncStore ו-localStorage (Phase 1B)
  const projects = (() => {
    const ybpProjects = (window.YBP_DATA && Array.isArray(window.YBP_DATA.projects)) ? window.YBP_DATA.projects : [];
    if (ybpProjects.length) return ybpProjects;
    const syncProjects = window.SyncStore?.get?.()?.projects;
    if (Array.isArray(syncProjects) && syncProjects.length) return syncProjects;
    try {
      const userProjects = JSON.parse(localStorage.getItem('ybp_user_projects') || '[]');
      if (Array.isArray(userProjects) && userProjects.length) return userProjects;
    } catch {}
    return [];
  })();

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <SectionHeader icon="☁️" title="Google Drive" subtitle="הגדר תיקיות Drive לכל פרויקט" />

      <div style={{
        padding: '12px 16px', borderRadius: 8, background: '#f0fdf4',
        border: '1px solid #bbf7d0', fontSize: 13, color: '#15803d',
        display: 'flex', gap: 8,
      }}>
        <span style={{ fontSize: 16, flexShrink: 0 }}>📁</span>
        <div>
          ה-Folder ID נמצא בכתובת Google Drive:
          <code style={{ display: 'block', marginTop: 4, padding: '4px 8px', background: 'rgba(0,0,0,0.05)', borderRadius: 4, fontSize: 11, direction: 'ltr' }}>
            https://drive.google.com/drive/folders/<strong>FOLDER_ID_HERE</strong>
          </code>
        </div>
      </div>

      <Field label="תיקיית שורש — YBPROJECTS" hint="תיקיית הבסיס של כל הפרויקטים ב-Drive">
        <input style={{ ...inp, direction: 'ltr', fontFamily: 'monospace' }}
          value={d.rootFolderId || ''}
          onChange={e => set('rootFolderId', e.target.value)}
          placeholder="1ABC...xyz" />
      </Field>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ybp-ink-soft,#374151)', letterSpacing: 0.3, paddingBottom: 6, borderBottom: '1.5px solid var(--ybp-border,#e5e7eb)' }}>
          תיקיות לפי פרויקט
        </div>
        {projects.map(proj => {
          const folders = settings.driveFolders || {};
          const storedFolderId = folders[proj.id] || '';
          return (
            <div key={proj.id} style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: isMobile ? 'wrap' : 'nowrap' }}>
              <div style={{ width: isMobile ? '100%' : 120, fontSize: 13, fontWeight: 600, color: 'var(--ybp-ink,#111827)', flexShrink: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {proj.name}
              </div>
              <input
                style={{ ...inp, flex: 1, direction: 'ltr', fontFamily: 'monospace', fontSize: 12, padding: '8px 10px' }}
                defaultValue={storedFolderId}
                onBlur={e => {
                  const raw = e.target.value.trim()
                    .replace(/.*\/folders\/([a-zA-Z0-9_-]+).*/,'$1')
                    .replace(/[^a-zA-Z0-9_-]/g,'');
                  if (raw) onChange('driveFolders', { ...(settings.driveFolders || {}), [proj.id]: raw });
                }}
                placeholder="Folder ID או קישור Drive..."
              />
              {storedFolderId && (
                <button onClick={() => {
                  const email = session?.user?.email || '';
                  const authParam = email ? `?authuser=${encodeURIComponent(email)}` : '';
                  window.open(`https://drive.google.com/drive/folders/${storedFolderId}${authParam}`, '_blank');
                }}
                  style={{ padding:'8px 12px', borderRadius:7, border:'1px solid var(--ybp-border,#e5e7eb)', background:'var(--ybp-panel,#fff)', cursor:'pointer', fontSize:13, flexShrink:0, color:'var(--ybp-ink,#111827)' }}>
                  🔗
                </button>
              )}
            </div>
          );
        })}
      </div>

      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <SaveBtn onClick={handleSave} saved={saved} />
      </div>
    </div>
  );
}

// ── Shared UI helpers ─────────────────────────────────────────────────────────
function AuthSection({ settings, onChange }) {
  const [saved, setSaved] = useState(false);
  const clientId = settings.googleClientId || '';

  const handleSave = () => {
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
    window.toastSuccess && window.toastSuccess('Google Client ID נשמר ✓');
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <SectionHeader icon="🔐" title="Google OAuth" subtitle="הגדרת כניסה עם חשבון Google" />

      <div style={{ padding: '12px 16px', borderRadius: 8, background: '#eff6ff', border: '1px solid #bfdbfe', fontSize: 13, color: '#1d4ed8', display: 'flex', gap: 8 }}>
        <span style={{ fontSize: 16, flexShrink: 0 }}>ℹ️</span>
        <div style={{ lineHeight: 1.6 }}>
          <strong>איך מקבלים Client ID:</strong><br />
          1. כנס ל-console.cloud.google.com<br />
          2. APIs &amp; Services → Credentials → Create → OAuth 2.0 Client ID<br />
          3. Application type: <strong>Web application</strong><br />
          4. Authorized JavaScript origins: <code style={{ background: 'rgba(0,0,0,0.07)', padding: '1px 5px', borderRadius: 3, fontSize: 11 }}>https://ybp-reports.pages.dev</code><br />
          5. העתק את ה-Client ID והדבק למטה
        </div>
      </div>

      <Field label="Google OAuth Client ID" hint="נראה כמו: 123456789-abc.apps.googleusercontent.com">
        <input
          style={{ width: '100%', padding: '10px 12px', borderRadius: 8, border: '1px solid var(--ybp-border,#e5e7eb)', fontSize: 13, fontFamily: 'monospace', direction: 'ltr', boxSizing: 'border-box', background: 'var(--ybp-input-bg,#fff)', color: 'var(--ybp-ink,#111827)', outline: 'none' }}
          value={clientId}
          onChange={e => onChange('googleClientId', e.target.value)}
          placeholder="123456789-xxxxxxxxxxxx.apps.googleusercontent.com"
          dir="ltr"
        />
      </Field>

      {clientId && (
        <div style={{ padding: '10px 14px', borderRadius: 8, background: '#f0fdf4', border: '1px solid #bbf7d0', fontSize: 12, color: '#15803d', display: 'flex', gap: 8 }}>
          <span>✅</span>
          <span>Client ID מוגדר — כניסה עם Google פעילה</span>
        </div>
      )}

      <button onClick={handleSave} style={{
        padding: '11px 24px', borderRadius: 9, border: 'none', alignSelf: 'flex-start',
        background: saved ? '#16a34a' : '#1a2c4a', color: '#fff',
        fontSize: 14, fontWeight: 700, cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
        transition: 'background 0.2s',
      }}>
        {saved ? '✅ נשמר!' : 'שמור'}
      </button>
    </div>
  );
}

function SectionHeader({ icon, title, subtitle }) {
  return (
    <div style={{ paddingBottom: 16, borderBottom: '2px solid var(--ybp-border,#e5e7eb)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <span style={{ fontSize: 22 }}>{icon}</span>
        <h2 style={{ margin: 0, fontSize: 20, fontWeight: 800, color: 'var(--ybp-ink,#111827)', fontFamily: 'Assistant, sans-serif' }}>{title}</h2>
      </div>
      {subtitle && <p style={{ margin: '6px 0 0 32px', fontSize: 13, color: 'var(--ybp-ink-faint,#6b7280)' }}>{subtitle}</p>}
    </div>
  );
}

function TabBtn({ active, onClick, children }) {
  return (
    <button onClick={onClick} style={{
      padding: '7px 16px', borderRadius: 7, border: 'none', cursor: 'pointer',
      fontFamily: 'Assistant, sans-serif', fontSize: 13, fontWeight: 600,
      background: active ? '#1a2c4a' : 'var(--ybp-row-hover,#f3f4f6)',
      color: active ? '#fff' : 'var(--ybp-ink-soft,#374151)',
      transition: 'all .15s',
    }}>{children}</button>
  );
}

function ToggleSwitch({ checked, onChange }) {
  return (
    <button
      onClick={() => onChange(!checked)}
      style={{
        width: 44, height: 24, borderRadius: 12, border: 'none', cursor: 'pointer',
        background: checked ? '#1a2c4a' : '#d1d5db',
        position: 'relative', transition: 'background .2s', flexShrink: 0, padding: 0,
      }}
    >
      <span style={{
        position: 'absolute', top: 3, borderRadius: '50%',
        width: 18, height: 18, background: '#fff',
        transition: 'right .2s, left .2s',
        right: checked ? 3 : undefined,
        left: checked ? undefined : 3,
        boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
      }} />
    </button>
  );
}

// ── Section: ניהול משתמשים ────────────────────────────────────────────────────
function UserManagementSection({ session }) {
  const [users, setUsers] = useState([]);
  const [roles, setRoles] = useState({});
  const [saving, setSaving] = useState(null);

  const SUPER_ADMIN_EMAIL = 'yuval@ybprojects.com';

  const refreshRoles = () => {
    try {
      const fromSettings = loadSettings().userRoles || {};
      const fromLocal = JSON.parse(localStorage.getItem('ybp_user_roles') || '{}');
      setRoles({ ...fromLocal, ...fromSettings });
    } catch {}
  };

  useEffect(() => {
    // טען מ-Supabase profiles (מקור אמת — כל המשתמשים)
    const loadUsers = async () => {
      try {
        if (window.YBP_SUPABASE) {
          const sb = await window.YBP_SUPABASE.getClient();
          const { data, error } = await sb.from('profiles').select('id, email, full_name, role').order('full_name');
          if (!error && data && data.length > 0) {
            setUsers(data.map(u => ({ id: u.id, email: u.email, name: u.full_name || u.email })));
            return;
          }
        }
      } catch (e) { console.warn('[UserMgmt] Supabase load failed:', e.message); }
      // fallback: localStorage
      const known = window.YBP_AUTH?.getKnownUsers?.() || [];
      setUsers(known);
    };
    loadUsers();
    refreshRoles();
    const onSync = () => refreshRoles();
    window.addEventListener('ybp-settings-changed', onSync);
    return () => window.removeEventListener('ybp-settings-changed', onSync);
  }, []);

  const getRole = (email) => {
    if (email === SUPER_ADMIN_EMAIL) return 'admin';
    return roles[email] || 'pm';
  };

  const handleRoleChange = (email, newRole) => {
    window.YBP_AUTH?.setUserRole?.(email, newRole);
    const updated = { ...roles, [email]: newRole };
    setRoles(updated);
    // mirror to settings for cloud sync
    const current = loadSettings();
    saveSettings({ ...current, userRoles: updated });
    setSaving(email);
    window.toastSuccess && window.toastSuccess('הרשאה עודכנה ✓');
    setTimeout(() => setSaving(null), 2000);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <SectionHeader icon="👥" title="ניהול משתמשים" subtitle="הגדר תפקידים לכל משתמש שנכנס למערכת" />

      <div style={{ padding: '12px 16px', borderRadius: 8, background: '#eff6ff', border: '1px solid #bfdbfe', fontSize: 13, color: '#1d4ed8', display: 'flex', gap: 8 }}>
        <span style={{ flexShrink: 0 }}>ℹ️</span>
        <div>משתמשים מופיעים כאן לאחר כניסתם הראשונה. שינוי תפקיד ייכנס לתוקף בכניסה הבאה שלהם.</div>
      </div>

      {users.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '40px 20px', color: '#9ca3af', fontSize: 14 }}>
          <div style={{ fontSize: 36, marginBottom: 12 }}>👤</div>
          <div>אין משתמשים רשומים עדיין</div>
          <div style={{ fontSize: 12, marginTop: 6 }}>משתמשים יופיעו כאן לאחר כניסתם הראשונה למערכת</div>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {users.map(u => {
            const role = getRole(u.email);
            const isSuperAdmin = u.email === SUPER_ADMIN_EMAIL;
            return (
              <div key={u.email} style={{
                display: 'flex', alignItems: 'center', gap: 14,
                padding: '14px 16px', borderRadius: 10,
                background: 'var(--ybp-row-hover,#f9fafb)',
                border: '1px solid var(--ybp-border,#e5e7eb)',
              }}>
                <div style={{
                  width: 40, height: 40, borderRadius: '50%', flexShrink: 0,
                  background: role === 'admin' ? '#1a2c4a' : '#0369a1',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 14, fontWeight: 700, color: '#fff',
                }}>{u.avatar || '?'}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>{u.name}</div>
                  <div style={{ fontSize: 12, color: '#6b7280' }}>{u.email}</div>
                  {u.lastLogin && (
                    <div style={{ fontSize: 11, color: '#9ca3af', marginTop: 1 }}>
                      כניסה אחרונה: {new Date(u.lastLogin).toLocaleDateString('he-IL')}
                    </div>
                  )}
                </div>
                {isSuperAdmin ? (
                  <div style={{ padding: '5px 12px', borderRadius: 6, background: '#1a2c4a', color: '#b5a882', fontSize: 12, fontWeight: 700, flexShrink: 0 }}>
                    🔑 Super Admin
                  </div>
                ) : (
                  <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
                    {['admin', 'pm'].map(r => (
                      <button key={r} onClick={() => handleRoleChange(u.email, r)} style={{
                        padding: '6px 14px', borderRadius: 7, border: 'none', cursor: 'pointer',
                        fontFamily: 'Assistant, sans-serif', fontSize: 12, fontWeight: 700,
                        background: role === r ? (r === 'admin' ? '#1a2c4a' : '#0369a1') : '#f3f4f6',
                        color: role === r ? '#fff' : '#374151',
                        transition: 'all .15s',
                      }}>
                        {r === 'admin' ? 'Admin' : 'PM'}
                      </button>
                    ))}
                  </div>
                )}
                {saving === u.email && (
                  <span style={{ fontSize: 14, color: '#16a34a', flexShrink: 0 }}>✅</span>
                )}
              </div>
            );
          })}
        </div>
      )}

      <div style={{ padding: '12px 16px', borderRadius: 8, background: '#fefce8', border: '1px solid #fde68a', fontSize: 12, color: '#92400e' }}>
        ⚠️ שינוי תפקיד ייכנס לתוקף בכניסה הבאה של המשתמש
      </div>
    </div>
  );
}

// ── Main SettingsScreen ───────────────────────────────────────────────────────
function SettingsScreen({ onBack, session }) {
  const role = session?.role || 'viewer';
  const isAdmin = role === 'admin';
  const sections = isAdmin ? SECTIONS_ADMIN : SECTIONS_PM;

  const [active, setActive] = useState(sections[0].id);
  const [settings, setSettings] = useState(() => loadSettings());
  const isRemoteUpdate = useRef(false);

  // שמירה אוטומטית בכל שינוי — דלג אם השינוי הגיע מהענן (למנוע לולאה)
  useEffect(() => {
    if (isRemoteUpdate.current) { isRemoteUpdate.current = false; return; }
    saveSettings(settings);
  }, [settings]);

  // האזנה לעדכוני ענן (polling / מכשיר אחר)
  useEffect(() => {
    const onRemote = (e) => {
      isRemoteUpdate.current = true;
      setSettings(e.detail || loadSettings());
    };
    window.addEventListener('ybp-settings-changed', onRemote);
    return () => window.removeEventListener('ybp-settings-changed', onRemote);
  }, []);

  const onChange = useCallback((section, data) => {
    setSettings(prev => ({ ...prev, [section]: data }));
  }, []);

  const renderSection = () => {
    switch (active) {
      case 'profile':      return <ProfileSection      settings={settings} onChange={onChange} session={session} />;
      case 'signature':    return <SignatureSection     settings={settings} onChange={onChange} />;
      case 'company':      return <CompanySection       settings={settings} onChange={onChange} />;
      case 'access':       return <AccessSection        settings={settings} onChange={onChange} />;
      case 'webhooks':     return <WebhooksSection      settings={settings} onChange={onChange} />;
      case 'sync':         return <SyncSection />;
      case 'notifications':return <NotificationsSection settings={settings} onChange={onChange} />;
      case 'drive':        return <DriveSection         settings={settings} onChange={onChange} session={session} />;
      case 'auth':         return <AuthSection          settings={settings} onChange={onChange} />;
      case 'users':        return <UserManagementSection session={session} />;
      default: return null;
    }
  };

  // מספר webhooks מחוברים
  const connectedWebhooks = Object.values(settings.webhooks || {}).filter(Boolean).length;
  const { isMobile } = useViewport();

  return (
    <div style={{
      display: 'flex', flexDirection: 'column', height: '100%',
      background: 'var(--ybp-outer-bg,#f6f7f9)', fontFamily: 'Assistant, sans-serif',
      direction: 'rtl',
    }}>
      {/* Header */}
      <div style={{
        background: 'var(--ybp-panel,#fff)', borderBottom: '1.5px solid var(--ybp-border,#e5e7eb)',
        padding: '12px 20px', display: 'flex', alignItems: 'center', gap: 14, flexShrink: 0,
      }}>
        <button onClick={onBack} style={{
          background: 'none', border: '1.5px solid var(--ybp-border,#e5e7eb)',
          borderRadius: 8, padding: '7px 14px', cursor: 'pointer',
          fontSize: 13, fontWeight: 700, color: 'var(--ybp-ink,#111827)',
          fontFamily: 'Assistant, sans-serif', display: 'flex', alignItems: 'center', gap: 6,
        }}>
          ← חזרה
        </button>
        <h1 style={{ margin: 0, fontSize: 18, fontWeight: 800, color: 'var(--ybp-ink,#111827)' }}>⚙️ הגדרות</h1>
        {!isAdmin && (
          <span style={{ fontSize: 12, padding: '3px 10px', borderRadius: 99, background: '#eff6ff', color: '#2563eb', fontWeight: 600 }}>
            PM — גישה חלקית
          </span>
        )}
      </div>

      {/* Body */}
      <div style={{ display: 'flex', flex: 1, overflow: 'hidden', flexDirection: isMobile ? 'column' : 'row' }}>

        {/* Sidebar — desktop only */}
        {!isMobile && (
          <div style={{
            width: 220, flexShrink: 0,
            background: 'var(--ybp-panel,#fff)',
            borderLeft: '1.5px solid var(--ybp-border,#e5e7eb)',
            padding: '16px 12px', display: 'flex', flexDirection: 'column', gap: 4,
            overflowY: 'auto',
          }}>
            {sections.map(sec => (
              <button key={sec.id} onClick={() => setActive(sec.id)} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '10px 12px', borderRadius: 8, border: 'none', cursor: 'pointer',
                background: active === sec.id ? '#1a2c4a' : 'transparent',
                color: active === sec.id ? '#fff' : 'var(--ybp-ink,#111827)',
                fontFamily: 'Assistant, sans-serif', fontSize: 14, fontWeight: active === sec.id ? 700 : 500,
                textAlign: 'right', width: '100%', transition: 'all .15s',
              }}
              onMouseEnter={e => { if (active !== sec.id) e.currentTarget.style.background = 'var(--ybp-row-hover,#f3f4f6)'; }}
              onMouseLeave={e => { if (active !== sec.id) e.currentTarget.style.background = 'transparent'; }}
              >
                <span style={{ fontSize: 18, width: 24, textAlign: 'center', flexShrink: 0 }}>{sec.icon}</span>
                <span style={{ flex: 1 }}>{sec.label}</span>
                {sec.id === 'webhooks' && connectedWebhooks > 0 && (
                  <span style={{ fontSize: 10, padding: '1px 6px', borderRadius: 99, background: active === 'webhooks' ? 'rgba(255,255,255,0.2)' : '#f0fdf4', color: active === 'webhooks' ? '#fff' : '#16a34a', fontWeight: 700 }}>
                    {connectedWebhooks}
                  </span>
                )}
              </button>
            ))}

            {/* Admin badge */}
            {isAdmin && (
              <div style={{ marginTop: 'auto', padding: '10px 12px', borderRadius: 8, background: '#f5f3ff', border: '1px solid #ddd6fe' }}>
                <div style={{ fontSize: 11, color: '#7c3aed', fontWeight: 700 }}>Admin</div>
                <div style={{ fontSize: 10, color: '#8b5cf6', marginTop: 2 }}>גישה מלאה לכל ההגדרות</div>
              </div>
            )}
          </div>
        )}

        {/* Mobile tabs nav */}
        {isMobile && (
          <nav style={{
            display: 'flex', gap: 6, overflowX: 'auto',
            padding: '8px 12px', background: 'var(--ybp-panel,#fff)',
            borderBottom: '1px solid var(--ybp-border,#e5e7eb)',
            position: 'sticky', top: 0, zIndex: 5,
            WebkitOverflowScrolling: 'touch',
            scrollbarWidth: 'none',
          }}>
            {sections.map(sec => (
              <button key={sec.id} onClick={() => setActive(sec.id)} style={{
                flexShrink: 0, padding: '8px 14px', borderRadius: 8,
                border: active === sec.id ? '1.5px solid #1d4ed8' : '1px solid var(--ybp-border,#e5e7eb)',
                background: active === sec.id ? '#eff6ff' : 'var(--ybp-panel,#fff)',
                color: active === sec.id ? '#1d4ed8' : 'var(--ybp-ink-soft,#6b7280)',
                fontSize: 13, fontWeight: 600, fontFamily: 'Assistant, sans-serif',
                cursor: 'pointer', minHeight: 40, whiteSpace: 'nowrap',
              }}>
                {sec.icon} {sec.label}
              </button>
            ))}
          </nav>
        )}

        {/* Content */}
        <div style={{ flex: 1, overflowY: 'auto', padding: isMobile ? '16px 12px' : '28px 32px' }}>
          <div style={{
            maxWidth: 700, background: 'var(--ybp-panel,#fff)',
            borderRadius: 12, padding: isMobile ? 16 : 28,
            border: '1.5px solid var(--ybp-border,#e5e7eb)',
            boxShadow: '0 1px 4px rgba(0,0,0,0.04)',
          }}>
            {renderSection()}
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Export ────────────────────────────────────────────────────────────────────
Object.assign(window, { SettingsScreen, loadSettings });

})();
