// =============================================================================
// settings.jsx — User-facing settings sheet (theme mode toggle)
// =============================================================================
// Triggered by a gear icon on the portfolio header. The visual style of the
// app (card style / number font / pnl color) is locked per the design final
// state; only the dark/light/auto theme is exposed here.
//
// Pref persists in localStorage 'hl.theme.v1' via window.hlSetThemePref().
// =============================================================================

function ThemeIcon({ kind, color, size = 18 }) {
  if (kind === 'auto')  return Icon.auto(color, size);
  if (kind === 'light') return Icon.sun(color, size);
  return Icon.moon(color, size);
}

function SettingsButton({ t, onClick, style = {} }) {
  const th = aTheme(t);
  return (
    <button onClick={onClick} aria-label="设置" title="设置" style={{
      ...th.card, borderRadius: 999, padding: 8, color: th.ink, cursor: 'pointer', ...style,
    }}>
      {Icon.cog('currentColor', 16)}
    </button>
  );
}

function SettingsSheet({ t, open, onClose }) {
  const th = aTheme(t);
  const isDark = th.mode === 'dark';
  const [pref, setPref] = React.useState(() => (typeof window !== 'undefined' ? (window.hlGetThemePref?.() || 'auto') : 'auto'));

  React.useEffect(() => {
    const refresh = () => setPref(window.hlGetThemePref?.() || 'auto');
    window.addEventListener('hl-tweaks-change', refresh);
    return () => window.removeEventListener('hl-tweaks-change', refresh);
  }, []);

  if (!open) return null;

  const choose = (v) => { window.hlSetThemePref?.(v); setPref(v); };

  const opts = [
    { key: 'auto',  label: '跟随系统', sub: '根据 iOS/系统外观自动切换' },
    { key: 'light', label: '浅色',     sub: '始终使用浅色主题' },
    { key: 'dark',  label: '深色',     sub: '始终使用深色主题' },
  ];

  return (
    <div style={{
      position:'absolute', inset:0, background: isDark?'rgba(0,0,0,0.55)':'rgba(0,0,0,0.35)', backdropFilter:'blur(6px)',
      display:'flex', alignItems:'flex-end', zIndex:90,
    }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width:'100%', background: th.tk.sheetBg, backdropFilter:'blur(30px)',
        borderTop: th.tk.sheetBorder, borderRadius:'24px 24px 0 0',
        padding:'14px 18px 26px',
      }}>
        <div style={{ width:36, height:4, borderRadius:2, background: isDark?'rgba(255,255,255,0.18)':'rgba(0,0,0,0.18)', margin:'0 auto 12px' }}/>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:14 }}>
          <div style={{ fontSize:16, fontWeight:600 }}>外观</div>
          <button onClick={onClose} style={{ background:'transparent', border:0, color:th.dim, cursor:'pointer', padding:6 }}>
            {Icon.close('currentColor', 18)}
          </button>
        </div>

        <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
          {opts.map((o) => {
            const on = pref === o.key;
            return (
              <button key={o.key} onClick={() => choose(o.key)} style={{
                ...th.card, borderRadius: 14, padding:'12px 14px',
                color: th.ink, cursor:'pointer', textAlign:'left',
                outline: on ? `1.5px solid ${th.accent}` : 'none',
                display:'flex', alignItems:'center', gap:12,
              }}>
                <span style={{
                  width:32, height:32, borderRadius:9,
                  background: isDark ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.04)',
                  display:'flex', alignItems:'center', justifyContent:'center',
                  color: on ? th.accent : th.dim, flexShrink: 0,
                }}>
                  <ThemeIcon kind={o.key} color="currentColor"/>
                </span>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:14.5, fontWeight:600 }}>{o.label}</div>
                  <div style={{ fontSize:12, color:th.dim, marginTop:2 }}>{o.sub}</div>
                </div>
                {on && (
                  <span style={{
                    width:20, height:20, borderRadius:'50%', background: th.accent,
                    display:'inline-flex', alignItems:'center', justifyContent:'center',
                    color: isDark?'#04130f':'#fff', flexShrink:0,
                  }}>
                    <svg width="11" height="11" viewBox="0 0 12 12" fill="none">
                      <path d="M2.5 6.2 L5 8.5 L9.5 3.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  </span>
                )}
              </button>
            );
          })}
        </div>

        <div style={{ marginTop:14, fontSize:12, color:th.faint, lineHeight:1.6, padding:'0 4px' }}>
          其他视觉风格（玻璃卡片 · 等宽数字 · 绿涨红跌）已锁定，与设计稿一致。
        </div>
      </div>
    </div>
  );
}

window.SettingsButton = SettingsButton;
window.SettingsSheet  = SettingsSheet;
