// 新页面集合 - Part 2：喝水提醒、家属监护、家庭健康报告、在线问诊、成员管理

// =====================================
// 喝水提醒页面
// =====================================
function WaterPage({ navigate, goBack }) {
  const { state, showToast } = React.useContext(AppContext);
  const [waterData, setWaterData] = React.useState(null);
  const [showSettings, setShowSettings] = React.useState(false);

  React.useEffect(() => {
    loadWater();
  }, []);

  async function loadWater() {
    try {
      const data = await api.getWaterToday();
      setWaterData(data);
    } catch (e) {
      showToast('加载失败');
    }
  }

  const handleAddWater = async (amount) => {
    try {
      const data = await api.addWaterRecord(amount);
      setWaterData(prev => ({ ...prev, ...data }));
      showToast(`已记录 ${amount}ml`);
    } catch (e) {
      showToast('记录失败');
    }
  };

  const remaining = waterData ? Math.max(0, waterData.goal - waterData.totalAmount) : 0;

  return (
    <div className="page">
      <TopBar title="喝水提醒" onBack={goBack} />

      <div style={{ padding: '16px', overflowY: 'auto', height: 'calc(100% - 56px)', paddingBottom: 24 }}>
        {waterData && (
          <>
            {/* 进度圆环 */}
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginBottom: 24 }}>
              <div style={{ position: 'relative', width: 180, height: 180 }}>
                <svg width="180" height="180" viewBox="0 0 180 180">
                  <circle cx="90" cy="90" r="75" fill="none" stroke="#e8e4dc" strokeWidth="14" />
                  <circle
                    cx="90" cy="90" r="75" fill="none"
                    stroke="#4a7dac" strokeWidth="14"
                    strokeLinecap="round"
                    strokeDasharray={`${waterData.progress * 4.71} 471`}
                    transform="rotate(-90 90 90)"
                    style={{ transition: 'stroke-dasharray 0.5s ease' }}
                  />
                </svg>
                <div style={{
                  position: 'absolute', top: '50%', left: '50%',
                  transform: 'translate(-50%, -50%)', textAlign: 'center',
                }}>
                  <div style={{ fontSize: 36, fontWeight: 700, color: '#4a7dac' }}>
                    {waterData.totalAmount}
                  </div>
                  <div style={{ fontSize: 13, color: '#8a9390' }}>
                    / {waterData.goal} ml
                  </div>
                </div>
              </div>
              <div style={{ marginTop: 12, fontSize: 13, color: '#8a9390' }}>
                还需喝 <span style={{ color: '#4a7dac', fontWeight: 600 }}>{remaining}ml</span> 达成目标
              </div>
            </div>

            {/* 快速记录 */}
            <div style={{ marginBottom: 20 }}>
              <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>快速记录</div>
              <div style={{ display: 'flex', gap: 10 }}>
                {[200, 250, 500].map(amount => (
                  <button
                    key={amount}
                    style={{
                      flex: 1, padding: '16px 0', borderRadius: 12,
                      background: 'rgba(74,125,172,0.1)',
                      border: 'none',
                      color: '#4a7dac',
                      fontWeight: 600, fontSize: 15,
                    }}
                    onClick={() => handleAddWater(amount)}
                  >
                    +{amount}ml
                  </button>
                ))}
              </div>
            </div>

            {/* 设置 */}
            <div className="card" style={{ marginBottom: 16 }}>
              <ListRow
                icon={<Icon.Settings color="#4a7dac" size={20} />}
                title="饮水目标"
                detail={`${waterData.goal} ml/天`}
                onClick={() => setShowSettings(true)}
              />
              <div className="divider" style={{ margin: 0 }} />
              <ListRow
                icon={<Icon.Bell color="#4a7dac" size={20} />}
                title="提醒间隔"
                detail={`每 ${waterData.reminderInterval} 分钟`}
                onClick={() => setShowSettings(true)}
              />
              <div className="divider" style={{ margin: 0 }} />
              <ListRow
                icon={<Icon.Calendar color="#4a7dac" size={20} />}
                title="提醒时段"
                detail={`${waterData.startTime} - ${waterData.endTime}`}
                onClick={() => setShowSettings(true)}
              />
            </div>

            {/* 今日记录 */}
            <div className="card">
              <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 12 }}>今日记录</div>
              {waterData.records.length === 0 ? (
                <div className="empty-state">
                  <div style={{ fontSize: 13, color: '#8a9390' }}>今天还没记录喝水哦</div>
                </div>
              ) : (
                waterData.records.map(r => (
                  <div key={r.id} style={{
                    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                    padding: '8px 0',
                    borderBottom: r.id !== waterData.records[waterData.records.length - 1].id ? '1px solid #ebe8e0' : 'none',
                  }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <Icon.Droplet color="#4a7dac" size={18} />
                      <span style={{ fontSize: 14 }}>{r.amount} ml</span>
                    </div>
                    <span style={{ fontSize: 12, color: '#8a9390' }}>{r.recordTime}</span>
                  </div>
                ))
              )}
            </div>
          </>
        )}
      </div>

      {/* 设置弹窗 */}
      {showSettings && (
        <WaterSettingsSheet
          data={waterData}
          onClose={() => setShowSettings(false)}
          onSave={() => { setShowSettings(false); loadWater(); showToast('设置已保存'); }}
        />
      )}
    </div>
  );
}

function WaterSettingsSheet({ data, onClose, onSave }) {
  const [goal, setGoal] = React.useState(data?.goal || 2000);
  const [interval, setInterval] = React.useState(data?.reminderInterval || 60);
  const [startTime, setStartTime] = React.useState(data?.startTime || '08:00');
  const [endTime, setEndTime] = React.useState(data?.endTime || '20:00');

  const handleSave = async () => {
    try {
      await api.updateWaterSettings({
        goal: Number(goal),
        reminderInterval: Number(interval),
        startTime, endTime,
      });
      onSave();
    } catch (e) {
      // 错误处理
    }
  };

  return (
    <BottomSheet onClose={onClose} title="喝水设置">
      <div className="form-group">
        <label>每日饮水目标 (ml)</label>
        <input type="number" value={goal} onChange={e => setGoal(e.target.value)} />
      </div>
      <div className="form-group">
        <label>提醒间隔 (分钟)</label>
        <select value={interval} onChange={e => setInterval(e.target.value)}>
          <option value="30">每 30 分钟</option>
          <option value="60">每 60 分钟</option>
          <option value="90">每 90 分钟</option>
          <option value="120">每 120 分钟</option>
        </select>
      </div>
      <div style={{ display: 'flex', gap: 10 }}>
        <div className="form-group" style={{ flex: 1 }}>
          <label>开始时间</label>
          <input type="time" value={startTime} onChange={e => setStartTime(e.target.value)} />
        </div>
        <div className="form-group" style={{ flex: 1 }}>
          <label>结束时间</label>
          <input type="time" value={endTime} onChange={e => setEndTime(e.target.value)} />
        </div>
      </div>
      <div style={{
        padding: 10, background: '#f5f3ee', borderRadius: 8,
        fontSize: 12, color: '#8a9390', marginTop: 8,
      }}>
        温馨提示：心衰、肾病患者饮水需遵医嘱，不可一次性大量饮水。
      </div>
      <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
        <button className="btn-outline" style={{ flex: 1 }} onClick={onClose}>取消</button>
        <button className="btn-primary" style={{ flex: 1 }} onClick={handleSave}>保存</button>
      </div>
    </BottomSheet>
  );
}

// =====================================
// 家属监护页面
// =====================================
function FamilyPage({ navigate, goBack }) {
  const { showToast } = React.useContext(AppContext);
  const [inviteCode, setInviteCode] = React.useState('');
  const [boundUserId, setBoundUserId] = React.useState('');
  const [overview, setOverview] = React.useState(null);
  const [showBind, setShowBind] = React.useState(false);
  const [bindInput, setBindInput] = React.useState('');
  const [guardianName, setGuardianName] = React.useState('');

  React.useEffect(() => {
    loadInviteCode();
  }, []);

  async function loadInviteCode() {
    try {
      const data = await api.getInviteCode();
      setInviteCode(data.inviteCode);
    } catch (e) {
      // 忽略
    }
  }

  const handleBind = async () => {
    if (!bindInput.trim()) return;
    try {
      const res = await api.bindFamily({ inviteCode: bindInput.trim().toUpperCase(), guardianName });
      setBoundUserId(res.boundUserId);
      loadOverview(res.boundUserId);
      setShowBind(false);
      showToast('绑定成功');
    } catch (e) {
      showToast(e.error || '绑定失败');
    }
  };

  async function loadOverview(userId) {
    try {
      const data = await api.getFamilyOverview(userId);
      setOverview(data);
    } catch (e) {
      showToast('获取数据失败');
    }
  }

  return (
    <div className="page">
      <TopBar title="家属监护" onBack={goBack} />

      <div style={{ padding: '12px 16px', overflowY: 'auto', height: 'calc(100% - 56px)', paddingBottom: 24 }}>
        {/* 我的邀请码 */}
        <div className="card" style={{ marginBottom: 16, textAlign: 'center' }}>
          <div style={{ fontSize: 13, color: '#8a9390', marginBottom: 8 }}>我的邀请码（家属用此码绑定）</div>
          <div style={{
            fontSize: 32, fontWeight: 700, color: '#3a8f7a',
            letterSpacing: 6, fontFamily: 'monospace',
          }}>
            {inviteCode || '------'}
          </div>
          <div style={{ fontSize: 12, color: '#a3a89f', marginTop: 4 }}>
            告知家属邀请码，即可让其查看您的健康数据
          </div>
        </div>

        {/* 绑定家属 */}
        <div style={{ display: 'flex', gap: 10, marginBottom: 16 }}>
          <button className="btn-outline" style={{ flex: 1 }} onClick={() => setShowBind(true)}>
            输入邀请码绑定
          </button>
          <button
            className="btn-outline"
            style={{ flex: 1 }}
            onClick={() => navigate('family-report')}
          >
            家庭健康报告
          </button>
        </div>

        {/* 被监护人概览 */}
        {overview ? (
          <div className="card">
            <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 12 }}>
              被监护人：{overview.user.name}
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 12 }}>
              <div style={{ padding: 12, background: '#f5f3ee', borderRadius: 10 }}>
                <div style={{ fontSize: 12, color: '#8a9390' }}>CCI得分</div>
                <div style={{ fontSize: 22, fontWeight: 700, color: getRiskColor(overview.risk) }}>
                  {overview.cciScore}
                </div>
                <div style={{ fontSize: 11, color: '#8a9390' }}>{overview.risk}</div>
              </div>
              <div style={{ padding: 12, background: '#f5f3ee', borderRadius: 10 }}>
                <div style={{ fontSize: 12, color: '#8a9390' }}>服药完成率</div>
                <div style={{ fontSize: 22, fontWeight: 700, color: '#3a8f7a' }}>
                  {overview.medicationRate}%
                </div>
                <div style={{ fontSize: 11, color: '#8a9390' }}>近7天</div>
              </div>
            </div>

            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0' }}>
              <span style={{ fontSize: 13 }}>慢病数量</span>
              <span style={{ fontSize: 13, fontWeight: 500 }}>{overview.diseases.length} 种</span>
            </div>
            <div className="divider" style={{ margin: 0 }} />
            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0' }}>
              <span style={{ fontSize: 13 }}>近7天血压记录</span>
              <span style={{ fontSize: 13, fontWeight: 500 }}>{overview.recentBP.length} 条</span>
            </div>
            <div className="divider" style={{ margin: 0 }} />
            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0' }}>
              <span style={{ fontSize: 13 }}>近7天血糖记录</span>
              <span style={{ fontSize: 13, fontWeight: 500 }}>{overview.recentBS.length} 条</span>
            </div>
            <div className="divider" style={{ margin: 0 }} />
            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0' }}>
              <span style={{ fontSize: 13 }}>异常指标</span>
              <span style={{
                fontSize: 13, fontWeight: 500,
                color: overview.abnormalCount > 0 ? '#d85a4a' : '#3a8f7a',
              }}>
                {overview.abnormalCount} 项
              </span>
            </div>

            {overview.diseases.length > 0 && (
              <>
                <div className="divider" />
                <div style={{ fontSize: 13, color: '#8a9390', marginBottom: 6 }}>当前慢病</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {overview.diseases.map((d, i) => (
                    <span key={i} className="chip" style={{
                      background: 'rgba(58,143,122,0.1)', color: '#3a8f7a', fontSize: 12,
                    }}>
                      {d.name}
                    </span>
                  ))}
                </div>
              </>
            )}
          </div>
        ) : boundUserId ? (
          <div style={{ textAlign: 'center', padding: 20, color: '#8a9390' }}>加载中...</div>
        ) : (
          <div className="empty-state">
            <Icon.Users color="#a3a89f" size={40} />
            <div style={{ marginTop: 12, fontSize: 14, color: '#8a9390' }}>暂无绑定的家属</div>
            <div style={{ marginTop: 4, fontSize: 12, color: '#a3a89f' }}>输入邀请码查看家属健康数据</div>
          </div>
        )}
      </div>

      {/* 绑定弹窗 */}
      {showBind && (
        <BottomSheet onClose={() => setShowBind(false)} title="绑定家属">
          <div className="form-group">
            <label>邀请码</label>
            <input
              type="text" value={bindInput}
              onChange={e => setBindInput(e.target.value.toUpperCase())}
              placeholder="请输入6位邀请码"
              maxLength={6}
              style={{ letterSpacing: 3, fontSize: 18, textAlign: 'center' }}
            />
          </div>
          <div className="form-group">
            <label>您的称呼（选填）</label>
            <input
              type="text" value={guardianName}
              onChange={e => setGuardianName(e.target.value)}
              placeholder="如：儿子、女儿、配偶"
            />
          </div>
          <div style={{ display: 'flex', gap: 10, marginTop: 8 }}>
            <button className="btn-outline" style={{ flex: 1 }} onClick={() => setShowBind(false)}>取消</button>
            <button className="btn-primary" style={{ flex: 1 }} onClick={handleBind}>绑定</button>
          </div>
        </BottomSheet>
      )}
    </div>
  );
}

function getRiskColor(risk) {
  if (risk && risk.includes('高')) return '#d85a4a';
  if (risk && risk.includes('中')) return '#e08b3a';
  return '#3a8f7a';
}

// =====================================
// 家庭健康报告页面
// =====================================
function FamilyReportPage({ navigate, goBack }) {
  const { showToast } = React.useContext(AppContext);
  const [range, setRange] = React.useState('week');
  const [report, setReport] = React.useState(null);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    loadReport();
  }, [range]);

  async function loadReport() {
    setLoading(true);
    try {
      const data = await api.getFamilyReport(range);
      setReport(data);
    } catch (e) {
      showToast('加载失败');
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="page">
      <TopBar title="家庭健康报告" onBack={goBack} />

      <div style={{ padding: '12px 16px', overflowY: 'auto', height: 'calc(100% - 56px)', paddingBottom: 24 }}>
        {/* 时间范围 */}
        <div style={{ display: 'flex', background: '#efece5', borderRadius: 10, padding: 4, marginBottom: 16 }}>
          {[
            { key: 'week', label: '本周' },
            { key: 'month', label: '本月' },
          ].map(t => (
            <button
              key={t.key}
              style={{
                flex: 1, padding: '8px 12px', borderRadius: 7,
                border: 'none',
                background: range === t.key ? '#fff' : 'transparent',
                color: range === t.key ? '#3a8f7a' : '#8a9390',
                fontWeight: range === t.key ? 600 : 400, fontSize: 14,
                boxShadow: range === t.key ? '0 2px 8px rgba(0,0,0,0.06)' : 'none',
              }}
              onClick={() => setRange(t.key)}
            >
              {t.label}
            </button>
          ))}
        </div>

        {loading ? (
          <div style={{ textAlign: 'center', padding: 40, color: '#8a9390' }}>加载中...</div>
        ) : report && report.report.length > 0 ? (
          report.report.map(m => (
            <div key={m.memberId} className="card" style={{ marginBottom: 16 }}>
              <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 12 }}>
                {m.name}
                {m.relation && <span style={{ fontSize: 12, color: '#8a9390', fontWeight: 400, marginLeft: 6 }}>
                  ({m.relation})
                </span>}
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                <div style={{ padding: 12, background: '#f5f3ee', borderRadius: 10 }}>
                  <div style={{ fontSize: 12, color: '#8a9390' }}>服药依从率</div>
                  <div style={{ fontSize: 24, fontWeight: 700, color: '#3a8f7a' }}>
                    {m.medicationRate !== null ? `${m.medicationRate}%` : '--'}
                  </div>
                </div>
                <div style={{ padding: 12, background: '#f5f3ee', borderRadius: 10 }}>
                  <div style={{ fontSize: 12, color: '#8a9390' }}>CCI得分</div>
                  <div style={{ fontSize: 24, fontWeight: 700, color: getRiskColor(m.cciScore > 3 ? '高风险' : m.cciScore > 1 ? '中风险' : '低风险') }}>
                    {m.cciScore}
                  </div>
                </div>
                <div style={{ padding: 12, background: '#f5f3ee', borderRadius: 10 }}>
                  <div style={{ fontSize: 12, color: '#8a9390' }}>血压达标率</div>
                  <div style={{ fontSize: 24, fontWeight: 700, color: '#4a7dac' }}>
                    {m.bpCount > 0 ? `${m.bpRate}%` : '--'}
                  </div>
                </div>
                <div style={{ padding: 12, background: '#f5f3ee', borderRadius: 10 }}>
                  <div style={{ fontSize: 12, color: '#8a9390' }}>血糖达标率</div>
                  <div style={{ fontSize: 24, fontWeight: 700, color: '#4a7dac' }}>
                    {m.bsCount > 0 ? `${m.bsRate}%` : '--'}
                  </div>
                </div>
              </div>

              {m.abnormalCount > 0 && (
                <div style={{
                  marginTop: 12, padding: 10,
                  background: 'rgba(216,90,74,0.08)', borderRadius: 8,
                  fontSize: 13, color: '#d85a4a',
                }}>
                  本期异常指标共 {m.abnormalCount} 次，建议关注并及时就医复查
                </div>
              )}

              {m.cciChanged !== 0 && (
                <div style={{
                  marginTop: 12, padding: 10,
                  background: 'rgba(224,139,58,0.08)', borderRadius: 8,
                  fontSize: 13, color: '#e08b3a',
                }}>
                  CCI得分较上期 {m.cciChanged > 0 ? '上升' : '下降'} {Math.abs(m.cciChanged)} 分
                  {m.cciChanged > 0 ? '，需加强慢病管理' : '，管理效果良好'}
                </div>
              )}
            </div>
          ))
        ) : (
          <div className="empty-state">
            <Icon.File color="#a3a89f" size={40} />
            <div style={{ marginTop: 12, fontSize: 14, color: '#8a9390' }}>暂无报告数据</div>
          </div>
        )}

        {report && (
          <div style={{
            marginTop: 8, padding: 12, background: '#f5f3ee', borderRadius: 10,
            fontSize: 11, color: '#8a9390', textAlign: 'center',
          }}>
            统计周期：{report.startDate} 至 {report.endDate}
          </div>
        )}
      </div>
    </div>
  );
}

// =====================================
// 在线问诊入口页面
// =====================================
function OnlineConsultPage({ navigate, goBack }) {
  const [showChecklist, setShowChecklist] = React.useState(false);

  return (
    <div className="page">
      <TopBar title="在线问诊" onBack={goBack} />

      <div style={{ padding: '12px 16px', overflowY: 'auto', height: 'calc(100% - 56px)', paddingBottom: 24 }}>
        {/* 提示卡片 */}
        <div style={{
          padding: 14, background: 'rgba(58,143,122,0.08)', borderRadius: 12,
          marginBottom: 16, fontSize: 13, color: '#3a8f7a', lineHeight: 1.6,
        }}>
          <div style={{ fontWeight: 600, marginBottom: 4 }}>温馨提示</div>
          本工具不提供在线问诊服务，以下为第三方互联网医院入口导航，
          请根据自身需求选择合适的平台。
        </div>

        {/* 就诊准备清单 */}
        <div className="card" style={{ marginBottom: 16 }}>
          <div
            style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', cursor: 'pointer' }}
            onClick={() => setShowChecklist(!showChecklist)}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <Icon.Check color="#3a8f7a" size={20} />
              <span style={{ fontWeight: 600 }}>就诊前准备清单</span>
            </div>
            <Icon.Chevron
              size={18} color="#8a9390"
              style={{ transform: showChecklist ? 'rotate(90deg)' : 'rotate(0deg)', transition: 'transform 0.2s' }}
            />
          </div>
          {showChecklist && (
            <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid #ebe8e0' }}>
              {PRE_CONSULTATION_CHECKLIST.map((item, i) => (
                <div key={i} style={{
                  display: 'flex', alignItems: 'flex-start', gap: 8,
                  padding: '6px 0', fontSize: 13, color: '#5a6360',
                }}>
                  <span style={{ color: '#3a8f7a' }}>•</span>
                  <span>{item}</span>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 平台列表 */}
        <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 12 }}>推荐平台</div>
        {ONLINE_CONSULTATION_PLATFORMS.map(p => (
          <div key={p.name} className="card" style={{ marginBottom: 12 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 4 }}>{p.name}</div>
                <div style={{ fontSize: 12, color: '#8a9390', marginBottom: 8 }}>
                  {p.description}
                </div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginBottom: 8 }}>
                  {p.features.map(f => (
                    <span key={f} className="chip" style={{
                      fontSize: 11, padding: '2px 8px',
                      background: 'rgba(58,143,122,0.1)', color: '#3a8f7a',
                    }}>
                      {f}
                    </span>
                  ))}
                </div>
                <div style={{ display: 'flex', gap: 16, fontSize: 12, color: '#8a9390' }}>
                  <span>价格：{p.price}</span>
                  <span>{p.response}</span>
                </div>
              </div>
            </div>
            <div style={{ marginTop: 12 }}>
              <a
                href={p.url} target="_blank" rel="noopener noreferrer"
                style={{
                  display: 'block', textAlign: 'center', padding: '10px',
                  background: '#3a8f7a', color: '#fff', borderRadius: 8,
                  fontSize: 14, fontWeight: 500, textDecoration: 'none',
                }}
              >
                前往 {p.name}
              </a>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// =====================================
// 成员管理页面
// =====================================
function MembersPage({ navigate, goBack }) {
  const { showToast } = React.useContext(AppContext);
  const [members, setMembers] = React.useState([]);
  const [showAdd, setShowAdd] = React.useState(false);
  const [editing, setEditing] = React.useState(null);

  React.useEffect(() => {
    loadMembers();
  }, []);

  async function loadMembers() {
    try {
      const data = await api.getFamilyMembers();
      setMembers(data);
    } catch (e) {
      showToast('加载失败');
    }
  }

  const handleDelete = async (id, name) => {
    if (!confirm(`确定删除成员"${name}"吗？相关数据将解除关联。`)) return;
    try {
      await api.deleteFamilyMember(id);
      loadMembers();
      showToast('已删除');
    } catch (e) {
      showToast('删除失败');
    }
  };

  return (
    <div className="page">
      <TopBar title="成员管理" onBack={goBack} />

      <div style={{ padding: '12px 16px', overflowY: 'auto', height: 'calc(100% - 56px)', paddingBottom: 80 }}>
        <div style={{ fontSize: 12, color: '#8a9390', marginBottom: 12 }}>
          一个账号可管理多位家庭成员的健康档案
        </div>

        {members.map(m => (
          <div key={m.id} className="card" style={{ marginBottom: 12 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{
                width: 48, height: 48, borderRadius: '50%',
                background: m.avatarColor || '#3a8f7a',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: '#fff', fontWeight: 600, fontSize: 18, flexShrink: 0,
              }}>
                {(m.name || '?').charAt(0)}
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600, fontSize: 16 }}>
                  {m.name}
                  {m.isSelf && (
                    <span className="chip" style={{
                      marginLeft: 8, fontSize: 10, padding: '1px 6px',
                      background: 'rgba(58,143,122,0.1)', color: '#3a8f7a',
                    }}>本人</span>
                  )}
                </div>
                <div style={{ fontSize: 12, color: '#8a9390' }}>
                  {m.relation || '未设置关系'} · {m.age || '?'}岁 · {m.gender}
                </div>
              </div>
              <button
                className="btn-ghost"
                style={{ padding: 6 }}
                onClick={() => setEditing(m)}
              >
                <Icon.Edit color="#8a9390" size={16} />
              </button>
              {!m.isSelf && (
                <button
                  className="btn-ghost"
                  style={{ padding: 6 }}
                  onClick={() => handleDelete(m.id, m.name)}
                >
                  <Icon.Trash color="#d85a4a" size={16} />
                </button>
              )}
            </div>
          </div>
        ))}

        <button className="btn-outline" style={{ width: '100%' }} onClick={() => setShowAdd(true)}>
          + 添加家庭成员
        </button>
      </div>

      {/* 新增/编辑弹窗 */}
      {(showAdd || editing) && (
        <BottomSheet
          onClose={() => { setShowAdd(false); setEditing(null); }}
          title={editing ? '编辑成员' : '添加成员'}
        >
          <MemberForm
            member={editing}
            onSuccess={() => {
              setShowAdd(false); setEditing(null);
              loadMembers();
              showToast(editing ? '已更新' : '已添加');
            }}
            onCancel={() => { setShowAdd(false); setEditing(null); }}
          />
        </BottomSheet>
      )}
    </div>
  );
}

function MemberForm({ member, onSuccess, onCancel }) {
  const { showToast } = React.useContext(AppContext);
  const [name, setName] = React.useState(member?.name || '');
  const [relation, setRelation] = React.useState(member?.relation || '');
  const [age, setAge] = React.useState(member?.age || '');
  const [gender, setGender] = React.useState(member?.gender || '男');

  const handleSubmit = async () => {
    if (!name.trim()) { showToast('请输入姓名'); return; }
    try {
      if (member) {
        await api.updateFamilyMember(member.id, {
          name, relation, age: Number(age) || 0, gender,
        });
      } else {
        await api.addFamilyMember({
          name, relation, age: Number(age) || 0, gender,
        });
      }
      onSuccess();
    } catch (e) {
      showToast('保存失败');
    }
  };

  return (
    <div>
      <div className="form-group">
        <label>姓名 *</label>
        <input type="text" value={name} onChange={e => setName(e.target.value)} placeholder="请输入姓名" />
      </div>
      <div className="form-group">
        <label>关系</label>
        <input type="text" value={relation} onChange={e => setRelation(e.target.value)} placeholder="如：父亲、母亲、配偶" />
      </div>
      <div style={{ display: 'flex', gap: 10 }}>
        <div className="form-group" style={{ flex: 1 }}>
          <label>年龄</label>
          <input type="number" value={age} onChange={e => setAge(e.target.value)} />
        </div>
        <div className="form-group" style={{ flex: 1 }}>
          <label>性别</label>
          <select value={gender} onChange={e => setGender(e.target.value)}>
            <option value="男">男</option>
            <option value="女">女</option>
          </select>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 10, marginTop: 8 }}>
        <button className="btn-outline" style={{ flex: 1 }} onClick={onCancel}>取消</button>
        <button className="btn-primary" style={{ flex: 1 }} onClick={handleSubmit}>保存</button>
      </div>
    </div>
  );
}

// 暴露到全局
Object.assign(window, {
  WaterPage,
  WaterSettingsSheet,
  FamilyPage,
  FamilyReportPage,
  OnlineConsultPage,
  MembersPage,
  MemberForm,
});
