// views_profile.jsx - authenticated Profile & Settings, adapted from approved profile prototype.
(function () {
  const { useEffect, useMemo, useState } = React;

  const SECTION_LINKS = [
    ['account', 'Account', 'user'],
    ['organization', 'Organization', 'building'],
    ['security', 'Security', 'shield'],
    ['notifications', 'Notifications', 'bell'],
    ['audit-defaults', 'Audit defaults', 'trending'],
    ['api-keys', 'API keys', 'key']
  ];

  const INDUSTRIES = [
    ['auto', 'Auto-detect'],
    ['ecommerce', 'E-commerce / Retail'],
    ['saas', 'SaaS / Technology'],
    ['services', 'Professional services'],
    ['healthcare', 'Healthcare'],
    ['realestate', 'Real estate'],
    ['hospitality', 'Hospitality / Travel'],
    ['finance', 'Finance'],
    ['education', 'Education'],
    ['media', 'Media / Publishing'],
    ['other', 'Other']
  ];

  const DEFAULT_NOTIFICATIONS = {
    auditComplete: true,
    citationAlerts: true,
    weeklyReport: false,
    productUpdates: false
  };

  const DEFAULT_AUDIT_DEFAULTS = {
    industry: 'auto',
    primaryLocation: '',
    maxPages: 20
  };

  function initials(name, fallback = 'JS') {
    const source = String(name || '').trim();
    if (!source) return fallback;
    const parts = source.split(/\s+/).filter(Boolean);
    const letters = parts.length > 1 ? `${parts[0][0]}${parts[parts.length - 1][0]}` : source.slice(0, 2);
    return letters.toUpperCase();
  }

  function roleLabel(role) {
    if (role === 'platform_admin' || role === 'super_admin') return 'Super admin';
    if (role === 'agency_owner') return 'Agency · Owner';
    if (role === 'agency_member' || role === 'agency') return 'Agency';
    if (role === 'client_admin' || role === 'client_viewer' || role === 'client') return 'Client';
    return 'Member';
  }

  function formatDate(value) {
    if (!value) return '-';
    try { return new Date(value).toISOString().slice(0, 10); } catch { return String(value).slice(0, 10); }
  }

  function maskKey(key) {
    if (!key) return 'jsai_live_....';
    if (key.maskedKey) return key.maskedKey;
    if (key.keyPrefix) return `${key.keyPrefix}........${String(key.id || '').slice(-4) || 'key'}`;
    return 'jsai_live_....';
  }

  function passwordScore(value) {
    let score = 0;
    if (String(value || '').length >= 10) score += 1;
    if (/[a-z]/.test(value) && /[A-Z]/.test(value)) score += 1;
    if (/\d/.test(value)) score += 1;
    if (/[^A-Za-z0-9]/.test(value)) score += 1;
    return value ? score : 0;
  }

  function readImageDataUrl(file) {
    return new Promise((resolve, reject) => {
      if (!file) return resolve('');
      if (!/^image\//.test(file.type || '')) return reject(new Error('Only image uploads are supported.'));
      if (file.size > 700000) return reject(new Error('Please use an image under 700 KB for this local profile preview.'));
      const reader = new FileReader();
      reader.onload = () => resolve(String(reader.result || ''));
      reader.onerror = () => reject(new Error('Could not read image.'));
      reader.readAsDataURL(file);
    });
  }

  function ProfileSettingsView({ session, go }) {
    const [loading, setLoading] = useState(true);
    const [loadError, setLoadError] = useState('');
    const [toast, setToast] = useState('');
    const [error, setError] = useState('');
    const [saving, setSaving] = useState('');
    const [activeSection, setActiveSection] = useState('account');
    const [user, setUser] = useState(session?.user || {});
    const [organization, setOrganization] = useState({});
    const [account, setAccount] = useState({ fullName: '', phone: '', email: '', jobTitle: '', avatarUrl: '' });
    const [orgForm, setOrgForm] = useState({ name: '', websiteUrl: '', industry: 'auto', primaryLocation: '', logoUrl: '' });
    const [notifications, setNotifications] = useState(DEFAULT_NOTIFICATIONS);
    const [auditDefaults, setAuditDefaults] = useState(DEFAULT_AUDIT_DEFAULTS);
    const [passwords, setPasswords] = useState({ currentPassword: '', newPassword: '', confirmPassword: '', showCurrent: false, showNew: false, showConfirm: false });
    const [passwordError, setPasswordError] = useState('');
    const [apiKeys, setApiKeys] = useState([]);
    const [keyName, setKeyName] = useState('');
    const [newRawKey, setNewRawKey] = useState('');
    const [avatarDirty, setAvatarDirty] = useState(false);
    const [logoDirty, setLogoDirty] = useState(false);

    const api = window.JS_API?.profile;
    const userRole = user?.role || session?.user?.role || '';
    const canManageKeys = !['client_viewer'].includes(userRole);
    const canEditOrg = !['client_viewer'].includes(userRole);
    const chipName = account.fullName || account.email || 'Your account';

    function handleAuthError(err) {
      if (err?.status === 401) {
        window.JS_SESSION?.logout?.();
        window.JS_API?.logout?.();
        setLoadError('Your session expired. Please sign in again.');
        return true;
      }
      return false;
    }

    function flash(message) {
      setToast(message);
      window.clearTimeout(ProfileSettingsView._toastTimer);
      ProfileSettingsView._toastTimer = window.setTimeout(() => setToast(''), 2600);
    }

    function applyProfile(payload = {}) {
      const nextUser = payload.user || {};
      const nextOrg = payload.organization || {};
      const prefs = nextUser.preferences || {};
      const nextDefaults = nextUser.auditDefaults || prefs.auditDefaults || {};
      setUser(nextUser);
      setOrganization(nextOrg);
      setAccount({
        fullName: nextUser.fullName || nextUser.displayName || '',
        phone: nextUser.phone || '',
        email: nextUser.email || '',
        jobTitle: nextUser.jobTitle || '',
        avatarUrl: nextUser.avatarUrl || ''
      });
      setOrgForm({
        name: nextOrg.name || '',
        websiteUrl: nextOrg.websiteUrl || '',
        industry: nextOrg.industry || 'auto',
        primaryLocation: nextOrg.primaryLocation || '',
        logoUrl: nextOrg.logoUrl || ''
      });
      setNotifications({ ...DEFAULT_NOTIFICATIONS, ...(prefs.notifications || {}) });
      setAuditDefaults({ ...DEFAULT_AUDIT_DEFAULTS, ...nextDefaults, maxPages: Number(nextDefaults.maxPages || DEFAULT_AUDIT_DEFAULTS.maxPages) });
    }

    async function loadProfile() {
      if (!api) {
        setLoadError('Profile API client is not loaded.');
        setLoading(false);
        return;
      }
      setLoading(true);
      setLoadError('');
      try {
        const [profile, keysResponse] = await Promise.all([
          api.me(),
          api.listApiKeys().catch(err => {
            if (err?.status === 403) return { apiKeys: [] };
            throw err;
          })
        ]);
        applyProfile(profile);
        const listedKeys = Array.isArray(keysResponse?.apiKeys) ? keysResponse.apiKeys : Array.isArray(keysResponse?.keys) ? keysResponse.keys : [];
        setApiKeys(listedKeys.filter(item => item?.status !== 'revoked'));
      } catch (err) {
        if (!handleAuthError(err)) setLoadError(err.message || 'Could not load profile.');
      } finally {
        setLoading(false);
      }
    }

    useEffect(() => { loadProfile(); }, []);

    useEffect(() => {
      const observer = new IntersectionObserver((entries) => {
        entries.forEach((entry) => { if (entry.isIntersecting) setActiveSection(entry.target.id); });
      }, { rootMargin: '-20% 0px -70% 0px' });
      SECTION_LINKS.forEach(([id]) => {
        const el = document.getElementById(id);
        if (el) observer.observe(el);
      });
      return () => observer.disconnect();
    }, [loading]);

    function jumpToSection(id) {
      setActiveSection(id);
      const el = document.getElementById(id);
      if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }

    async function saveSection(name, fn, message = 'Saved.') {
      setSaving(name);
      setError('');
      try {
        const result = await fn();
        if (result?.user) setUser(result.user);
        flash(message);
        return result;
      } catch (err) {
        if (!handleAuthError(err)) setError(err.message || 'Save failed.');
        return null;
      } finally {
        setSaving('');
      }
    }

    async function saveAccount() {
      await saveSection('account', async () => {
        let result = await api.updateAccount({
          fullName: account.fullName,
          phone: account.phone,
          jobTitle: account.jobTitle
        });
        if (avatarDirty) {
          result = await api.updateAvatar({ avatarDataUrl: account.avatarUrl || '' });
          setAvatarDirty(false);
        }
        if (result?.user) {
          setAccount(current => ({ ...current, avatarUrl: result.user.avatarUrl || current.avatarUrl }));
        }
        return result;
      });
    }

    async function saveOrganization() {
      await saveSection('organization', async () => {
        const result = await api.updateOrganization({
          name: orgForm.name,
          agencyName: orgForm.name,
          websiteUrl: orgForm.websiteUrl,
          industry: orgForm.industry,
          primaryLocation: orgForm.primaryLocation,
          logoUrl: orgForm.logoUrl
        });
        if (result?.organization) setOrganization(result.organization);
        setLogoDirty(false);
        return result;
      }, 'Organization saved.');
    }

    async function saveNotifications() {
      await saveSection('notifications', () => api.updatePreferences(notifications), 'Notification preferences saved.');
    }

    async function saveAuditDefaults() {
      await saveSection('audit-defaults', () => api.updateAuditDefaults({ ...auditDefaults, maxPages: Number(auditDefaults.maxPages) }), 'Audit defaults saved.');
    }

    async function changePassword() {
      setPasswordError('');
      if (passwords.newPassword.length < 10) {
        setPasswordError('New password must be at least 10 characters.');
        return;
      }
      if (passwords.newPassword !== passwords.confirmPassword) {
        setPasswordError('New passwords do not match.');
        return;
      }
      await saveSection('password', async () => {
        const result = await api.changePassword({ currentPassword: passwords.currentPassword, newPassword: passwords.newPassword });
        setPasswords({ currentPassword: '', newPassword: '', confirmPassword: '', showCurrent: false, showNew: false, showConfirm: false });
        return result;
      }, 'Password updated.');
    }

    async function createKey() {
      await saveSection('key-create', async () => {
        const result = await api.createApiKey({ name: keyName.trim() || 'Profile API key', scopes: ['api:*'] });
        const rawKey = result?.rawKey || result?.key || result?.apiKey?.key || '';
        if (rawKey) setNewRawKey(rawKey);
        const apiKey = result?.apiKey || { id: `new-${Date.now()}`, name: keyName.trim() || 'Profile API key', keyPrefix: rawKey.slice(0, 12), createdAt: new Date().toISOString() };
        setApiKeys(current => [apiKey, ...current.filter(item => item.id !== apiKey.id)]);
        setKeyName('');
        return result;
      }, 'API key created.');
    }

    async function revokeKey(id) {
      await saveSection(`key-${id}`, async () => {
        const result = await api.revokeApiKey(id);
        setApiKeys(current => current.filter(item => item.id !== id));
        return result;
      }, 'API key revoked.');
    }

    async function onAvatarFile(file) {
      setError('');
      try {
        const dataUrl = await readImageDataUrl(file);
        setAccount(current => ({ ...current, avatarUrl: dataUrl }));
        setAvatarDirty(true);
      } catch (err) {
        setError(err.message || 'Could not load avatar.');
      }
    }

    async function onLogoFile(file) {
      setError('');
      try {
        const dataUrl = await readImageDataUrl(file);
        setOrgForm(current => ({ ...current, logoUrl: dataUrl }));
        setLogoDirty(true);
      } catch (err) {
        setError(err.message || 'Could not load logo.');
      }
    }

    const strength = useMemo(() => passwordScore(passwords.newPassword), [passwords.newPassword]);

    if (loading) {
      return (
        <div className="js-view">
          <div className="js-pagehead"><div><p className="eyebrow">Profile</p><h1>Loading <em>settings</em></h1><p className="sub">Fetching your account, workspace, preferences, and keys from the authenticated backend.</p></div></div>
        </div>
      );
    }

    if (loadError) {
      return (
        <div className="js-view">
          <div className="js-pagehead"><div><p className="eyebrow">Profile</p><h1>Profile <em>unavailable</em></h1><p className="sub">{loadError}</p></div><div className="js-head-actions"><Btn icon="refresh" onClick={loadProfile}>Retry</Btn></div></div>
        </div>
      );
    }

    return (
      <div className="js-view js-view--wide profile-page">
        <header className="profile-hero">
          <div>
            <p className="eyebrow">Profile & settings</p>
            <h1>Your account, <em>workspace, and access.</em></h1>
            <p className="sub">Manage who you are, how your workspace appears, notification defaults, audit preferences, and programmatic access.</p>
          </div>
          <div className="profile-chip">
            <span className="profile-chip__avatar">{account.avatarUrl ? <img src={account.avatarUrl} alt="" /> : initials(chipName)}</span>
            <span><strong>{chipName}</strong><small>{roleLabel(userRole)}</small></span>
          </div>
        </header>

        <div className="profile-shell">
          <nav className="profile-nav" aria-label="Settings sections">
            {SECTION_LINKS.map(([id, label, icon]) => (
              <button key={id} type="button" className={'pn-link' + (activeSection === id ? ' is-active' : '')} onClick={() => jumpToSection(id)}><Icon name={icon} size={18} />{label}</button>
            ))}
          </nav>

          <div className="profile-content">
            {toast && <div className="alert alert--ok is-show" role="status">{toast}</div>}
            {error && <div className="alert alert--err is-show" role="alert">{error}</div>}

            <section className="psec card" id="account">
              <div className="psec-head"><h2>Account</h2><p>Your personal details and how teammates see you.</p></div>
              <div className="uploader profile-uploader">
                <div className="up-preview profile-avatar">{account.avatarUrl ? <img src={account.avatarUrl} alt="" /> : initials(chipName)}</div>
                <div>
                  <div className="field-label">Profile photo</div>
                  <div className="row" style={{ gap: 10, marginTop: 8 }}>
                    <label className="btn btn--ghost btn--sm">Upload<input type="file" accept="image/*" hidden onChange={(e) => onAvatarFile(e.target.files?.[0])} /></label>
                    <button className="btn btn--ghost btn--sm" type="button" onClick={() => { setAccount(current => ({ ...current, avatarUrl: '' })); setAvatarDirty(true); }}>Remove</button>
                  </div>
                  <div className="field-hint" style={{ marginTop: 8 }}>PNG or JPG, at least 200x200px. Local JSON storage is capped for preview safety.</div>
                </div>
              </div>
              <div className="field-row">
                <Field label="Full name" value={account.fullName} onChange={value => setAccount(current => ({ ...current, fullName: value }))} />
                <Field label="Phone" value={account.phone} onChange={value => setAccount(current => ({ ...current, phone: value }))} type="tel" />
              </div>
              <div className="field-row">
                <Field label="Email" value={account.email} readOnly hint="Email changes require a verified email-change flow." />
                <Field label="Job title" value={account.jobTitle} onChange={value => setAccount(current => ({ ...current, jobTitle: value }))} placeholder="e.g. Head of Growth" />
              </div>
              <div className="psec-actions"><Btn onClick={saveAccount} disabled={Boolean(saving)}>{saving === 'account' ? 'Saving...' : 'Save changes'}</Btn></div>
            </section>

            <section className="psec card" id="organization">
              <div className="psec-head"><h2>Organization</h2><p>Workspace details used across reports and white-label outputs.</p></div>
              <div className="uploader profile-uploader">
                <div className="up-preview profile-logo">{orgForm.logoUrl ? <img src={orgForm.logoUrl} alt="" /> : initials(orgForm.name || organization.name)}</div>
                <div>
                  <div className="field-label">Organization logo</div>
                  <div className="row" style={{ gap: 10, marginTop: 8 }}>
                    <label className="btn btn--ghost btn--sm">Upload<input type="file" accept="image/*" hidden disabled={!canEditOrg} onChange={(e) => onLogoFile(e.target.files?.[0])} /></label>
                    <button className="btn btn--ghost btn--sm" type="button" disabled={!canEditOrg} onClick={() => { setOrgForm(current => ({ ...current, logoUrl: '' })); setLogoDirty(true); }}>Remove</button>
                  </div>
                  <div className="field-hint" style={{ marginTop: 8 }}>Shown on white-label reports and the embeddable widget where supported.</div>
                </div>
              </div>
              <Field label="Organization name" value={orgForm.name} disabled={!canEditOrg} onChange={value => setOrgForm(current => ({ ...current, name: value }))} />
              <div className="field-row">
                <Field label="Primary website" value={orgForm.websiteUrl} disabled={!canEditOrg} onChange={value => setOrgForm(current => ({ ...current, websiteUrl: value }))} type="url" placeholder="https://company.com" />
                <SelectField label="Industry" value={orgForm.industry} disabled={!canEditOrg} options={INDUSTRIES} onChange={value => setOrgForm(current => ({ ...current, industry: value }))} />
              </div>
              <Field label="Primary market" value={orgForm.primaryLocation} disabled={!canEditOrg} onChange={value => setOrgForm(current => ({ ...current, primaryLocation: value }))} placeholder="e.g. Sydney, AU" />
              <div className="psec-actions"><Btn onClick={saveOrganization} disabled={!canEditOrg || Boolean(saving)}>{saving === 'organization' ? 'Saving...' : 'Save organization'}</Btn>{!canEditOrg && <span className="field-hint">Your role is read-only for organization settings.</span>}</div>
            </section>

            <section className="psec card" id="security">
              <div className="psec-head"><h2>Security</h2><p>Change your password. You will stay signed in on this device.</p></div>
              <PasswordField label="Current password" value={passwords.currentPassword} visible={passwords.showCurrent} onToggle={() => setPasswords(current => ({ ...current, showCurrent: !current.showCurrent }))} onChange={value => setPasswords(current => ({ ...current, currentPassword: value }))} />
              <div className="field-row profile-security-row">
                <PasswordField label="New password" value={passwords.newPassword} visible={passwords.showNew} onToggle={() => setPasswords(current => ({ ...current, showNew: !current.showNew }))} onChange={value => setPasswords(current => ({ ...current, newPassword: value }))} />
                <PasswordField label="Confirm new" value={passwords.confirmPassword} visible={passwords.showConfirm} onToggle={() => setPasswords(current => ({ ...current, showConfirm: !current.showConfirm }))} onChange={value => setPasswords(current => ({ ...current, confirmPassword: value }))} />
              </div>
              <div className="pw-meter" data-score={strength}><span className="seg" /><span className="seg" /><span className="seg" /><span className="seg" /></div>
              {passwordError && <div className="alert alert--err is-show" style={{ marginTop: 16 }}>{passwordError}</div>}
              <div className="psec-actions"><Btn onClick={changePassword} disabled={Boolean(saving)}>{saving === 'password' ? 'Updating...' : 'Update password'}</Btn></div>
            </section>

            <section className="psec card" id="notifications">
              <div className="psec-head"><h2>Notifications</h2><p>Choose what JiffyScore emails you about.</p></div>
              <SwitchRow title="Audit complete" desc="Email me when an audit finishes and the score is ready." checked={notifications.auditComplete} onChange={value => setNotifications(current => ({ ...current, auditComplete: value }))} />
              <SwitchRow title="Citation alerts" desc="Tell me when an answer engine starts or stops citing a tracked site." checked={notifications.citationAlerts} onChange={value => setNotifications(current => ({ ...current, citationAlerts: value }))} />
              <SwitchRow title="Weekly visibility report" desc="A Monday digest of score movement across my sites." checked={notifications.weeklyReport} onChange={value => setNotifications(current => ({ ...current, weeklyReport: value }))} />
              <SwitchRow title="Product updates" desc="Occasional news about new features. No more than monthly." checked={notifications.productUpdates} onChange={value => setNotifications(current => ({ ...current, productUpdates: value }))} />
              <div className="psec-actions"><Btn onClick={saveNotifications} disabled={Boolean(saving)}>{saving === 'notifications' ? 'Saving...' : 'Save preferences'}</Btn></div>
            </section>

            <section className="psec card" id="audit-defaults">
              <div className="psec-head"><h2>Audit defaults</h2><p>Pre-fill new audits so you can run them in one click.</p></div>
              <div className="field-row">
                <SelectField label="Default industry" value={auditDefaults.industry} options={INDUSTRIES} onChange={value => setAuditDefaults(current => ({ ...current, industry: value }))} />
                <Field label="Default market" value={auditDefaults.primaryLocation} onChange={value => setAuditDefaults(current => ({ ...current, primaryLocation: value }))} placeholder="e.g. Sydney, AU" />
              </div>
              <div className="field field--tight profile-slider">
                <div className="slider-row">
                  <div className="slider-head"><span className="slider-name">Max pages per crawl</span><span className="slider-val">{auditDefaults.maxPages}</span></div>
                  <input className="slider-input" type="range" min="5" max="100" step="5" value={auditDefaults.maxPages} onChange={(e) => setAuditDefaults(current => ({ ...current, maxPages: Number(e.target.value) }))} />
                </div>
                <div className="field-hint" style={{ marginTop: 10 }}>The backend clamps this to the configured crawl maximum and plan policy.</div>
              </div>
              <div className="psec-actions"><Btn onClick={saveAuditDefaults} disabled={Boolean(saving)}>{saving === 'audit-defaults' ? 'Saving...' : 'Save defaults'}</Btn></div>
            </section>

            <section className="psec card" id="api-keys">
              <div className="psec-head"><h2>API keys</h2><p>Programmatic access for automation and scheduled audits. Keys are shown once at creation.</p></div>
              {newRawKey && (
                <div className="alert alert--info is-show">
                  <span>New key created. Copy it now, it will not be shown again:</span>
                  <code>{newRawKey}</code>
                  <button className="btn btn--ghost btn--sm" type="button" onClick={() => setNewRawKey('')}>Hide</button>
                </div>
              )}
              <div className="row profile-key-create">
                <input className="input" value={keyName} onChange={(e) => setKeyName(e.target.value)} placeholder="Key name (e.g. Automation pipeline)" disabled={!canManageKeys} />
                <Btn onClick={createKey} disabled={!canManageKeys || Boolean(saving)}>{saving === 'key-create' ? 'Creating...' : 'Create key'}</Btn>
              </div>
              {!canManageKeys && <div className="field-hint">Your role is read-only for API keys.</div>}
              <div className="stack profile-key-list">
                {apiKeys.length ? apiKeys.map(key => (
                  <div className="key-row" key={key.id}>
                    <div><div className="k-name">{key.name || 'API key'}</div><div className="k-val">{maskKey(key)}</div></div>
                    <div className="row key-row__meta">
                      <span className="k-meta">created {formatDate(key.createdAt)} · used {key.lastUsedAt ? formatDate(key.lastUsedAt) : 'never'}</span>
                      <button className="btn btn--ghost btn--sm" type="button" disabled={!canManageKeys || saving === `key-${key.id}`} onClick={() => revokeKey(key.id)}>Revoke</button>
                    </div>
                  </div>
                )) : <div className="field-hint">No API keys yet.</div>}
              </div>
            </section>
          </div>
        </div>
      </div>
    );
  }

  function Field({ label, value, onChange, type = 'text', placeholder = '', readOnly = false, disabled = false, hint = '' }) {
    return (
      <div className="field field--tight">
        <label className="field-label">{label}</label>
        <input className="input" type={type} value={value || ''} placeholder={placeholder} readOnly={readOnly} disabled={disabled} onChange={(e) => onChange && onChange(e.target.value)} />
        {hint && <div className="field-hint">{hint}</div>}
      </div>
    );
  }

  function SelectField({ label, value, options, onChange, disabled = false }) {
    return (
      <div className="field field--tight">
        <label className="field-label">{label}</label>
        <select className="select" value={value || ''} disabled={disabled} onChange={(e) => onChange(e.target.value)}>
          {options.map(([id, labelText]) => <option key={id} value={id}>{labelText}</option>)}
        </select>
      </div>
    );
  }

  function PasswordField({ label, value, onChange, visible, onToggle }) {
    return (
      <div className="field field--tight profile-password-field">
        <label className="field-label">{label}</label>
        <div className="input-wrap">
          <input className="input" type={visible ? 'text' : 'password'} value={value || ''} onChange={(e) => onChange(e.target.value)} />
          <button type="button" className="pw-toggle" onClick={onToggle} aria-label={visible ? 'Hide password' : 'Show password'}><Icon name="eye" size={18} /></button>
        </div>
      </div>
    );
  }

  function SwitchRow({ title, desc, checked, onChange }) {
    return (
      <label className="switch-row">
        <div><div className="sr-t">{title}</div><div className="sr-d">{desc}</div></div>
        <span className="switch"><input type="checkbox" checked={Boolean(checked)} onChange={(e) => onChange(e.target.checked)} /><span className="track" /></span>
      </label>
    );
  }

  window.ProfileSettingsView = ProfileSettingsView;
})();
