// wearable.jsx — Health Connect & biometrics surfaces (trainee + trainer)

const WEARABLE_DEFAULTS = {
  connected: true,
  source: 'apple', // 'apple' | 'google' | 'garmin'
  always: {
    steps: true,
    workouts: true,
    activeEnergy: true,
    heartRate: true,
    standHours: false,
  },
  daily: {
    sleep:    { granted: true,  expires: 'พรุ่งนี้ 23:59' },
    hrv:      { granted: false, requested: true,  msg: 'โค้ชขอดู HRV วันนี้' },
    weight:   { granted: false, requested: false },
    bloodOxy: { granted: false, requested: false },
    bodyFat:  { granted: false, requested: false },
  },
};

const WEARABLE_DATA = {
  steps: 8420, stepsGoal: 10000,
  activeEnergy: 412, energyGoal: 600,
  workouts: [
    { time:'07:12', t:'Strength · Lower body', dur:42, kcal:286, hrAvg:128, hrMax:162 },
  ],
  hr: { resting:58, current:72, zones:[12,28,18,8,2] }, // mins in z1..z5 today
  sleep: { total:'6h 42m', deep:'1h 18m', rem:'1h 22m', score:78, bedtime:'00:08', wake:'06:50' },
  hrv: 48, // ms
};

// ── Trainee — health connect / permissions screen
function TraineeHealthConnect({ dark, onClose, settings, setSettings }) {
  const T = tokens(dark);
  const s = settings;
  const setAlways = (k, v) => setSettings({...s, always:{...s.always, [k]:v}});
  const grantDaily = (k) => setSettings({...s, daily:{...s.daily, [k]:{...s.daily[k], granted:true, requested:false, expires:'วันนี้ 23:59'}}});
  const denyDaily = (k) => setSettings({...s, daily:{...s.daily, [k]:{...s.daily[k], requested:false}}});

  const sourceLabel = s.source==='apple' ? 'Apple Health' : s.source==='google' ? 'Google Health Connect' : 'Garmin';
  const sourceIcon = s.source==='apple' ? '' : s.source==='google' ? '' : '';
  const pendingCount = Object.values(s.daily).filter(d=>d.requested).length;

  return (
    <div style={{ background:T.bg, minHeight:'100%', paddingBottom:120 }}>
      <PhoneStatus dark={dark}/>
      <div style={{ padding:'4px 16px 0', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
        <button onClick={onClose} style={{ width:36, height:36, borderRadius:18, background:T.card, border:`0.5px solid ${T.line}`, display:'flex', alignItems:'center', justifyContent:'center' }}>
          <Icon name="back" size={18} color={T.ink}/>
        </button>
        <div style={{ fontSize:14, fontWeight:700, color:T.ink }}>Health Connect</div>
        <div style={{ width:36 }}/>
      </div>

      {/* hero — connected device */}
      <div style={{ padding:'14px 16px 0' }}>
        <div style={{ background: dark?'linear-gradient(135deg,#1A2210,#0E1110)':'linear-gradient(135deg,#DDF1A8,#C9F76F)', borderRadius:22, padding:18, border:`0.5px solid ${T.line}`, position:'relative', overflow:'hidden' }}>
          <div style={{ display:'flex', alignItems:'center', gap:14 }}>
            <div style={{ width:56, height:56, borderRadius:14, background:dark?'rgba(255,255,255,0.06)':'rgba(255,255,255,0.7)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:30 }}>
              {s.source==='apple'?'⌚':s.source==='google'?'⌚':'⌚'}
            </div>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:11, fontWeight:700, letterSpacing:1.2, color:dark?'#C9F76F':'#3D5C0E', textTransform:'uppercase' }}>เชื่อมต่อแล้ว</div>
              <div style={{ fontSize:18, fontWeight:700, color:dark?'#F4F7F4':'#1B2710', marginTop:2, letterSpacing:-0.3 }}>{sourceLabel}</div>
              <div style={{ fontSize:12, color:dark?'rgba(244,247,244,.7)':'#3D5C0E', marginTop:2 }}>sync ล่าสุด · 2 นาที</div>
            </div>
            <div style={{ width:10, height:10, borderRadius:5, background:'#41A55E', boxShadow:'0 0 0 4px rgba(65,165,94,0.25)' }}/>
          </div>
          <div style={{ display:'flex', gap:8, marginTop:14 }}>
            {[
              {l:'ก้าว', v:`${(WEARABLE_DATA.steps/1000).toFixed(1)}k`, of:'10k'},
              {l:'พลังงาน', v:WEARABLE_DATA.activeEnergy, of:`/${WEARABLE_DATA.energyGoal}`},
              {l:'HR avg', v:WEARABLE_DATA.hr.current, of:'bpm'},
            ].map(k=>(
              <div key={k.l} style={{ flex:1, background:dark?'rgba(255,255,255,0.06)':'rgba(255,255,255,0.6)', borderRadius:12, padding:'8px 10px' }}>
                <div style={{ fontSize:9, color:dark?'rgba(244,247,244,.7)':'#3D5C0E', fontWeight:700, letterSpacing:0.4, textTransform:'uppercase' }}>{k.l}</div>
                <div style={{ fontSize:18, fontWeight:700, color:dark?'#F4F7F4':'#1B2710', fontFamily:'"Plus Jakarta Sans"', letterSpacing:-0.3 }}>{k.v}<span style={{ fontSize:10, color:dark?'rgba(244,247,244,.6)':'rgba(27,39,16,.55)', fontWeight:600 }}> {k.of}</span></div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* pending requests from coach */}
      {pendingCount>0 && (
        <div style={{ padding:'14px 16px 0' }}>
          <div style={{ fontSize:11, fontWeight:700, color:T.ink2, letterSpacing:0.5, textTransform:'uppercase', marginBottom:8, display:'flex', alignItems:'center', gap:6 }}>
            คำขอจากโค้ช <span style={{ background:'#FF8273', color:'#fff', borderRadius:99, padding:'1px 6px', fontSize:10 }}>{pendingCount}</span>
          </div>
          <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
            {Object.entries(s.daily).filter(([_,d])=>d.requested).map(([k,d])=>{
              const meta = METRIC_META[k];
              return (
                <div key={k} style={{ background:T.card, borderRadius:16, padding:12, border:`1px solid ${dark?'rgba(255,179,107,0.3)':'rgba(255,138,51,0.25)'}` }}>
                  <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                    <Avatar name="Coach Jin" tone="#FFD66B" size={32}/>
                    <div style={{ flex:1 }}>
                      <div style={{ fontSize:13, fontWeight:700, color:T.ink }}>{meta.label} <span style={{ color:T.ink3, fontWeight:500 }}>· วันนี้</span></div>
                      <div style={{ fontSize:11, color:T.ink2, marginTop:2 }}>{d.msg || `โค้ชขอดู ${meta.label} วันนี้เพื่อปรับแผน`}</div>
                    </div>
                  </div>
                  <div style={{ display:'flex', gap:8, marginTop:10 }}>
                    <button onClick={()=>denyDaily(k)} style={{ flex:1, height:38, borderRadius:12, border:`0.5px solid ${T.line}`, background:T.card, color:T.ink, fontSize:13, fontWeight:600, cursor:'pointer' }}>ไม่อนุญาต</button>
                    <button onClick={()=>grantDaily(k)} style={{ flex:1, height:38, borderRadius:12, border:0, background:T.brand, color:T.brandInk, fontSize:13, fontWeight:700, cursor:'pointer' }}>อนุญาต 24 ชม.</button>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* always-on metrics */}
      <div style={{ padding:'18px 16px 0' }}>
        <div style={{ fontSize:11, fontWeight:700, color:T.ink2, letterSpacing:0.5, textTransform:'uppercase', marginBottom:4 }}>แชร์ตลอด · Always-on</div>
        <div style={{ fontSize:11, color:T.ink3, marginBottom:10 }}>โค้ชดูได้ทุกเมื่อ — ปิดได้ตลอดเวลา</div>
        <div style={{ background:T.card, borderRadius:16, border:`0.5px solid ${T.line}` }}>
          {[
            {k:'steps', l:'ก้าวเดิน', sub:'จำนวนก้าวรายวัน', icon:'wave'},
            {k:'workouts', l:'การออกกำลัง', sub:'workout sessions + HR', icon:'dumbbell'},
            {k:'activeEnergy', l:'Active energy', sub:'พลังงานที่เผาผลาญ', icon:'flame'},
            {k:'heartRate', l:'อัตราการเต้นหัวใจ', sub:'resting + workout HR', icon:'wave'},
            {k:'standHours', l:'ชั่วโมงยืน', sub:'stand hours', icon:'gauge'},
          ].map((m,i,arr)=>(
            <div key={m.k} style={{ display:'flex', alignItems:'center', gap:12, padding:'12px 14px', borderBottom: i<arr.length-1?`0.5px solid ${T.line}`:0 }}>
              <div style={{ width:36, height:36, borderRadius:10, background:T.chip, display:'flex', alignItems:'center', justifyContent:'center' }}>
                <Icon name={m.icon} size={18} color={T.ink}/>
              </div>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:13, fontWeight:600, color:T.ink }}>{m.l}</div>
                <div style={{ fontSize:11, color:T.ink2, marginTop:1 }}>{m.sub}</div>
              </div>
              <button onClick={()=>setAlways(m.k, !s.always[m.k])} style={{
                position:'relative', width:42, height:24, borderRadius:99, border:0, cursor:'pointer',
                background: s.always[m.k] ? '#41A55E' : T.line, transition:'background 0.15s', padding:0,
              }}>
                <span style={{
                  position:'absolute', top:2, left: s.always[m.k]?20:2,
                  width:20, height:20, borderRadius:10, background:'#fff',
                  boxShadow:'0 1px 3px rgba(0,0,0,0.25)', transition:'left 0.15s',
                }}/>
              </button>
            </div>
          ))}
        </div>
      </div>

      {/* by-request metrics */}
      <div style={{ padding:'18px 16px 0' }}>
        <div style={{ fontSize:11, fontWeight:700, color:T.ink2, letterSpacing:0.5, textTransform:'uppercase', marginBottom:4 }}>ขอเป็นวันๆ · By-request</div>
        <div style={{ fontSize:11, color:T.ink3, marginBottom:10 }}>โค้ชต้องขอ ลูกเทรนอนุญาตทีละครั้ง · หมดอายุ 24 ชม.</div>
        <div style={{ background:T.card, borderRadius:16, border:`0.5px solid ${T.line}` }}>
          {Object.entries(s.daily).map(([k,d],i,arr)=>{
            const meta = METRIC_META[k];
            return (
              <div key={k} style={{ display:'flex', alignItems:'center', gap:12, padding:'12px 14px', borderBottom: i<arr.length-1?`0.5px solid ${T.line}`:0 }}>
                <div style={{ width:36, height:36, borderRadius:10, background:T.chip, display:'flex', alignItems:'center', justifyContent:'center' }}>
                  <Icon name={meta.icon} size={18} color={T.ink}/>
                </div>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:13, fontWeight:600, color:T.ink }}>{meta.label}</div>
                  <div style={{ fontSize:11, color:d.granted?T.good:d.requested?'#FF8A33':T.ink3, marginTop:1, fontWeight:d.granted||d.requested?600:400 }}>
                    {d.granted ? `แชร์อยู่ · ${d.expires}` : d.requested ? 'มีคำขอใหม่' : 'ไม่ได้แชร์'}
                  </div>
                </div>
                {d.granted && <Pill kind="good" dark={dark}>active</Pill>}
                {d.requested && <Pill kind="warn" dark={dark}>1 คำขอ</Pill>}
                {!d.granted && !d.requested && <Icon name="lock" size={16} color={T.ink3}/>}
              </div>
            );
          })}
        </div>
      </div>

      {/* footer */}
      <div style={{ padding:'18px 16px 0' }}>
        <div style={{ fontSize:11, color:T.ink3, lineHeight:1.5, padding:'10px 14px', background:T.chip, borderRadius:12 }}>
          🔒 <b style={{ color:T.ink2 }}>Privacy:</b> ข้อมูล by-request จะหมดอายุอัตโนมัติทุก 24 ชม. คุณสามารถปิดได้ทุกเมื่อจากหน้านี้
        </div>
      </div>
    </div>
  );
}

const METRIC_META = {
  sleep:    { label:'การนอน', icon:'moon' },
  hrv:      { label:'HRV (ความเครียด)', icon:'wave' },
  weight:   { label:'น้ำหนักจาก smart scale', icon:'gauge' },
  bloodOxy: { label:'Blood oxygen (SpO₂)', icon:'water' },
  bodyFat:  { label:'Body composition', icon:'target' },
};

// ── Card embedded in TraineeMe / TraineeHome — biometrics summary
function BiometricsCard({ dark, onOpen, settings }) {
  const T = tokens(dark);
  const pending = Object.values(settings.daily).filter(d=>d.requested).length;
  const w = WEARABLE_DATA;
  return (
    <div style={{ background:T.card, borderRadius:18, padding:14, border:`0.5px solid ${T.line}` }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:10 }}>
        <div>
          <div style={{ fontSize:11, color:T.ink3, fontWeight:700, letterSpacing:0.5, textTransform:'uppercase' }}>จาก Apple Health</div>
          <div style={{ fontSize:14, fontWeight:700, color:T.ink, marginTop:2 }}>วันนี้ · ⌚ sync 2 นาที</div>
        </div>
        <button onClick={onOpen} style={{ background:T.chip, border:0, padding:'6px 10px', borderRadius:99, fontSize:11, fontWeight:700, color:T.ink, position:'relative', cursor:'pointer' }}>
          จัดการ
          {pending>0 && <span style={{ position:'absolute', top:-3, right:-3, background:'#FF8273', color:'#fff', borderRadius:99, padding:'1px 5px', fontSize:9, fontWeight:700 }}>{pending}</span>}
        </button>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:8 }}>
        {[
          {l:'ก้าว', v:`${(w.steps/1000).toFixed(1)}k`, sub:`/${w.stepsGoal/1000}k`, c:'#41A55E', p:w.steps/w.stepsGoal},
          {l:'kcal', v:w.activeEnergy, sub:`/${w.energyGoal}`, c:'#FF8A33', p:w.activeEnergy/w.energyGoal},
          {l:'HR rest', v:w.hr.resting, sub:'bpm', c:'#E1573B', p:0.5},
        ].map(m=>(
          <div key={m.l} style={{ background:T.chip, borderRadius:12, padding:10 }}>
            <div style={{ fontSize:9, color:T.ink3, fontWeight:700, letterSpacing:0.4, textTransform:'uppercase' }}>{m.l}</div>
            <div style={{ fontSize:18, fontWeight:700, color:T.ink, fontFamily:'"Plus Jakarta Sans"', letterSpacing:-0.3, marginTop:2 }}>{m.v}<span style={{ fontSize:10, color:T.ink3, fontWeight:500 }}> {m.sub}</span></div>
            <div style={{ height:3, borderRadius:2, background:T.line, overflow:'hidden', marginTop:6 }}>
              <div style={{ width:`${Math.min(m.p,1)*100}%`, height:'100%', background:m.c }}/>
            </div>
          </div>
        ))}
      </div>
      {pending>0 && (
        <button onClick={onOpen} style={{
          marginTop:10, width:'100%', height:40, borderRadius:12, border:0, cursor:'pointer',
          background: dark?'rgba(255,179,107,0.15)':'rgba(255,138,51,0.12)', color:dark?'#FFB36B':'#9C4A0E',
          fontSize:12, fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center', gap:6,
        }}>
          🔔 โค้ชจินขอดู HRV วันนี้ · กดเพื่อตอบ
        </button>
      )}
    </div>
  );
}

// ── Trainer view — biometrics panel inside trainee detail
function TrainerBiometricsPanel({ dark, onRequest, settings }) {
  const T = tokens(dark);
  const w = WEARABLE_DATA;
  return (
    <div style={{ background:T.card, borderRadius:18, padding:14, border:`0.5px solid ${T.line}` }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:10 }}>
        <div>
          <div style={{ fontSize:11, color:T.ink3, fontWeight:700, letterSpacing:0.5, textTransform:'uppercase' }}>Biometrics · ⌚ live</div>
          <div style={{ fontSize:14, fontWeight:700, color:T.ink, marginTop:2 }}>จาก Apple Health</div>
        </div>
        <Pill kind="good" dark={dark}>● sync 2m</Pill>
      </div>
      {/* always-on grid */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8 }}>
        <div style={{ background:T.chip, borderRadius:12, padding:10 }}>
          <div style={{ fontSize:9, color:T.ink3, fontWeight:700, letterSpacing:0.4, textTransform:'uppercase' }}>ก้าวเดิน</div>
          <div style={{ fontSize:20, fontWeight:700, color:T.ink, fontFamily:'"Plus Jakarta Sans"', letterSpacing:-0.4, marginTop:2 }}>{w.steps.toLocaleString()}</div>
          <div style={{ marginTop:6 }}>
            <Bars data={[6200,7800,9100,8400,10200,7900,w.steps]} w={130} h={20} color={T.brand} dark={dark} max={11000}/>
          </div>
        </div>
        <div style={{ background:T.chip, borderRadius:12, padding:10 }}>
          <div style={{ fontSize:9, color:T.ink3, fontWeight:700, letterSpacing:0.4, textTransform:'uppercase' }}>HR · resting</div>
          <div style={{ fontSize:20, fontWeight:700, color:T.ink, fontFamily:'"Plus Jakarta Sans"', letterSpacing:-0.4, marginTop:2 }}>{w.hr.resting}<span style={{ fontSize:11, color:T.ink2, fontWeight:500 }}> bpm</span></div>
          <div style={{ marginTop:6 }}>
            <Sparkline data={[62,60,59,58,60,59,58]} w={130} h={20} color="#E1573B" fill="rgba(225,87,59,0.14)" dot={false}/>
          </div>
        </div>
      </div>

      {/* today's workout from watch */}
      <div style={{ marginTop:10, padding:10, background:dark?'rgba(201,247,111,0.06)':'rgba(201,247,111,0.18)', borderRadius:12, display:'flex', alignItems:'center', gap:10 }}>
        <div style={{ width:36, height:36, borderRadius:10, background:T.brand, display:'flex', alignItems:'center', justifyContent:'center' }}>
          <Icon name="dumbbell" size={18} color={T.brandInk}/>
        </div>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:12, fontWeight:700, color:T.ink }}>{w.workouts[0].t}</div>
          <div style={{ fontSize:11, color:T.ink2, marginTop:2, fontFamily:'"JetBrains Mono", monospace' }}>{w.workouts[0].dur}m · {w.workouts[0].kcal}kcal · HR {w.workouts[0].hrAvg}/{w.workouts[0].hrMax}</div>
        </div>
        <Icon name="arrow" size={16} color={T.ink3}/>
      </div>

      {/* by-request — sleep granted */}
      <div style={{ marginTop:10, padding:'10px 12px', background:T.chip, borderRadius:12, display:'flex', alignItems:'center', gap:10 }}>
        <Icon name="moon" size={18} color={T.ink2}/>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:12, fontWeight:700, color:T.ink }}>นอน {w.sleep.total} <span style={{ color:T.ink3, fontWeight:500 }}>· คะแนน {w.sleep.score}</span></div>
          <div style={{ fontSize:10, color:T.ink2, fontFamily:'"JetBrains Mono", monospace', marginTop:1 }}>deep {w.sleep.deep} · rem {w.sleep.rem} · {w.sleep.bedtime}–{w.sleep.wake}</div>
        </div>
        <Pill kind="good" dark={dark}>granted</Pill>
      </div>

      {/* by-request — request more */}
      <div style={{ marginTop:8, display:'flex', gap:6, flexWrap:'wrap' }}>
        <button onClick={()=>onRequest('hrv')} style={{ background:T.chip, border:`0.5px solid ${T.line}`, color:T.ink, borderRadius:99, padding:'7px 12px', fontSize:11, fontWeight:600, cursor:'pointer', display:'flex', alignItems:'center', gap:5 }}>
          <Icon name="lock" size={11} color={T.ink2}/> ขอดู HRV วันนี้
        </button>
        <button onClick={()=>onRequest('weight')} style={{ background:T.chip, border:`0.5px solid ${T.line}`, color:T.ink, borderRadius:99, padding:'7px 12px', fontSize:11, fontWeight:600, cursor:'pointer', display:'flex', alignItems:'center', gap:5 }}>
          <Icon name="lock" size={11} color={T.ink2}/> ขอน้ำหนัก scale
        </button>
        <button onClick={()=>onRequest('bloodOxy')} style={{ background:T.chip, border:`0.5px solid ${T.line}`, color:T.ink, borderRadius:99, padding:'7px 12px', fontSize:11, fontWeight:600, cursor:'pointer', display:'flex', alignItems:'center', gap:5 }}>
          <Icon name="lock" size={11} color={T.ink2}/> ขอ SpO₂
        </button>
      </div>
    </div>
  );
}

Object.assign(window, {
  WEARABLE_DEFAULTS, WEARABLE_DATA, METRIC_META,
  TraineeHealthConnect, BiometricsCard, TrainerBiometricsPanel,
});
