// 新页面集合 - Part 3：CCI增强页、健康小贴士、新手引导、首页增强组件
// 以及 index.html 中需要的老年模式 CSS

// =====================================
// CCI 增强页面（含历史趋势图）
// =====================================
function CCIPageEnhanced({ navigate, goBack }) {
  const { state, showToast } = React.useContext(AppContext);
  const [cciData, setCciData] = React.useState(null);
  const chartRef = React.useRef(null);
  const chartInstance = React.useRef(null);

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

  React.useEffect(() => {
    if (cciData && cciData.history && cciData.history.length > 0 && chartRef.current) {
      initChart();
    }
    return () => {
      if (chartInstance.current) {
        chartInstance.current.dispose();
        chartInstance.current = null;
      }
    };
  }, [cciData]);

  async function loadData() {
    try {
      const data = await api.getCCIDetail();
      setCciData(data);
    } catch (e) {
      showToast('加载失败');
    }
  }

  function initChart() {
    if (!chartRef.current || !window.echarts || !cciData?.history?.length) return;

    if (chartInstance.current) chartInstance.current.dispose();

    const chart = echarts.init(chartRef.current);
    chartInstance.current = chart;

    const history = cciData.history;
    const dates = history.map(h => {
      const d = new Date(h.createdAt.replace(' ', 'T'));
      return `${d.getMonth() + 1}/${d.getDate()}`;
    });
    const scores = history.map(h => h.score);

    chart.setOption({
      grid: { left: 40, right: 20, top: 20, bottom: 30 },
      xAxis: {
        type: 'category',
        data: dates,
        axisLabel: { fontSize: 10, color: '#8a9390' },
        axisLine: { lineStyle: { color: '#ebe8e0' } },
      },
      yAxis: {
        type: 'value',
        min: 0,
        axisLabel: { fontSize: 10, color: '#8a9390' },
        splitLine: { lineStyle: { color: '#f0ece5' } },
      },
      series: [{
        type: 'line',
        data: scores,
        smooth: true,
        lineStyle: { color: '#3a8f7a', width: 2 },
        itemStyle: { color: '#3a8f7a' },
        areaStyle: {
          color: {
            type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(58,143,122,0.3)' },
              { offset: 1, color: 'rgba(58,143,122,0.02)' },
            ],
          },
        },
        symbol: 'circle',
        symbolSize: 6,
      }],
      tooltip: {
        trigger: 'axis',
        formatter: params => {
          const p = params[0];
          return `${p.name}<br/>CCI得分：<strong>${p.value}</strong>`;
        },
      },
    });

    window.addEventListener('resize', () => chart.resize());
  }

  const getRiskInfo = (score) => {
    if (score <= 0) return { level: '无风险', color: '#3a8f7a', desc: '当前无共病负担' };
    if (score <= 1) return { level: '低风险', color: '#3a8f7a', desc: '共病程度较轻，定期监测即可' };
    if (score <= 2) return { level: '中风险', color: '#e08b3a', desc: '存在多种慢病，建议规律随访管理' };
    if (score <= 4) return { level: '较高风险', color: '#e0784a', desc: '共病情况较复杂，建议密切关注' };
    return { level: '高风险', color: '#d85a4a', desc: '共病情况复杂，建议密切关注并定期复诊' };
  };

  const risk = cciData ? getRiskInfo(cciData.score) : null;

  return (
    <div className="page">
      <TopBar title="CCI共病指数" onBack={goBack} />

      <div style={{ padding: '12px 16px', overflowY: 'auto', height: 'calc(100% - 56px)', paddingBottom: 24 }}>
        {cciData && risk && (
          <>
            {/* 得分卡片 */}
            <div className="card" style={{ marginBottom: 16, textAlign: 'center', padding: 20 }}>
              <div style={{ fontSize: 13, color: '#8a9390', marginBottom: 8 }}>您的CCI共病指数</div>
              <div style={{ fontSize: 56, fontWeight: 700, color: risk.color, lineHeight: 1 }}>
                {cciData.score}
              </div>
              <div style={{
                marginTop: 8, display: 'inline-block',
                padding: '4px 16px', borderRadius: 14,
                background: `${risk.color}15`, color: risk.color,
                fontSize: 13, fontWeight: 600,
              }}>
                {risk.level}
              </div>
              <div style={{ fontSize: 12, color: '#8a9390', marginTop: 8 }}>
                {risk.desc}
              </div>
            </div>

            {/* 历史趋势 */}
            {cciData.history && cciData.history.length > 0 && (
              <div className="card" style={{ marginBottom: 16 }}>
                <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 12 }}>得分变化趋势</div>
                <div ref={chartRef} style={{ width: '100%', height: 180 }} />
              </div>
            )}

            {/* 疾病分值明细 */}
            <div className="card" style={{ marginBottom: 16 }}>
              <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 12 }}>疾病分值明细</div>
              {cciData.diseases.length === 0 ? (
                <div style={{ textAlign: 'center', padding: 20, color: '#8a9390', fontSize: 13 }}>
                  暂未录入慢病
                </div>
              ) : (
                cciData.diseases.map(d => (
                  <div key={d.id} style={{
                    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                    padding: '10px 0',
                    borderBottom: d.id !== cciData.diseases[cciData.diseases.length - 1].id
                      ? '1px solid #ebe8e0' : 'none',
                  }}>
                    <div>
                      <div style={{ fontWeight: 500 }}>{d.name}</div>
                      <div style={{ fontSize: 11, color: '#8a9390' }}>确诊：{d.diagnoseDate}</div>
                    </div>
                    <div style={{
                      fontSize: 18, fontWeight: 700,
                      color: d.cciScore > 0 ? '#e08b3a' : '#a3a89f',
                    }}>
                      +{d.cciScore}
                    </div>
                  </div>
                ))
              )}
            </div>

            {/* 健康建议 */}
            <div className="card">
              <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 12 }}>健康建议</div>
              <div style={{ fontSize: 13, color: '#5a6360', lineHeight: 1.8 }}>
                <div>1. 规律服药，不要自行停药或调整剂量</div>
                <div>2. 定期监测血压、血糖等关键指标</div>
                <div>3. 保持健康饮食，低盐低糖低脂</div>
                <div>4. 适度运动，每周至少150分钟中等强度有氧</div>
                <div>5. 定期复诊，每3-6个月复查相关指标</div>
                <div>6. 出现不适及时就医，避免延误病情</div>
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// =====================================
// 健康小贴士组件
// =====================================
function HealthTipCard({ diseaseNames }) {
  const [tip, setTip] = React.useState(null);
  const [tipKey, setTipKey] = React.useState(0);

  React.useEffect(() => {
    updateTip();
  }, [diseaseNames, tipKey]);

  function updateTip() {
    const today = new Date();
    const dateStr = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}-${tipKey}`;
    const t = getDailyTip(diseaseNames || [], dateStr);
    setTip(t);
  }

  if (!tip) return null;

  return (
    <div className="card" style={{ marginBottom: 12, background: 'linear-gradient(135deg, #f5f3ee 0%, #ebe8e0 100%)' }}>
      <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
        <div style={{
          width: 36, height: 36, borderRadius: '50%',
          background: 'rgba(224,139,58,0.15)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}>
          <Icon.Lightbulb color="#e08b3a" size={20} />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 12, color: '#e08b3a', fontWeight: 600, marginBottom: 4 }}>
            今日健康小贴士 · {tip.category}
          </div>
          <div style={{ fontSize: 13, color: '#5a6360', lineHeight: 1.6 }}>
            {tip.text}
          </div>
          <div style={{ marginTop: 8 }}>
            <button
              className="btn-ghost"
              style={{ fontSize: 12, color: '#8a9390', padding: '4px 10px' }}
              onClick={() => setTipKey(k => k + 1)}
            >
              <Icon.Refresh color="#8a9390" size={12} /> 换一条
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// =====================================
// 今日服药卡片（首页用）
// =====================================
function TodayMedicationCard({ navigate }) {
  const { showToast } = React.useContext(AppContext);
  const [reminders, setReminders] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    loadReminders();
    const timer = setInterval(loadReminders, 60000); // 每分钟刷新
    return () => clearInterval(timer);
  }, []);

  async function loadReminders() {
    try {
      const data = await api.getTodayReminders();
      setReminders(data);
    } catch (e) {
      // 静默失败
    } finally {
      setLoading(false);
    }
  }

  const handleStatus = async (id, status) => {
    try {
      await api.updateReminderStatus(id, status);
      loadReminders();
      showToast(status === 'taken' ? '已标记已服用' : '已更新');
    } catch (e) {
      showToast('操作失败');
    }
  };

  const pending = reminders.filter(r => r.status === 'pending').length;
  const taken = reminders.filter(r => r.status === 'taken').length;
  const total = reminders.length;
  const rate = total > 0 ? Math.round((taken / total) * 100) : 0;

  return (
    <div className="card" style={{ marginBottom: 12 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <Icon.Pill color="#3a8f7a" size={20} />
          <span style={{ fontWeight: 600 }}>今日服药</span>
          {pending > 0 && (
            <span className="chip" style={{
              fontSize: 10, padding: '1px 6px',
              background: 'rgba(224,139,58,0.1)', color: '#e08b3a',
            }}>
              {pending} 个待服
            </span>
          )}
        </div>
        <button
          className="btn-ghost"
          style={{ fontSize: 12, color: '#8a9390', padding: 0 }}
          onClick={() => navigate('medication')}
        >
          管理 <Icon.Chevron size={14} color="#8a9390" />
        </button>
      </div>

      {loading ? (
        <div style={{ textAlign: 'center', padding: 16, color: '#8a9390', fontSize: 13 }}>加载中...</div>
      ) : total === 0 ? (
        <div style={{ textAlign: 'center', padding: 16, color: '#8a9390', fontSize: 13 }}>
          暂无用药计划，去添加常用药吧
        </div>
      ) : (
        <>
          {/* 进度条 */}
          <div style={{
            height: 6, background: '#ebe8e0', borderRadius: 3,
            marginBottom: 12, overflow: 'hidden',
          }}>
            <div style={{
              height: '100%', width: `${rate}%`,
              background: '#3a8f7a', borderRadius: 3,
              transition: 'width 0.3s',
            }} />
          </div>

          {/* 列表（最多显示3条） */}
          {reminders.slice(0, 3).map(r => (
            <div key={r.id} style={{
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              padding: '8px 0',
              borderBottom: r.id !== reminders[Math.min(2, reminders.length - 1)].id ? '1px solid #ebe8e0' : 'none',
            }}>
              <div>
                <div style={{ fontSize: 14, fontWeight: 500 }}>{r.name}</div>
                <div style={{ fontSize: 11, color: '#8a9390' }}>
                  {r.dose} · {r.scheduledTime}
                </div>
              </div>
              {r.status === 'taken' ? (
                <span style={{ fontSize: 12, color: '#3a8f7a', display: 'flex', alignItems: 'center', gap: 2 }}>
                  <Icon.Check color="#3a8f7a" size={14} /> 已服用
                </span>
              ) : r.status === 'skipped' ? (
                <span style={{ fontSize: 12, color: '#e08b3a' }}>已跳过</span>
              ) : (
                <button
                  className="btn-primary"
                  style={{ fontSize: 12, padding: '4px 12px', borderRadius: 14 }}
                  onClick={() => handleStatus(r.id, 'taken')}
                >
                  已吃
                </button>
              )}
            </div>
          ))}

          {reminders.length > 3 && (
            <div style={{ textAlign: 'center', marginTop: 8 }}>
              <button
                className="btn-ghost"
                style={{ fontSize: 12, color: '#8a9390' }}
                onClick={() => navigate('medication-calendar')}
              >
                查看全部（日历视图）
              </button>
            </div>
          )}
        </>
      )}
    </div>
  );
}

// =====================================
// 首页喝水卡片
// =====================================
function WaterMiniCard({ navigate }) {
  const { showToast } = React.useContext(AppContext);
  const [waterData, setWaterData] = React.useState(null);

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

  async function loadWater() {
    try {
      const data = await api.getWaterToday();
      setWaterData(data);
    } catch (e) {
      // 静默
    }
  }

  const handleQuickAdd = async (amount) => {
    try {
      const data = await api.addWaterRecord(amount);
      setWaterData(prev => ({ ...prev, ...data }));
      showToast(`已记录 ${amount}ml`);
    } catch (e) {
      // 静默
    }
  };

  if (!waterData) return null;

  return (
    <div className="card" style={{ marginBottom: 12 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <Icon.Droplet color="#4a7dac" size={20} />
          <span style={{ fontWeight: 600 }}>今日喝水</span>
        </div>
        <button
          className="btn-ghost"
          style={{ fontSize: 12, color: '#8a9390', padding: 0 }}
          onClick={() => navigate('water')}
        >
          设置 <Icon.Chevron size={14} color="#8a9390" />
        </button>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{ position: 'relative', width: 50, height: 50, flexShrink: 0 }}>
          <svg width="50" height="50" viewBox="0 0 50 50">
            <circle cx="25" cy="25" r="20" fill="none" stroke="#e8e4dc" strokeWidth="4" />
            <circle
              cx="25" cy="25" r="20" fill="none" stroke="#4a7dac" strokeWidth="4"
              strokeLinecap="round"
              strokeDasharray={`${waterData.progress * 1.26} 126`}
              transform="rotate(-90 25 25)"
            />
          </svg>
          <div style={{
            position: 'absolute', top: '50%', left: '50%',
            transform: 'translate(-50%, -50%)', fontSize: 11, color: '#4a7dac', fontWeight: 600,
          }}>
            {waterData.progress}%
          </div>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, color: '#5a6360', marginBottom: 6 }}>
            <span style={{ fontWeight: 600, color: '#4a7dac' }}>{waterData.totalAmount}ml</span>
            <span style={{ color: '#8a9390' }}> / {waterData.goal}ml</span>
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            {[200, 250, 500].map(amt => (
              <button
                key={amt}
                onClick={() => handleQuickAdd(amt)}
                style={{
                  padding: '4px 8px', fontSize: 11,
                  background: 'rgba(74,125,172,0.1)',
                  border: 'none', borderRadius: 12,
                  color: '#4a7dac', fontWeight: 500,
                }}
              >
                +{amt}
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// =====================================
// 首页异常预警卡片
// =====================================
function AlertMiniCard({ navigate }) {
  const { showToast } = React.useContext(AppContext);
  const [abnormals, setAbnormals] = React.useState([]);

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

  async function loadData() {
    try {
      const data = await api.getAbnormalRecords(5);
      // 只显示最近7天的
      const sevenDaysAgo = Date.now() - 7 * 86400000;
      const recent = data.filter(r => {
        const t = new Date(r.time.replace(' ', 'T')).getTime();
        return t >= sevenDaysAgo;
      });
      setAbnormals(recent);
    } catch (e) {
      // 静默
    }
  }

  if (abnormals.length === 0) return null;

  return (
    <div
      className="card"
      style={{
        marginBottom: 12,
        background: 'rgba(216,90,74,0.06)',
        border: '1px solid rgba(216,90,74,0.2)',
        cursor: 'pointer',
      }}
      onClick={() => navigate('abnormal-alerts')}
    >
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
        <div style={{
          width: 36, height: 36, borderRadius: '50%',
          background: 'rgba(216,90,74,0.15)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}>
          <Icon.Alert color="#d85a4a" size={20} />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: '#d85a4a', marginBottom: 4 }}>
            近7天有 {abnormals.length} 项异常指标
          </div>
          <div style={{ fontSize: 12, color: '#8a534a' }}>
            {abnormals[0].type === 'blood_pressure'
              ? `最近：血压${abnormals[0].abnormalType === 'high' ? '偏高' : '偏低'} ${abnormals[0].value1}/${abnormals[0].value2}`
              : `最近：血糖${abnormals[0].abnormalType === 'high' ? '偏高' : '偏低'} ${abnormals[0].value1}`
            }
          </div>
        </div>
        <Icon.Chevron size={16} color="#d85a4a" />
      </div>
    </div>
  );
}

// =====================================
// 新手引导组件
// =====================================
function OnboardingGuide({ onClose, navigate, showToast }) {
  const [step, setStep] = React.useState(0);

  const steps = [
    {
      title: '欢迎使用',
      desc: '慢病共病健康管理应用\n帮您轻松管理多种慢病',
      icon: 'heart',
    },
    {
      title: '完善基础信息',
      desc: '填写您的年龄、性别、身高体重\n系统会为您推荐合适的健康建议',
      icon: 'user',
      action: '完善资料',
      actionPage: 'profile',
    },
    {
      title: '录入慢病',
      desc: '添加您已患有的慢性病\n自动计算CCI共病指数',
      icon: 'disease',
      action: '去录入',
      actionPage: 'disease',
    },
    {
      title: '添加用药',
      desc: '记录您正在服用的药物\n设置提醒时间，按时吃药不忘记',
      icon: 'pill',
      action: '去添加',
      actionPage: 'medication',
    },
    {
      title: '记录指标',
      desc: '每天记录血压血糖\n趋势图表一目了然',
      icon: 'activity',
      action: '去记录',
      actionPage: 'vitals',
    },
    {
      title: '开始使用',
      desc: '您已完成基础设置\n更多功能等您探索',
      icon: 'check',
    },
  ];

  const handleNext = () => {
    if (step < steps.length - 1) {
      setStep(step + 1);
    } else {
      completeGuide();
    }
  };

  const handleSkip = () => {
    completeGuide();
  };

  const completeGuide = async () => {
    try {
      await api.updateGuideStatus(true);
    } catch (e) { /* 忽略 */ }
    onClose();
  };

  const currentStep = steps[step];
  const iconColor = '#3a8f7a';

  const renderIcon = () => {
    switch (currentStep.icon) {
      case 'heart': return <Icon.Heart color={iconColor} size={60} />;
      case 'user': return <Icon.User color={iconColor} size={60} />;
      case 'disease': return <Icon.Record color={iconColor} size={60} />;
      case 'pill': return <Icon.Pill color={iconColor} size={60} />;
      case 'activity': return <Icon.Activity color={iconColor} size={60} />;
      case 'check': return <Icon.Check color={iconColor} size={60} />;
      default: return <Icon.Info color={iconColor} size={60} />;
    }
  };

  return (
    <div style={{
      position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
      background: 'rgba(0,0,0,0.7)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      zIndex: 1000,
    }}>
      <div style={{
        width: '85%', maxWidth: 320, background: '#faf8f3', borderRadius: 16,
        padding: 32, textAlign: 'center',
      }}>
        <div style={{
          width: 100, height: 100, margin: '0 auto 24px',
          borderRadius: '50%', background: 'rgba(58,143,122,0.1)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          {renderIcon()}
        </div>

        <div style={{ fontSize: 22, fontWeight: 700, color: '#2c3e3a', marginBottom: 12 }}>
          {currentStep.title}
        </div>
        <div style={{ fontSize: 14, color: '#8a9390', lineHeight: 1.7, whiteSpace: 'pre-line', marginBottom: 28 }}>
          {currentStep.desc}
        </div>

        {/* 进度点 */}
        <div style={{ display: 'flex', justifyContent: 'center', gap: 6, marginBottom: 24 }}>
          {steps.map((_, i) => (
            <div key={i} style={{
              width: i === step ? 20 : 8, height: 8, borderRadius: 4,
              background: i === step ? '#3a8f7a' : '#e0dcd2',
              transition: 'all 0.3s',
            }} />
          ))}
        </div>

        <div style={{ display: 'flex', gap: 10 }}>
          <button
            className="btn-outline" style={{ flex: 1 }}
            onClick={handleSkip}
          >
            跳过
          </button>
          <button
            className="btn-primary" style={{ flex: 1 }}
            onClick={handleNext}
          >
            {step === steps.length - 1 ? '开始使用' : '下一步'}
          </button>
        </div>
      </div>
    </div>
  );
}

// =====================================
// 语音朗读辅助函数（老年模式用）
// =====================================
function speakText(text) {
  if (!window.speechSynthesis) return;
  window.speechSynthesis.cancel();
  const utter = new SpeechSynthesisUtterance(text);
  utter.lang = 'zh-CN';
  utter.rate = 0.9;
  window.speechSynthesis.speak(utter);
}

// 暴露到全局
Object.assign(window, {
  CCIPageEnhanced,
  HealthTipCard,
  TodayMedicationCard,
  WaterMiniCard,
  AlertMiniCard,
  OnboardingGuide,
  speakText,
});
