// PULS3 — Sleep Deep Dive
// Ring gauge + weekly 3am-wake pattern + coach insight + what's driving it.

function SleepDeepDive() {
  const nights = [
    { d: 'M', score: 72, woke: false, hrs: 6.8 },
    { d: 'T', score: 58, woke: true,  hrs: 5.4 },
    { d: 'W', score: 61, woke: true,  hrs: 5.1 },
    { d: 'T', score: 54, woke: true,  hrs: 4.9 },
    { d: 'F', score: 66, woke: false, hrs: 6.2 },
    { d: 'S', score: 71, woke: true,  hrs: 5.8 },
    { d: 'S', score: 63, woke: false, hrs: 6.5 }, // today
  ];
  const today = nights[nights.length - 1];

  // Ring
  const ringSize = 168, ringStroke = 14, r = (ringSize - ringStroke) / 2;
  const circ = 2 * Math.PI * r;
  const pct = today.score / 100;
  const off = circ * (1 - pct);

  return (
    <ScreenFrame tint="sleep">
      <div style={{
        position: 'relative', zIndex: 1, height: '100%',
        overflowY: 'auto', boxSizing: 'border-box',
        padding: '62px 20px 110px',
      }}>
        {/* Back + title row */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18 }}>
          <div style={{
            width: 34, height: 34, borderRadius: '50%',
            background: 'rgba(255,255,255,0.08)',
            border: '1px solid rgba(255,255,255,0.12)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: 'rgba(255,255,255,0.8)',
          }}>
            <svg width="11" height="18" viewBox="0 0 12 20" fill="none">
              <path d="M10 2L2 10l8 8" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
          <Eyebrow color="#A78BDB">Sleep · last 7 nights</Eyebrow>
        </div>

        {/* Ring + metric */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 22 }}>
          <div style={{ position: 'relative', width: ringSize, height: ringSize, flexShrink: 0 }}>
            <svg width={ringSize} height={ringSize} style={{ transform: 'rotate(-90deg)' }}>
              <defs>
                <linearGradient id="ringg" x1="0" y1="0" x2="1" y2="1">
                  <stop offset="0%" stopColor="#A78BDB"/>
                  <stop offset="100%" stopColor="#00D4FF"/>
                </linearGradient>
              </defs>
              <circle cx={ringSize/2} cy={ringSize/2} r={r} fill="none"
                stroke="rgba(255,255,255,0.08)" strokeWidth={ringStroke}/>
              <circle cx={ringSize/2} cy={ringSize/2} r={r} fill="none"
                stroke="url(#ringg)" strokeWidth={ringStroke}
                strokeDasharray={circ} strokeDashoffset={off}
                strokeLinecap="round"
                style={{ filter: 'drop-shadow(0 0 8px rgba(167,139,219,0.5))' }}/>
            </svg>
            <div style={{
              position: 'absolute', inset: 0, display: 'flex',
              flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
            }}>
              <div style={{
                fontSize: 48, fontWeight: 700, letterSpacing: '0.02em', lineHeight: 1,
                background: 'linear-gradient(135deg, #00D4FF, #A78BDB)',
                WebkitBackgroundClip: 'text', backgroundClip: 'text', color: 'transparent',
                textShadow: '0 0 10px rgba(0,212,255,0.35)',
              }}>{today.score}</div>
              <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)', marginTop: 4, letterSpacing: '0.12em', textTransform: 'uppercase' }}>
                Last night
              </div>
            </div>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.5)', marginBottom: 6 }}>You slept</div>
            <div style={{ fontSize: 34, fontWeight: 600, letterSpacing: '-0.01em', lineHeight: 1 }}>
              6h 29m
            </div>
            <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 6, fontSize: 12.5, color: 'rgba(255,255,255,0.7)' }}>
              <Row label="Deep"  val="52 min" color="#A78BDB" pct={0.42} />
              <Row label="REM"   val="1h 14m" color="#00D4FF" pct={0.62} />
              <Row label="Awake" val="38 min" color="#E8836B" pct={0.28} />
            </div>
          </div>
        </div>

        {/* 3am pattern card — the distinctive viz */}
        <GlassCard wash glowColor="#A78BDB" style={{ marginBottom: 14 }}>
          <Eyebrow color="rgba(255,255,255,0.45)">You're waking at 3</Eyebrow>
          <div style={{ fontSize: 17, fontWeight: 600, marginBottom: 14, letterSpacing: '-0.01em' }}>
            4 of the last 7 nights
          </div>
          <NightStrip nights={nights} />
          <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.7)', lineHeight: 1.55, marginTop: 14 }}>
            That clustering is usually a temperature thing. Your body's working harder to cool down mid-hormonal-cycle — it's common around day 21.
          </div>
        </GlassCard>

        {/* What's driving it */}
        <Eyebrow color="rgba(255,255,255,0.45)">What I noticed</Eyebrow>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 18 }}>
          <FactorRow Icon={IcCoffee} title="Afternoon caffeine"
            detail="3 coffees Tue–Thu · later than usual" trend="watch" color="#F28059" />
          <FactorRow Icon={IcFlame} title="Bedroom at 72°F"
            detail="Running warmer than your baseline 68°" trend="watch" color="#E8836B" />
          <FactorRow Icon={IcMove} title="Evening walks"
            detail="Helped on Mon + Fri — the nights you slept through" trend="good" color="#8CDDB3" />
        </div>

        {/* Coach follow-up */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 14 }}>
          <AssistantBubble>
            Want me to set a gentle wind-down at 9:30 tonight? Cooler room, no caffeine after 2.
          </AssistantBubble>
          <ChipPanel>
            <Chip selected>Yes, try it</Chip>
            <Chip>Tell me more first</Chip>
            <Chip>Not tonight</Chip>
          </ChipPanel>
        </div>
      </div>
      <TabBar active="Trends" />
    </ScreenFrame>
  );
}

const Row = ({ label, val, color, pct }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
    <div style={{ width: 52, color: 'rgba(255,255,255,0.6)' }}>{label}</div>
    <div style={{ flex: 1, height: 4, borderRadius: 2, background: 'rgba(255,255,255,0.08)', overflow: 'hidden' }}>
      <div style={{ height: '100%', width: `${pct*100}%`, background: color, borderRadius: 2 }} />
    </div>
    <div style={{ fontVariantNumeric: 'tabular-nums', color: '#fff', fontWeight: 500, minWidth: 52, textAlign: 'right' }}>{val}</div>
  </div>
);

// The night strip: each column is a night; vertical axis is hours 10pm→7am
// A lavender segment shows the sleep window; a cyan "wake" pip shows ~3am awake
function NightStrip({ nights }) {
  const hours = 9; // 10pm → 7am
  const h = 110;
  return (
    <div style={{ position: 'relative', height: h + 22 }}>
      {/* time axis */}
      <div style={{
        position: 'absolute', left: 0, top: 0, width: 32, height: h,
        fontSize: 10, color: 'rgba(255,255,255,0.35)',
        display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
        fontFamily: '-apple-system, system-ui',
      }}>
        <div>10p</div>
        <div>2a</div>
        <div>7a</div>
      </div>
      {/* 3am guide line */}
      <div style={{
        position: 'absolute', left: 34, right: 0, top: (5/hours) * h,
        borderTop: '1px dashed rgba(0,212,255,0.35)',
      }}>
        <div style={{
          position: 'absolute', right: 0, top: -8, fontSize: 9.5,
          color: 'rgba(0,212,255,0.7)', letterSpacing: '0.08em',
        }}>3 AM</div>
      </div>
      <div style={{
        position: 'absolute', left: 34, right: 0, top: 0, bottom: 22,
        display: 'flex', justifyContent: 'space-between',
      }}>
        {nights.map((n, i) => {
          // Sleep from 11pm (hr 1) for 'hrs' hours
          const topPx = (1/hours) * h;
          const heightPx = (n.hrs/hours) * h;
          return (
            <div key={i} style={{ width: 22, position: 'relative', height: h }}>
              <div style={{
                position: 'absolute', left: '50%', transform: 'translateX(-50%)',
                top: topPx, height: heightPx, width: 8,
                borderRadius: 5,
                background: i === nights.length - 1
                  ? 'linear-gradient(180deg, #A78BDB, #7B6BBF)'
                  : 'rgba(167,139,219,0.4)',
                border: i === nights.length - 1 ? '1px solid rgba(255,255,255,0.25)' : 'none',
              }} />
              {n.woke && (
                <div style={{
                  position: 'absolute', left: '50%', transform: 'translate(-50%, -50%)',
                  top: (5/hours) * h, width: 12, height: 12,
                  borderRadius: '50%', background: '#00D4FF',
                  boxShadow: '0 0 8px rgba(0,212,255,0.8)',
                  border: '2px solid #1A3E3E',
                }} />
              )}
              <div style={{
                position: 'absolute', bottom: 0, left: 0, right: 0, textAlign: 'center',
                fontSize: 11, color: i === nights.length - 1 ? '#fff' : 'rgba(255,255,255,0.45)',
                fontWeight: i === nights.length - 1 ? 600 : 400,
              }}>{n.d}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function FactorRow({ Icon, title, detail, trend, color }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '12px 14px', borderRadius: 18,
      background: 'rgba(255,255,255,0.04)',
      border: '1px solid rgba(255,255,255,0.08)',
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 10, flexShrink: 0,
        background: `${color}22`, border: `1px solid ${color}40`,
        color, display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon size={17} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 600 }}>{title}</div>
        <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.6)', marginTop: 1 }}>{detail}</div>
      </div>
      <div style={{
        fontSize: 10.5, letterSpacing: '0.1em', textTransform: 'uppercase',
        color: trend === 'good' ? '#8CDDB3' : '#FAC257',
      }}>{trend === 'good' ? 'Helping' : 'Watch'}</div>
    </div>
  );
}

Object.assign(window, { SleepDeepDive });
