// Trimester checklists — per-trimester actionable items with localStorage persistence.

const CHECKLISTS = {
  1: {
    label:'第一孕期 1–12 週',
    en:'1st Trimester',
    color:'var(--accent)',
    bg:'var(--accent-soft)',
    sections: [
      {
        title:'📋 產前檢查', en:'Prenatal Checks',
        items:[
          { id:'c1_1', zh:'確認懷孕（超音波）', en:'Confirm pregnancy via ultrasound', weekHint:[4,8] },
          { id:'c1_2', zh:'第一次正式產檢（8–10 週）', en:'First OB appointment 8–10 wks', weekHint:[8,10] },
          { id:'c1_3', zh:'NIPT 非侵入性產前檢測（10 週起）', en:'NIPT from ~10 weeks', weekHint:[10,12] },
          { id:'c1_4', zh:'初唐篩檢 / NT 超音波（11–14 週）', en:'NT scan + first trimester screen 11–14 wks', weekHint:[11,14] },
          { id:'c1_5', zh:'確認胎兒心跳（約 6–8 週）', en:'Confirm fetal heartbeat ~6–8 wks', weekHint:[6,8] },
        ]
      },
      {
        title:'💊 補充品', en:'Supplements',
        items:[
          { id:'c1_6', zh:'每日葉酸 400–800 mcg', en:'Folic acid 400–800 mcg daily' },
          { id:'c1_7', zh:'產前維生素（DHA、鐵、鈣）', en:'Prenatal vitamins with DHA, iron, calcium' },
          { id:'c1_8', zh:'維生素 D3 補充', en:'Vitamin D3 supplementation' },
        ]
      },
      {
        title:'⚠️ 生活注意', en:'Lifestyle',
        items:[
          { id:'c1_9', zh:'禁菸禁酒禁咖啡因（<200mg/日）', en:'No smoking, alcohol · limit caffeine <200mg/d' },
          { id:'c1_10', zh:'避免提重物（超過 5 公斤）', en:'Avoid lifting heavy objects >5 kg' },
          { id:'c1_11', zh:'了解孕吐應對方式', en:'Learn morning sickness management' },
          { id:'c1_12', zh:'告知工作單位（視情況）', en:'Inform workplace as appropriate' },
        ]
      },
    ]
  },
  2: {
    label:'第二孕期 13–27 週',
    en:'2nd Trimester',
    color:'var(--sage)',
    bg:'var(--sage-soft)',
    sections: [
      {
        title:'📋 產前檢查', en:'Prenatal Checks',
        items:[
          { id:'c2_1', zh:'高層次超音波（18–22 週）', en:'Anatomy scan 18–22 wks', weekHint:[18,22] },
          { id:'c2_2', zh:'妊娠糖尿病篩檢 OGTT（24–28 週）', en:'Gestational diabetes screen 24–28 wks', weekHint:[24,28] },
          { id:'c2_3', zh:'母血唐氏症篩檢（四指標）', en:'Quad screen / maternal serum screen', weekHint:[15,20] },
          { id:'c2_4', zh:'確認胎盤位置', en:'Confirm placenta location', weekHint:[18,22] },
        ]
      },
      {
        title:'💊 補充品', en:'Supplements',
        items:[
          { id:'c2_5', zh:'鈣質補充（每日 1000 mg）', en:'Calcium 1000 mg daily' },
          { id:'c2_6', zh:'鐵質補充（每日 27 mg）', en:'Iron 27 mg daily' },
          { id:'c2_7', zh:'Omega-3 / DHA 持續補充', en:'Continue DHA / Omega-3' },
        ]
      },
      {
        title:'🌸 生活注意', en:'Lifestyle',
        items:[
          { id:'c2_8', zh:'適度運動（散步 30 分鐘 / 游泳）', en:'Light exercise: walking 30min, swimming' },
          { id:'c2_9', zh:'開始按摩肚皮預防妊娠紋', en:'Begin belly massage to prevent stretch marks' },
          { id:'c2_10', zh:'購買托腹帶 / 孕婦枕', en:'Buy maternity support belt / pregnancy pillow' },
          { id:'c2_11', zh:'了解胎動感覺（約 18–22 週）', en:'Learn to identify fetal movements' },
          { id:'c2_12', zh:'安排孕婦寫真（可選）', en:'Schedule maternity photoshoot (optional)' },
        ]
      },
      {
        title:'🏠 準備工作', en:'Preparation',
        items:[
          { id:'c2_13', zh:'開始研究分娩方式與醫院', en:'Research delivery options and hospitals' },
          { id:'c2_14', zh:'參加孕婦教室 / 拉梅茲課程', en:'Join childbirth education class' },
          { id:'c2_15', zh:'準備嬰兒房 / 採購清單', en:'Plan nursery and baby shopping list' },
        ]
      },
    ]
  },
  3: {
    label:'第三孕期 28–40 週',
    en:'3rd Trimester',
    color:'#b07b5a',
    bg:'color-mix(in oklab,var(--butter) 25%,white)',
    sections: [
      {
        title:'📋 產前檢查', en:'Prenatal Checks',
        items:[
          { id:'c3_1', zh:'每週/每兩週密集產檢', en:'Bi-weekly then weekly OB visits', weekHint:[28,40] },
          { id:'c3_2', zh:'乙型鏈球菌篩檢 GBS（35–37 週）', en:'GBS screening 35–37 wks', weekHint:[35,37] },
          { id:'c3_3', zh:'確認胎位（頭位優先）', en:'Confirm fetal position (head-down ideal)', weekHint:[35,40] },
          { id:'c3_4', zh:'胎兒體重與生長評估', en:'Fetal weight and growth assessment', weekHint:[28,36] },
          { id:'c3_5', zh:'無壓力測試 NST（如有指示）', en:'Non-stress test if indicated', weekHint:[36,40] },
        ]
      },
      {
        title:'👶 胎動監測', en:'Fetal Movement',
        items:[
          { id:'c3_6', zh:'每日胎動計數（10次/2小時）', en:'Daily kick count: 10 kicks in 2 hours' },
          { id:'c3_7', zh:'記錄胎動規律', en:'Log fetal movement patterns' },
          { id:'c3_8', zh:'了解胎動減少的警示', en:'Know warning signs of decreased movement' },
        ]
      },
      {
        title:'🎒 待產準備', en:'Birth Prep',
        items:[
          { id:'c3_9', zh:'準備待產包（母嬰用品）', en:'Pack hospital bag (mom + baby items)' },
          { id:'c3_10', zh:'練習拉梅茲呼吸法', en:'Practice Lamaze breathing techniques' },
          { id:'c3_11', zh:'確認前往醫院的路線/計畫', en:'Confirm route and plan to hospital' },
          { id:'c3_12', zh:'了解產兆：陣痛、破水、落紅', en:'Learn labor signs: contractions, water breaking, bloody show' },
          { id:'c3_13', zh:'安排月子中心或協助人員', en:'Arrange postnatal care / confinement help' },
        ]
      },
      {
        title:'💪 身體保養', en:'Self-Care',
        items:[
          { id:'c3_14', zh:'預防水腫（抬腿、低鹽飲食）', en:'Prevent edema: elevate legs, low-sodium diet' },
          { id:'c3_15', zh:'練習凱格爾運動', en:'Practice Kegel exercises' },
          { id:'c3_16', zh:'控制體重增加速度', en:'Monitor weight gain rate' },
        ]
      },
    ]
  },
};

function ChecklistPage() {
  const getPregnancyWeek = () => {
    try {
      const s = JSON.parse(localStorage.getItem('preg_home') || '{}');
      let start;
      if (s.mode === 'lmp' && s.lmp)          start = new Date(s.lmp);
      else if (s.mode === 'et' && s.etDate)   { start = new Date(s.etDate); start.setDate(start.getDate()-14); }
      else if (s.mode === 'due' && s.dueDate) { start = new Date(s.dueDate); start.setDate(start.getDate()-280); }
      if (!start || isNaN(start)) return 0;
      const days = Math.floor((Date.now() - start) / 86400000);
      return days >= 0 ? Math.floor(days / 7) + 1 : 0;
    } catch(e) { return 0; }
  };

  const [activeTrim, setActiveTrim] = React.useState(() => {
    const w = getPregnancyWeek();
    if (w >= 28) return 3;
    if (w >= 13) return 2;
    return 1;
  });
  const currentWeek = React.useMemo(getPregnancyWeek, []);
  const [checked, setChecked] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('cl_checked') || '{}'); } catch(e) { return {}; }
  });

  const toggle = (id) => {
    const next = { ...checked, [id]: !checked[id] };
    setChecked(next);
    localStorage.setItem('cl_checked', JSON.stringify(next));
  };

  const trim = CHECKLISTS[activeTrim];
  const allIds = trim.sections.flatMap(s => s.items.map(i => i.id));
  const doneCount = allIds.filter(id => checked[id]).length;
  const pct = Math.round((doneCount / allIds.length) * 100);

  return (
    <div style={{ display:'flex', flexDirection:'column' }}>
      {/* Trimester tabs */}
      <div style={{
        display:'grid', gridTemplateColumns:'repeat(3,1fr)',
        borderBottom:'1px solid var(--line)',
        background:'var(--card)',
        position:'sticky', top:0, zIndex:10,
      }}>
        {[1,2,3].map(t => (
          <button key={t} className="btn-reset" onClick={() => setActiveTrim(t)} style={{
            padding:'12px 8px',
            borderBottom: activeTrim===t ? `2px solid ${CHECKLISTS[t].color}` : '2px solid transparent',
            background: activeTrim===t ? CHECKLISTS[t].bg : 'transparent',
            color: activeTrim===t ? CHECKLISTS[t].color : 'var(--ink-soft)',
            fontWeight: activeTrim===t ? 600 : 400,
            fontSize:11.5, transition:'all 0.15s',
          }}>
            <div>{['第一孕期','第二孕期','第三孕期'][t-1]}</div>
            <div style={{ fontSize:9, opacity:0.7, marginTop:1 }}>{['1–12 週','13–27 週','28–40 週'][t-1]}</div>
          </button>
        ))}
      </div>

      {/* Progress */}
      <div style={{ padding:'12px 16px 0' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:6 }}>
          <span style={{ fontSize:11.5, color:'var(--ink-soft)' }}>完成進度 · Progress</span>
          <span className="mono" style={{ fontSize:12, color: trim.color, fontWeight:600 }}>{doneCount}/{allIds.length}</span>
        </div>
        <div style={{ height:5, background:'var(--line)', borderRadius:99, overflow:'hidden' }}>
          <div style={{
            height:'100%', width:`${pct}%`,
            background: trim.color, borderRadius:99, transition:'width 0.4s',
          }}/>
        </div>
      </div>

      {/* Sections */}
      <div style={{ padding:'12px 16px 100px', display:'flex', flexDirection:'column', gap:12 }}>
        {trim.sections.map(sec => (
          <Card key={sec.title} pad="14px">
            <div style={{ display:'flex', alignItems:'baseline', gap:8, marginBottom:12 }}>
              <div style={{ fontSize:13, fontWeight:600, color:'var(--ink)' }}>{sec.title}</div>
              <div className="en" style={{ fontSize:10 }}>{sec.en}</div>
            </div>
            <div style={{ display:'flex', flexDirection:'column', gap:2 }}>
              {sec.items.map(item => {
                const isNow = !checked[item.id] && currentWeek > 0 && item.weekHint &&
                  currentWeek >= item.weekHint[0] - 1 && currentWeek <= item.weekHint[1];
                return (
                <label key={item.id} style={{
                  display:'flex', alignItems:'flex-start', gap:12,
                  padding:'9px 0',
                  borderBottom:'1px solid var(--line-soft)',
                  cursor:'pointer',
                  background: isNow ? `color-mix(in oklab,${trim.color} 6%,transparent)` : 'transparent',
                  borderRadius: isNow ? 6 : 0,
                  margin: isNow ? '0 -4px' : 0,
                  padding: isNow ? '9px 4px' : '9px 0',
                }}>
                  <div style={{
                    minWidth:22, height:22, borderRadius:6, marginTop:1,
                    border:`1.5px solid ${checked[item.id] ? trim.color : isNow ? trim.color : 'var(--line)'}`,
                    background: checked[item.id] ? trim.color : 'transparent',
                    display:'flex', alignItems:'center', justifyContent:'center',
                    transition:'all 0.15s', flexShrink:0,
                  }} onClick={() => toggle(item.id)}>
                    {checked[item.id] && (
                      <svg width="12" height="12" viewBox="0 0 12 12">
                        <polyline points="2,6 5,9 10,3" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                      </svg>
                    )}
                  </div>
                  <div style={{ opacity: checked[item.id] ? 0.45 : 1, transition:'opacity 0.15s', flex:1 }}>
                    <div style={{ display:'flex', alignItems:'center', gap:6, flexWrap:'wrap' }}>
                      <span style={{ fontSize:13, color:'var(--ink)', lineHeight:1.4,
                        textDecoration: checked[item.id] ? 'line-through' : 'none' }}>
                        {item.zh}
                      </span>
                      {isNow && (
                        <span style={{
                          fontSize:9, fontWeight:600, padding:'1px 5px', borderRadius:99,
                          background: trim.color, color:'#fff', letterSpacing:'0.04em',
                          flexShrink:0,
                        }}>本週</span>
                      )}
                    </div>
                    <div className="en" style={{ fontSize:10.5, marginTop:1 }}>{item.en}</div>
                  </div>
                </label>
                );
              })}
            </div>
          </Card>
        ))}

        {pct === 100 && (
          <div style={{
            padding:'20px', borderRadius:12, textAlign:'center',
            background: trim.bg, border:`1px solid color-mix(in oklab,${trim.color} 25%,var(--line))`,
          }}>
            <div style={{ fontSize:32, marginBottom:8 }}>🎉</div>
            <div style={{ fontSize:15, fontWeight:600, color: trim.color }}>{trim.label}全部完成！</div>
            <div className="en" style={{ fontSize:11, color:'var(--ink-soft)', marginTop:4 }}>
              All {trim.en} items checked off!
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { ChecklistPage });
