// My Settings — personal profile & preferences accessible to ALL roles.
// Persisted per-user in localStorage under stagevo_user_prefs_<userId>.
// Theme change is applied immediately and overrides the org-wide setting.

function MyProfile({ currentUser, onUpdateUser, showToast, onThemeChange }) {
  const PREFS_KEY = 'stagevo_user_prefs_' + currentUser.id;

  const loadPrefs = () => {
    try { return JSON.parse(localStorage.getItem(PREFS_KEY) || '{}'); } catch { return {}; }
  };

  const [prefs, setPrefs] = React.useState(loadPrefs);
  const [tab, setTab] = React.useState('appearance');
  const [twofaOpen, setTwofaOpen] = React.useState(false);
  const [newPw, setNewPw] = React.useState('');
  const [confirmPw, setConfirmPw] = React.useState('');
  const [pwStatus, setPwStatus] = React.useState(null); // null | 'ok' | 'mismatch' | 'short' | 'error'
  const [pwLoading, setPwLoading] = React.useState(false);

  // Reload prefs if user switches in demo mode
  React.useEffect(() => { setPrefs(loadPrefs()); }, [currentUser.id]);

  // In live mode, reflect the real Supabase MFA enrolment state on load so the
  // toggle can't drift from what the auth server actually enforces.
  React.useEffect(() => {
    const isLive = !!(window.sb && window.STAGEVO_BACKEND === 'live' && window.sb.auth && window.sb.auth.mfa);
    if (!isLive) return;
    let alive = true;
    (async () => {
      try {
        const { data } = await window.sb.auth.mfa.listFactors();
        if (!alive) return;
        const verified = (data && data.all || []).find(f => f.factor_type === 'totp' && f.status === 'verified');
        updatePref(['security', 'twofaEnrolled'], !!verified);
        if (verified) updatePref(['security', 'twofaFactorId'], verified.id);
      } catch (e) {}
    })();
    return () => { alive = false; };
  }, [currentUser.id]);

  const updatePref = (keyOrPath, value) => {
    setPrefs(prev => {
      let next;
      if (Array.isArray(keyOrPath)) {
        next = { ...prev, [keyOrPath[0]]: { ...(prev[keyOrPath[0]] || {}), [keyOrPath[1]]: value } };
      } else {
        next = { ...prev, [keyOrPath]: value };
      }
      try { localStorage.setItem(PREFS_KEY, JSON.stringify(next)); } catch {}
      return next;
    });
  };

  const applyTheme = (themeId) => {
    updatePref('theme', themeId);
    onThemeChange && onThemeChange(themeId);
  };

  const changePassword = async () => {
    if (newPw.length < 8) { setPwStatus('short'); return; }
    if (newPw !== confirmPw) { setPwStatus('mismatch'); return; }
    setPwLoading(true); setPwStatus(null);
    try {
      if (window.sb) {
        const { error } = await window.sb.auth.updateUser({ password: newPw });
        setPwStatus(error ? 'error' : 'ok');
        if (!error) { setNewPw(''); setConfirmPw(''); showToast && showToast('Password updated successfully'); }
      } else {
        await new Promise(r => setTimeout(r, 700));
        setPwStatus('ok');
        setNewPw(''); setConfirmPw('');
        showToast && showToast('Password updated (live mode only)');
      }
    } catch { setPwStatus('error'); }
    setPwLoading(false);
  };

  const secPrefs = prefs.security || {};
  const notifPrefs = prefs.notifications || {};
  const currentTheme = prefs.theme || (window.DEFAULT_SETTINGS?.appearance?.theme) || 'pine';

  const TABS = [
    { id: 'appearance', label: 'Appearance', icon: 'tag' },
    { id: 'security', label: 'Security', icon: 'lock' },
    { id: 'notifications', label: 'Notifications', icon: 'alert' },
  ];

  const roleLabel = {
    admin: 'Administrator', leadership: 'Leadership (GM)',
    manager: 'Showroom Manager', sales_designer: 'Sales Designer',
  }[currentUser.role] || currentUser.role;

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '220px minmax(0,1fr)', gap: 20, alignItems: 'start' }}>

      {/* Left nav */}
      <nav style={{ position: 'sticky', top: 0, display: 'flex', flexDirection: 'column', gap: 2 }}>
        {/* Identity card */}
        <div className="card" style={{ padding: '14px 16px', marginBottom: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
            <span className="avatar lg" style={currentUser.avatarColor ? { background: currentUser.avatarColor } : null}>
              {currentUser.name.split(' ').map(s => s[0]).slice(0, 2).join('')}
            </span>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600, lineHeight: 1.3 }}>{currentUser.name}</div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>{currentUser.title || roleLabel}</div>
              {currentUser.email && (
                <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {currentUser.email}
                </div>
              )}
              <span className={`role-pill ${currentUser.role}`} style={{ marginTop: 5, display: 'inline-block' }}>
                {roleLabel}
              </span>
            </div>
          </div>
        </div>

        {TABS.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)}
            style={{
              display: 'flex', alignItems: 'center', gap: 9, padding: '8px 11px',
              borderRadius: 7, fontSize: 13, fontWeight: 500, textAlign: 'left',
              cursor: 'pointer', border: 'none',
              color: tab === t.id ? 'var(--ink)' : 'var(--ink-3)',
              background: tab === t.id ? 'var(--surface-3)' : 'transparent',
              transition: 'background 0.12s',
            }}
            onMouseEnter={e => { if (tab !== t.id) e.currentTarget.style.background = 'var(--surface-2)'; }}
            onMouseLeave={e => { if (tab !== t.id) e.currentTarget.style.background = 'transparent'; }}>
            <Icon name={t.icon} size={14}/> {t.label}
          </button>
        ))}

        <div style={{ marginTop: 12, padding: '10px 12px', background: 'var(--surface-2)', borderRadius: 8, fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.5 }}>
          <Icon name="alert" size={11}/> These settings apply only to your account and are saved per device.
        </div>
      </nav>

      {/* Right panel */}
      <div>

        {/* ── APPEARANCE ─────────────────────────────────────────────── */}
        {tab === 'appearance' && (
          <Panel title="Appearance" sub="Choose your personal theme — overrides the workspace default for your account">
            <div style={{ paddingTop: 8, paddingBottom: 4 }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-2)', marginBottom: 12, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Colour theme</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: 10 }}>
                {(window.THEMES || []).map(t => {
                  const on = currentTheme === t.id;
                  return (
                    <button key={t.id} onClick={() => applyTheme(t.id)}
                      style={{
                        textAlign: 'left', cursor: 'pointer', borderRadius: 10, padding: 13,
                        border: '1.5px solid ' + (on ? 'var(--accent)' : 'var(--border)'),
                        background: on ? 'var(--accent-soft)' : 'var(--surface)',
                        transition: 'border-color 0.12s, background 0.12s',
                      }}>
                      {/* Mini preview */}
                      <div style={{ height: 52, borderRadius: 7, overflow: 'hidden', border: '1px solid var(--border)', display: 'flex', marginBottom: 11 }}>
                        <div style={{ width: '33%', background: t.sidebar, display: 'flex', flexDirection: 'column', gap: 4, padding: '7px 6px' }}>
                          <span style={{ width: '80%', height: 5, borderRadius: 3, background: t.sidebarAccent }}></span>
                          <span style={{ width: '100%', height: 3, borderRadius: 2, background: 'rgba(255,255,255,0.25)' }}></span>
                          <span style={{ width: '70%', height: 3, borderRadius: 2, background: 'rgba(255,255,255,0.15)' }}></span>
                          <span style={{ width: '85%', height: 3, borderRadius: 2, background: 'rgba(255,255,255,0.15)' }}></span>
                        </div>
                        <div style={{ flex: 1, background: t.bg, padding: 7, display: 'flex', flexDirection: 'column', gap: 5 }}>
                          <span style={{ width: 42, height: 14, borderRadius: 6, background: t.accent }}></span>
                          <span style={{ width: '100%', height: 8, borderRadius: 3, background: '#fff' }}></span>
                          <span style={{ width: '75%', height: 8, borderRadius: 3, background: '#fff' }}></span>
                        </div>
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                        <span style={{ width: 12, height: 12, borderRadius: '50%', background: t.accent, flexShrink: 0 }}></span>
                        <span style={{ fontSize: 13, fontWeight: 600 }}>{t.name}</span>
                        {t.id === 'pine' && <span className="pill" style={{ fontSize: 9, padding: '1px 6px' }}>Default</span>}
                        {on && <Icon name="check" size={14} color="var(--accent)" style={{ marginLeft: 'auto' }}/>}
                      </div>
                      <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 4, lineHeight: 1.4 }}>{t.desc}</div>
                    </button>
                  );
                })}
              </div>
            </div>
          </Panel>
        )}

        {/* ── SECURITY ──────────────────────────────────────────────── */}
        {tab === 'security' && (
          <div>
            <Panel title="Two-factor authentication" sub="Protect your account with a one-time code every time you sign in">
              <SettingRow
                label="Authenticator app (2FA)"
                desc="Works with Google Authenticator, Microsoft Authenticator, Authy, or 1Password">
                {secPrefs.twofaEnrolled ? (
                  <React.Fragment>
                    <span className="pill" style={{ background: 'var(--won-soft)', color: 'oklch(0.4 0.1 155)' }}>
                      <Icon name="check" size={11}/> Active
                    </span>
                    <button className="btn sm" onClick={() => setTwofaOpen(true)}>Reconfigure</button>
                    <button className="btn sm" style={{ color: 'var(--lost)' }}
                      onClick={async () => {
                        if (!confirm('Disable authenticator 2FA? Your account will be less secure.')) return;
                        const isLive = !!(window.sb && window.STAGEVO_BACKEND === 'live' && window.sb.auth && window.sb.auth.mfa);
                        if (isLive) {
                          try {
                            const { data } = await window.sb.auth.mfa.listFactors();
                            const totp = (data && data.all || []).filter(f => f.factor_type === 'totp');
                            for (const f of totp) { try { await window.sb.auth.mfa.unenroll({ factorId: f.id }); } catch (e) {} }
                          } catch (e) {
                            showToast && showToast('Could not disable 2FA — please try again');
                            return;
                          }
                        }
                        updatePref(['security', 'twofaEnrolled'], false);
                        updatePref(['security', 'twofaSecret'], '');
                        updatePref(['security', 'twofaFactorId'], '');
                        showToast && showToast('Authenticator disabled');
                      }}>
                      Disable
                    </button>
                  </React.Fragment>
                ) : (
                  <button className="btn sm primary" onClick={() => setTwofaOpen(true)}>
                    <Icon name="lock" size={12}/> Set up authenticator
                  </button>
                )}
              </SettingRow>

              {!secPrefs.twofaEnrolled && (
                <div style={{ padding: '12px 0 4px', fontSize: 12.5, color: 'var(--ink-3)', display: 'flex', gap: 8, alignItems: 'flex-start' }}>
                  <Icon name="alert" size={13} color="oklch(0.55 0.13 60)"/>
                  <span>Two-factor authentication adds a second step to sign-in. Even if someone learns your password, they can't access your account without your authenticator code.</span>
                </div>
              )}
            </Panel>

            <Panel title="Change password" sub="Use a strong, unique password you don't use anywhere else">
              <div className="detail-grid" style={{ paddingTop: 8 }}>
                <div className="detail-field" style={{ gridColumn: '1 / -1' }}>
                  <span className="lbl">New password</span>
                  <input
                    type="password"
                    value={newPw}
                    onChange={e => { setNewPw(e.target.value); setPwStatus(null); }}
                    placeholder="At least 8 characters"
                    autoComplete="new-password"
                  />
                </div>
                <div className="detail-field" style={{ gridColumn: '1 / -1' }}>
                  <span className="lbl">Confirm new password</span>
                  <input
                    type="password"
                    value={confirmPw}
                    onChange={e => { setConfirmPw(e.target.value); setPwStatus(null); }}
                    placeholder="Re-enter your new password"
                    autoComplete="new-password"
                  />
                </div>
              </div>

              {/* Strength indicator */}
              {newPw.length > 0 && (
                <div style={{ paddingTop: 4, paddingBottom: 8 }}>
                  <div style={{ display: 'flex', gap: 3, marginBottom: 4 }}>
                    {[1, 2, 3, 4].map(i => {
                      const score = Math.min(4, [newPw.length >= 8, /[A-Z]/.test(newPw), /[0-9]/.test(newPw), /[^a-zA-Z0-9]/.test(newPw)].filter(Boolean).length);
                      return <div key={i} style={{ flex: 1, height: 4, borderRadius: 2, background: i <= score ? (score >= 3 ? 'var(--won)' : score >= 2 ? 'oklch(0.55 0.13 60)' : 'var(--lost)') : 'var(--border)' }}></div>;
                    })}
                  </div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>
                    {(() => {
                      const score = [newPw.length >= 8, /[A-Z]/.test(newPw), /[0-9]/.test(newPw), /[^a-zA-Z0-9]/.test(newPw)].filter(Boolean).length;
                      return score >= 4 ? 'Strong password' : score >= 3 ? 'Good — add a symbol to make it stronger' : score >= 2 ? 'Fair — add uppercase letters and numbers' : 'Weak — use 8+ characters with mixed types';
                    })()}
                  </div>
                </div>
              )}

              {pwStatus === 'mismatch' && <div style={{ fontSize: 12, color: 'var(--lost)', paddingBottom: 8 }}>Passwords don't match — please check and try again.</div>}
              {pwStatus === 'short' && <div style={{ fontSize: 12, color: 'var(--lost)', paddingBottom: 8 }}>Password must be at least 8 characters.</div>}
              {pwStatus === 'ok' && <div style={{ fontSize: 12, color: 'var(--won)', paddingBottom: 8, display: 'flex', alignItems: 'center', gap: 5 }}><Icon name="check" size={12}/> Password updated successfully.</div>}
              {pwStatus === 'error' && <div style={{ fontSize: 12, color: 'var(--lost)', paddingBottom: 8 }}>Something went wrong — please try again or contact your admin.</div>}

              <div style={{ paddingBottom: 8 }}>
                <button
                  className="btn primary"
                  disabled={!newPw || !confirmPw || pwLoading}
                  onClick={changePassword}
                  style={{ opacity: (!newPw || !confirmPw) ? 0.5 : 1 }}>
                  {pwLoading ? 'Updating…' : <React.Fragment><Icon name="lock" size={12}/> Update password</React.Fragment>}
                </button>
              </div>
            </Panel>
          </div>
        )}

        {/* ── NOTIFICATIONS ──────────────────────────────────────────── */}
        {tab === 'notifications' && (
          <Panel title="Notification preferences" sub="Your personal settings — these override the workspace defaults for your account only">
            <SettingRow label="Email reminders" desc="Receive reminder emails before appointments and follow-up tasks">
              <Toggle on={notifPrefs.emailReminders !== false} onChange={v => updatePref(['notifications', 'emailReminders'], v)}/>
            </SettingRow>
            <SettingRow label="SMS reminders" desc="Text message reminders before appointments (requires Twilio integration)">
              <Toggle on={!!notifPrefs.smsReminders} onChange={v => updatePref(['notifications', 'smsReminders'], v)}/>
            </SettingRow>
            <SettingRow label="Daily pipeline digest" desc="Morning email with today's appointments, due reminders and any stuck deals">
              <Toggle on={notifPrefs.dailyDigest !== false} onChange={v => updatePref(['notifications', 'dailyDigest'], v)}/>
            </SettingRow>
            <SettingRow label="New inbound lead alerts" desc="Get notified immediately when a new lead arrives for your showroom">
              <Toggle on={notifPrefs.newLeadAlert !== false} onChange={v => updatePref(['notifications', 'newLeadAlert'], v)}/>
            </SettingRow>
            <SettingRow label="Stuck-deal alerts" desc="Notify me when one of my deals has had no activity for 21+ days">
              <Toggle on={notifPrefs.stuckDealAlert !== false} onChange={v => updatePref(['notifications', 'stuckDealAlert'], v)}/>
            </SettingRow>
            <SettingRow label="Deal outcome notifications" desc="Get a notification when a deal in your team is won or lost">
              <Toggle on={!!notifPrefs.dealOutcomeAlert} onChange={v => updatePref(['notifications', 'dealOutcomeAlert'], v)}/>
            </SettingRow>
            <SettingRow label="Weekly summary report" desc="A weekly email round-up of your pipeline performance">
              <Toggle on={!!notifPrefs.weeklySummary} onChange={v => updatePref(['notifications', 'weeklySummary'], v)}/>
            </SettingRow>
            <div style={{ paddingTop: 10, paddingBottom: 4, fontSize: 11.5, color: 'var(--ink-3)' }}>
              <Icon name="alert" size={11}/> Delivery via email is managed through your workspace's notification integration. SMS requires Twilio to be connected in Settings.
            </div>
          </Panel>
        )}
      </div>

      {/* 2FA modal — reuse Authenticator2FA from Settings.jsx */}
      {twofaOpen && typeof Authenticator2FA !== 'undefined' && (
        <Authenticator2FA
          account={currentUser.email || currentUser.name}
          issuer="Stagevo CRM"
          existingSecret={secPrefs.twofaSecret || ''}
          onClose={() => setTwofaOpen(false)}
          onEnrolled={secret => {
            updatePref(['security', 'twofaSecret'], secret);
            updatePref(['security', 'twofaEnrolled'], true);
            showToast && showToast('Authenticator app verified and enabled');
            setTwofaOpen(false);
          }}
        />
      )}
    </div>
  );
}

window.MyProfile = MyProfile;
