// me.jsx — Me / profile / goal / achievements / theme settings
function MeScreen() {
  const T = useTheme();
  const app = useApp();
  const { A, names, goal, openGoal, badges, settings, updateSettings, changeName, switchRole, fire } = app;
  const card = { background: T.card, borderRadius: T.r, boxShadow: T.shadow };
  const pct = Math.round(((A.start - A.cur) / (A.start - goal.A)) * 100);
  const [editName, setEditName] = React.useState(false);
  const [nameVal, setNameVal] = React.useState(names.A);
  React.useEffect(() => { setNameVal(names.A); }, [names.A]);

  const row = (icon, label, value, onClick, last) => (
    <button onClick={onClick} disabled={!onClick} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', background: 'none', border: 'none', borderTop: last===undefined?'none':`1px solid ${T.line}`, cursor: onClick?'pointer':'default', textAlign: 'left' }}>
      <div style={{ width: 30, height: 30, borderRadius: 9, background: T.bg2, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{icon}</div>
      <span style={{ flex: 1, fontSize: 14.5, color: T.ink, fontWeight: 500 }}>{label}</span>
      {value && <span style={{ fontSize: 13.5, color: T.sub, fontFamily: T.NUM, whiteSpace: 'nowrap' }}>{value}</span>}
      {onClick && <svg width="18" height="18" viewBox="0 0 24 24"><path d="M9 6l6 6-6 6" stroke={T.faint} strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>}
    </button>
  );

  // ── theme controls ──
  const segBtn = (val, cur, on, label) => (
    <button key={val} onClick={() => on(val)} style={{ flex: 1, border: 'none', borderRadius: T.rSm, padding: '8px 0', cursor: 'pointer', fontFamily: T.FONT, fontSize: 13, fontWeight: 700, background: cur===val ? T.card : 'transparent', color: cur===val ? T.Ad : T.faint, boxShadow: cur===val ? '0 1px 4px rgba(0,0,0,0.08)' : 'none' }}>{label}</button>
  );
  const seg = (label, value, options, onChange) => (
    <div style={{ marginBottom: 14 }}>
      <div style={{ fontSize: 12.5, color: T.sub, fontWeight: 600, marginBottom: 7 }}>{label}</div>
      <div style={{ display: 'flex', gap: 4, background: T.bg2, padding: 4, borderRadius: T.rSm }}>
        {options.map(o => segBtn(o, value, onChange, o))}
      </div>
    </div>
  );

  return (
    <>
      <PageTitle title="我的" />
      <div style={{ flex: 1, overflow: 'auto', padding: '8px 20px 28px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        {/* profile */}
        <div style={{ ...card, padding: 20, display: 'flex', alignItems: 'center', gap: 16 }}>
          <Avatar who="A" size={64} ring />
          <div style={{ flex: 1, minWidth: 0 }}>
            {editName ? (
              <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                <input value={nameVal} maxLength={12} onChange={(e) => setNameVal(e.target.value)} onKeyDown={(e) => e.key==='Enter' && (changeName(nameVal.trim()||names.A), setEditName(false))}
                  style={{ flex: 1, minWidth: 0, height: 36, borderRadius: 10, border: `1.5px solid ${T.line}`, background: T.bg, padding: '0 12px', fontFamily: T.FONT, fontSize: 16, color: T.ink, outline: 'none' }} autoFocus />
                <button onClick={() => { changeName(nameVal.trim()||names.A); setEditName(false); }} style={{ border: 'none', background: T.As, color: T.Ad, borderRadius: 10, padding: '8px 12px', fontFamily: T.FONT, fontSize: 13, fontWeight: 700, cursor: 'pointer' }}>保存</button>
              </div>
            ) : (
              <div style={{ fontSize: 19, fontWeight: 700, color: T.ink, display: 'flex', alignItems: 'center', gap: 8 }}>
                {names.A}
                <button onClick={() => setEditName(true)} style={{ border: 'none', background: 'none', cursor: 'pointer', color: T.faint, fontSize: 13, padding: 0 }}>✎</button>
              </div>
            )}
            <div style={{ fontSize: 13, color: T.sub, marginTop: 3 }}>加入第 {A.streak} 天 · 已减 {(A.start-A.cur).toFixed(1)}kg</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 5, color: T.Ad, background: T.As, padding: '6px 12px', borderRadius: 999, whiteSpace: 'nowrap' }}>
            <Flame size={15} /><span style={{ fontFamily: T.NUM, fontWeight: 800, fontSize: 15 }}>{A.streak}</span>
          </div>
        </div>

        {/* goal card */}
        <div style={{ ...card, padding: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
            <span style={{ fontSize: 14.5, fontWeight: 700, color: T.ink }}>我的目标</span>
            <button onClick={openGoal} style={{ background: T.As, border: 'none', color: T.Ad, borderRadius: 999, padding: '6px 14px', fontFamily: T.FONT, fontSize: 13, fontWeight: 700, cursor: 'pointer' }}>修改目标</button>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
            <span style={{ fontFamily: T.NUM, fontSize: 14, color: T.faint, width: 42 }}>{A.start}</span>
            <div style={{ flex: 1, height: 10, borderRadius: 999, background: T.bg2, overflow: 'hidden' }}>
              <div style={{ width: `${Math.max(0,Math.min(100,pct))}%`, height: '100%', borderRadius: 999, background: `linear-gradient(90deg, ${T.Ac}, ${T.Ad})`, transition: 'width .8s' }} />
            </div>
            <span style={{ fontFamily: T.NUM, fontSize: 14, color: T.good, fontWeight: 700, width: 42, textAlign: 'right' }}>{goal.A}</span>
          </div>
          <div style={{ textAlign: 'center', fontSize: 13, color: T.sub }}>当前 <b style={{ fontFamily: T.NUM, color: T.ink }}>{A.cur}kg</b>，已完成 <b style={{ color: T.Ad }}>{pct}%</b>，还差 <b style={{ fontFamily: T.NUM, color: T.Ad }}>{(A.cur-goal.A).toFixed(1)}kg</b></div>
        </div>

        {/* badges */}
        <div style={{ ...card, padding: 18 }}>
          <div style={{ fontSize: 14.5, fontWeight: 700, color: T.ink, marginBottom: 14 }}>成就徽章</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
            {badges.map((b, i) => (
              <div key={i} style={{ textAlign: 'center', opacity: b.got ? 1 : 0.32 }}>
                <div style={{ width: 52, height: 52, margin: '0 auto', borderRadius: '50%', background: b.got ? `linear-gradient(145deg, ${T.star}, ${T.Ac})` : T.bg2, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24, boxShadow: b.got ? '0 4px 12px rgba(0,0,0,0.12)' : 'none' }}>{b.icon}</div>
                <div style={{ fontSize: 11, color: T.sub, marginTop: 6, fontWeight: 600 }}>{b.name}</div>
              </div>
            ))}
          </div>
        </div>

        {/* appearance / theme */}
        <div style={{ ...card, padding: 18 }}>
          <div style={{ fontSize: 14.5, fontWeight: 700, color: T.ink, marginBottom: 14 }}>外观主题</div>
          {seg('模式', settings.dark ? '深色' : '浅色', ['浅色', '深色'], (v) => updateSettings({ dark: v === '深色' }))}
          {seg('配色', settings.palette, Object.keys(PALETTES), (v) => updateSettings({ palette: v }))}
          {seg('字体', settings.font, Object.keys(FONTS), (v) => updateSettings({ font: v }))}
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, color: T.sub, fontWeight: 600, marginBottom: 7 }}><span>圆角</span><span style={{ fontFamily: T.NUM, color: T.Ad }}>{settings.radius}px</span></div>
            <input type="range" min={12} max={30} step={1} value={settings.radius} onChange={(e) => updateSettings({ radius: parseInt(e.target.value, 10) })} style={{ width: '100%', accentColor: T.Ac }} />
          </div>
        </div>

        {/* settings */}
        <div style={{ ...card, padding: 0, overflow: 'hidden' }}>
          {row(<Heart size={17} color={T.Bc} />, '与 ' + names.B + ' 的关系', settings.relationship, () => fire('已绑定，互相监督中 ❤️'))}
          {row(<svg width="17" height="17" viewBox="0 0 24 24"><path d="M12 2a7 7 0 00-7 7c0 5 7 13 7 13s7-8 7-13a7 7 0 00-7-7z" stroke={T.sub} strokeWidth="2" fill="none"/><circle cx="12" cy="9" r="2.5" stroke={T.sub} strokeWidth="2" fill="none"/></svg>, '提醒时间', `每天 ${settings.remindAt}`, () => fire(`提醒已设为每天 ${settings.remindAt}`), true)}
          {row(<svg width="17" height="17" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9" stroke={T.sub} strokeWidth="2" fill="none"/><path d="M12 7v5l3 2" stroke={T.sub} strokeWidth="2" fill="none" strokeLinecap="round"/></svg>, '单位', '公斤 kg', () => fire('当前单位：公斤 kg'), true)}
          {row(<svg width="17" height="17" viewBox="0 0 24 24"><path d="M4 6h16M4 12h16M4 18h16" stroke={T.sub} strokeWidth="2" strokeLinecap="round"/></svg>, '切换角色', null, switchRole, true)}
        </div>
        <div style={{ textAlign: 'center', fontSize: 12, color: T.faint, marginTop: 2 }}>双人减肥记录 · v1.0</div>
      </div>
    </>
  );
}
window.MeScreen = MeScreen;
