/* global React, C, Screen, Header, Toggle, Close, PALETTES */
// screens-settings.jsx — Settings sheet (slides up from gear icon on Stats).

function SettingsScreen() {
  const settings = window.useStore((s) => s.settings);
  const me = window.useStore((s) => s.me);
  const close = () => { const n = window.appNav; if (n) n.closeSheet(); };
  const patch = (partial) => window.STORE.patch('settings', partial);
  const patchNotif = (partial) => window.STORE.patch('settings', {
    notifications: { ...settings.notifications, ...partial },
  });

  const setPalette = (id) => patch({ palette: id });

  const signOut = () => {
    if (window.cambamApi && window.cambamApi.signOut) {
      window.cambamApi.signOut().catch(() => {});
    }
    window.STORE.set({ authed: false });
    close();
    window.STORE.toast('Signed out');
  };

  const openAdmin = () => {
    if (window.appNav) window.appNav.openSheet('admin');
  };

  return (
    <Screen label="09 Settings" bottomNav={null} scroll={false}>
      <div onClick={close} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.55)' }} />

      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        height: 'calc(100% - 64px)',
        background: C.surface,
        borderTopLeftRadius: 16, borderTopRightRadius: 16,
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
      }}>
        <div style={{ display: 'flex', justifyContent: 'center', padding: '8px 0 0', flexShrink: 0 }}>
          <div style={{ width: 36, height: 4, borderRadius: 999, background: C.hairline }} />
        </div>

        <div style={{
          padding: '8px 16px 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          flexShrink: 0,
        }}>
          <div style={{ font: '600 18px/24px Inter', color: C.text }}>Settings</div>
          <button aria-label="Close settings" onClick={close} style={{
            width: 32, height: 32, borderRadius: 999, background: C.surface2,
            border: 'none', cursor: 'pointer', color: C.text2,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}><Close size={16} /></button>
        </div>

        <div style={{ flex: 1, overflow: 'auto', paddingBottom: 56 }}>

          <SettingsGroup title="Account">
            <SettingsRow label="Magic-link email"  value={me.email} />
            <SettingsRow label="Display name"      value={me.displayName} />
            <SettingsRow label="Handle"            value={me.handle} last />
          </SettingsGroup>

          <PasskeysGroup />

          <SettingsGroup title="Notifications">
            <ToggleRow label="Lock reminders"     sub="24h / 2h / 15min before lineups close"
              on={settings.notifications.lockReminders} onChange={(v) => patchNotif({ lockReminders: v })} />
            <ToggleRow label="Score swings"       sub="Your golfer scores or makes the cut"
              on={settings.notifications.scoreSwings} onChange={(v) => patchNotif({ scoreSwings: v })} />
            <ToggleRow label="Leaderboard"        sub="Someone passes you in the standings"
              on={settings.notifications.leaderboard} onChange={(v) => patchNotif({ leaderboard: v })} />
            <ToggleRow label="WD / MC alerts"     sub="Your golfer withdraws or misses cut"
              on={settings.notifications.wdMc} onChange={(v) => patchNotif({ wdMc: v })} />
            <ToggleRow label="Weekly recap"       sub="Sunday-night summary post-major"
              on={settings.notifications.weeklyRecap} onChange={(v) => patchNotif({ weeklyRecap: v })} />
            <ToggleRow label="Clubhouse mentions" sub="Someone @-mentions you" last
              on={settings.notifications.clubMentions} onChange={(v) => patchNotif({ clubMentions: v })} />
          </SettingsGroup>

          <SettingsGroup title="Appearance">
            <div style={{ padding: '14px 16px 4px' }}>
              <div style={{
                font: '500 11px/16px Inter', textTransform: 'uppercase', letterSpacing: 0.04 * 11,
                color: C.text3,
              }}>Palette</div>
              <div style={{
                display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8, marginTop: 10,
              }}>
                {PALETTES.map((p) => (
                  <PaletteSwatch key={p.id} p={p}
                    active={settings.palette === p.id}
                    onClick={() => setPalette(p.id)} />
                ))}
              </div>
            </div>
            <ToggleRow label="Reduce motion" sub="Disable score-swoosh and pulse"
              on={settings.reduceMotion} onChange={(v) => patch({ reduceMotion: v })} />
            <ToggleRow label="Tabular zeros" sub="Show 0.0 instead of '—' for pending scores" last
              on={settings.tabularZeros} onChange={(v) => patch({ tabularZeros: v })} />
          </SettingsGroup>

          <SettingsGroup title="Pool">
            <SettingsRow label="Invite a friend" value="invite-only · open roster" accent />
            <CommissionerRow />
            <SettingsRow label="Open commissioner view"
              value={<span style={{ color: C.emerald }}>Admin →</span>}
              onClick={openAdmin} last />
          </SettingsGroup>

          <div style={{ padding: '8px 16px 32px' }}>
            <button onClick={signOut} style={{
              width: '100%', height: 48, borderRadius: 8,
              background: C.surface2, border: `1px solid ${C.hairline}`,
              color: C.red, font: '600 15px/1 Inter', cursor: 'pointer',
            }}>Sign out</button>
            <div style={{
              marginTop: 14, font: '400 11px/16px Inter', color: C.text3, textAlign: 'center',
            }}>
              CamBam · v0.4 build 26.0517<br />
              Terms · Privacy · Built for the four-major season
            </div>
          </div>
        </div>
      </div>
    </Screen>
  );
}

function SettingsGroup({ title, children }) {
  return (
    <div style={{ marginTop: 12 }}>
      <div style={{
        padding: '4px 16px 8px',
        font: '500 11px/16px Inter', textTransform: 'uppercase', letterSpacing: 0.04 * 11,
        color: C.text3,
      }}>{title}</div>
      <div style={{ background: C.surface2, margin: '0 16px', borderRadius: 12, overflow: 'hidden' }}>
        {children}
      </div>
    </div>
  );
}

// ─── Passkeys (WebAuthn MFA) ─────────────────────────────────────
// Sits between Account and Notifications. Empty state shows "Add a passkey";
// after enrollment, each verified factor renders as a row with a remove
// button. Hides itself entirely on browsers that don't support WebAuthn
// or when Supabase isn't configured.

function devicePasskeyLabel() {
  const ua = (typeof navigator !== 'undefined' && navigator.userAgent) || '';
  let device = 'this device';
  if (/iPhone/i.test(ua)) device = 'iPhone';
  else if (/iPad/i.test(ua)) device = 'iPad';
  else if (/Android/i.test(ua)) device = 'Android';
  else if (/Macintosh/i.test(ua)) device = 'Mac';
  else if (/Windows/i.test(ua)) device = 'Windows';
  return `Passkey on ${device}`;
}

function PasskeysGroup() {
  const api = window.cambamApi;
  const me = window.useStore((s) => s.me);
  const supported = !!(api && api.webauthnSupported && api.webauthnSupported());
  const configured = !!(api && api.isConfigured && api.isConfigured());
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [busy, setBusy] = React.useState(false);

  const refresh = React.useCallback(async () => {
    if (!configured) { setLoading(false); return; }
    setLoading(true);
    try {
      const list = await api.listPasskeys();
      setItems(list || []);
    } finally { setLoading(false); }
  }, [api, configured]);

  React.useEffect(() => { refresh(); }, [refresh]);

  if (!configured || !supported) return null;

  const add = async () => {
    if (busy) return;
    if (!me?.email) { window.STORE.toast('Sign in first'); return; }
    setBusy(true);
    try {
      const res = await api.enrollPasskey(me.email, devicePasskeyLabel());
      if (res.ok) {
        window.STORE.toast('Passkey added');
        await refresh();
      } else if (res.cancelled) {
        // User cancelled the OS prompt — no error toast, just no-op.
      } else {
        window.STORE.toast(res.error || 'Could not add passkey');
      }
    } finally { setBusy(false); }
  };

  const remove = async (factor) => {
    if (busy) return;
    setBusy(true);
    try {
      const res = await api.unenrollPasskey(factor.id);
      if (!res.ok) window.STORE.toast(res.error || 'Could not remove passkey');
      else { window.STORE.toast('Passkey removed'); await refresh(); }
    } finally { setBusy(false); }
  };

  return (
    <SettingsGroup title="Sign in">
      {loading ? (
        <SettingsRow label="Passkeys" value="Loading…" last />
      ) : items.length === 0 ? (
        <PasskeyAddRow onAdd={add} busy={busy} label="Add a passkey" last />
      ) : (
        <>
          {items.map((f, i) => (
            <PasskeyRow
              key={f.id}
              factor={f}
              onRemove={() => remove(f)}
              busy={busy}
              last={false}
            />
          ))}
          <PasskeyAddRow onAdd={add} busy={busy} label="Add another passkey" last />
        </>
      )}
    </SettingsGroup>
  );
}

function PasskeyRow({ factor, onRemove, busy }) {
  const created = factor.created_at ? new Date(factor.created_at) : null;
  const sub = created ? `Added ${created.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}` : 'Added recently';
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '14px 16px', borderBottom: `1px solid ${C.hairline}`,
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ font: '500 15px/20px Inter', color: C.text }}>{factor.friendly_name || 'Unnamed passkey'}</div>
        <div style={{ font: '400 12px/16px Inter', color: C.text2, marginTop: 1 }}>{sub}</div>
      </div>
      <button
        onClick={onRemove}
        disabled={busy}
        style={{
          background: 'transparent', border: 'none', cursor: busy ? 'wait' : 'pointer',
          color: C.red, font: '500 13px/18px Inter', padding: '4px 8px',
        }}>Remove</button>
    </div>
  );
}

function PasskeyAddRow({ onAdd, busy, label, last }) {
  return (
    <div
      onClick={busy ? undefined : onAdd}
      role="button"
      tabIndex={0}
      onKeyDown={(e) => { if (!busy && (e.key === 'Enter' || e.key === ' ')) onAdd(); }}
      style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        gap: 12, padding: '14px 16px',
        borderBottom: last ? 'none' : `1px solid ${C.hairline}`,
        cursor: busy ? 'wait' : 'pointer',
      }}>
      <span style={{ font: '500 15px/20px Inter', color: C.emerald }}>{busy ? 'Working…' : label}</span>
      <span style={{ font: '400 13px/18px Inter', color: C.text3 }}>Touch ID · Windows Hello · iCloud Keychain</span>
    </div>
  );
}

function CommissionerRow() {
  const [name, setName] = React.useState('—');
  React.useEffect(() => {
    const api = window.cambamApi;
    if (!api || !api.isConfigured?.()) return;
    let cancelled = false;
    (async () => {
      try {
        const members = await api.loadAllMembers();
        if (cancelled) return;
        const c = (members || []).find((m) => m.role === 'commissioner');
        if (c) setName(c.display_name || c.handle || 'unknown');
      } catch (e) { console.warn('commissioner row load failed', e); }
    })();
    return () => { cancelled = true; };
  }, []);
  return <SettingsRow label="Commissioner" value={name} />;
}

function SettingsRow({ label, value, accent, last, onClick }) {
  const interactive = !!onClick;
  return (
    <div
      onClick={onClick}
      role={interactive ? 'button' : undefined}
      tabIndex={interactive ? 0 : undefined}
      onKeyDown={interactive ? (e) => { if (e.key === 'Enter' || e.key === ' ') onClick(); } : undefined}
      style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        gap: 12, padding: '14px 16px',
        borderBottom: last ? 'none' : `1px solid ${C.hairline}`,
        cursor: interactive ? 'pointer' : 'default',
      }}>
      <span style={{ font: '500 15px/20px Inter', color: C.text }}>{label}</span>
      <span style={{
        font: '400 14px/20px Inter',
        color: accent ? C.emerald : C.text2,
      }}>{value}</span>
    </div>
  );
}

function ToggleRow({ label, sub, on, last, onChange }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '14px 16px',
      borderBottom: last ? 'none' : `1px solid ${C.hairline}`,
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ font: '500 15px/20px Inter', color: C.text }}>{label}</div>
        {sub && <div style={{ font: '400 12px/16px Inter', color: C.text2, marginTop: 1 }}>{sub}</div>}
      </div>
      <Toggle on={!!on} onChange={onChange} />
    </div>
  );
}

function PaletteSwatch({ p, active, onClick }) {
  return (
    <button onClick={onClick} style={{
      borderRadius: 10, padding: 8,
      background: p.bg,
      border: `1.5px solid ${active ? C.emerald : C.hairline}`,
      position: 'relative', cursor: 'pointer', textAlign: 'left',
    }}>
      <div style={{ display: 'flex', gap: 3, marginBottom: 6 }}>
        {[p.bg, p.surface, p.surface2, p.accent].map((c, i) => (
          <div key={i} style={{
            width: 10, height: 10, borderRadius: 999, background: c,
            border: c === p.bg ? `1px solid ${p.hairline}` : 'none',
          }} />
        ))}
      </div>
      <div style={{ font: '600 10px/14px Inter', color: p.text }}>{p.name.replace('Augusta at ', '').replace('Clubhouse ', '')}</div>
      {active && (
        <span style={{
          position: 'absolute', top: 6, right: 6,
          width: 14, height: 14, borderRadius: 999, background: C.emerald, color: '#0a0a0a',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          font: '700 9px/1 Inter',
        }}>✓</span>
      )}
    </button>
  );
}

Object.assign(window, { SettingsScreen });
