// health/CognitiveDetail.jsx
// Push from "Cognitive impact". Uses pentagon radar chart at top
// (more distinctive on detail than the horizontal bars).
// Then horizontal bars per domain with description, then a 14-day trend.

function Radar({ values, labels, size = 240, dark = false }) {
  const cx = size / 2, cy = size / 2;
  const radius = size / 2 - 30;
  const n = values.length;
  const angles = Array.from({ length: n }, (_, i) => -Math.PI / 2 + (i * 2 * Math.PI) / n);
  const point = (r, a) => [cx + Math.cos(a) * r, cy + Math.sin(a) * r];
  const rings = [0.25, 0.5, 0.75, 1];
  const ringStroke = dark ? 'rgba(235,235,245,0.18)' : 'rgba(60,60,67,0.18)';
  const axisStroke = dark ? 'rgba(235,235,245,0.12)' : 'rgba(60,60,67,0.12)';

  // value polygon (normalize 0-100 to radius)
  const poly = values.map((v, i) => point((v / 100) * radius, angles[i])).map(p => p.join(',')).join(' ');

  return (
    <svg width={size} height={size}>
      {/* Concentric rings */}
      {rings.map((r, i) => (
        <polygon key={i}
          points={angles.map(a => point(radius * r, a).join(',')).join(' ')}
          fill={i === rings.length - 1 ? 'transparent' : 'transparent'}
          stroke={ringStroke}
          strokeWidth={0.6}
        />
      ))}
      {/* Axes */}
      {angles.map((a, i) => {
        const [x, y] = point(radius, a);
        return <line key={i} x1={cx} y1={cy} x2={x} y2={y} stroke={axisStroke} strokeWidth={0.6}/>;
      })}
      {/* Value */}
      <polygon points={poly} fill="rgba(94,92,230,0.22)" stroke="var(--io-indigo)" strokeWidth={2} strokeLinejoin="round"/>
      {/* Dots */}
      {values.map((v, i) => {
        const [x, y] = point((v / 100) * radius, angles[i]);
        return <circle key={i} cx={x} cy={y} r={3.5} fill="var(--io-indigo)"/>;
      })}
      {/* Labels */}
      {angles.map((a, i) => {
        const [x, y] = point(radius + 18, a);
        const anchor = Math.abs(Math.cos(a)) < 0.3 ? 'middle' : (Math.cos(a) > 0 ? 'start' : 'end');
        return (
          <text key={i} x={x} y={y + 4} fontSize={12} fontWeight={600}
            fill={dark ? 'rgba(235,235,245,0.6)' : 'rgba(60,60,67,0.6)'}
            textAnchor={anchor}>{labels[i]}</text>
        );
      })}
    </svg>
  );
}

function CognitiveDetail({ dark = false }) {
  const domains = [
    { label: 'Attention',          pct: 64, value: '−14%', color: 'var(--io-orange)', body: 'Sustained focus reduced after short sleep. Schedule shallow work this morning.' },
    { label: 'Memory',             pct: 58, value: '−18%', color: 'var(--io-orange)', body: 'Encoding new information is harder. Defer high-stakes learning until tomorrow.' },
    { label: 'Executive function', pct: 72, value: '−8%',  color: 'var(--io-yellow)', body: 'Decision-making mildly impacted. Avoid open-ended planning before noon.' },
    { label: 'Emotional reg.',     pct: 80, value: '−4%',  color: 'var(--io-green)',  body: 'Mood resilience near baseline. Difficult conversations are okay today.' },
    { label: 'Reaction time',      pct: 46, value: '−24%', color: 'var(--io-red)',    body: 'Significantly slower responses. Avoid driving long distances if avoidable.' },
  ];

  return (
    <FrameScreen dark={dark}>
      <InlineNav back="Health" title="Cognitive impact"/>

      <div style={{ padding: '4px 20px 0' }}>
        <div className="eyebrow" style={{ color: 'var(--io-indigo)' }}>Forecast · today</div>
        <div className="t1" style={{ marginTop: 6, letterSpacing: -0.45 }}>Watch the next 6 hours.</div>
        <div className="bd" style={{ color: 'var(--io-label-secondary)', marginTop: 6 }}>
          Last night's 6h 12m of sleep is pulling four domains below your 14-day baseline.
        </div>
      </div>

      {/* Radar card */}
      <div style={{ padding: '16px 16px 0' }}>
        <div className="card" style={{ padding: '20px 16px 12px', display: 'grid', placeItems: 'center' }}>
          <Radar
            values={domains.map(d => d.pct)}
            labels={['Atten.', 'Mem.', 'Exec.', 'Mood', 'React.']}
            size={260}
            dark={dark}
          />
          <div className="row" style={{ gap: 18, marginTop: 4 }}>
            <div className="row" style={{ gap: 6 }}>
              <span style={{ width: 10, height: 10, background: 'var(--io-indigo)', borderRadius: 2 }}/>
              <span className="fn" style={{ color: 'var(--io-label-secondary)' }}>Today</span>
            </div>
            <div className="row" style={{ gap: 6 }}>
              <span style={{ width: 10, height: 10, background: dark ? 'rgba(235,235,245,0.3)' : 'rgba(60,60,67,0.3)', borderRadius: 2 }}/>
              <span className="fn" style={{ color: 'var(--io-label-secondary)' }}>14-day baseline</span>
            </div>
          </div>
        </div>
      </div>

      <SectionHead label="Domains"/>
      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {domains.map(d => (
          <div key={d.label} className="card padded" style={{ padding: 16 }}>
            <div className="between">
              <div className="hd" style={{ fontSize: 15 }}>{d.label}</div>
              <span style={{ fontSize: 17, fontWeight: 500, color: d.color, letterSpacing: -0.4 }} data-num>{d.value}</span>
            </div>
            <div className="hbar-row" style={{ marginTop: 10, gridTemplateColumns: '1fr' }}>
              <div className="track">
                <div className="fill" style={{ width: `${d.pct}%`, background: d.color }}/>
              </div>
            </div>
            <div className="fn" style={{ color: 'var(--io-label-secondary)', marginTop: 10, lineHeight: 1.4 }}>{d.body}</div>
          </div>
        ))}
      </div>

      <SectionHead label="What helps"/>
      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        <InsightCard emoji="☕" title="Caffeine, but timed" body="One cup before 11 AM. After that, half-life starts to push tonight's bedtime later."/>
        <InsightCard emoji="🚶" title="20-minute walk" body="Daylight after 9 AM tightens tonight's sleep onset by an average of 14 minutes."/>
        <InsightCard emoji="🌙" title="Earlier wind-down" body="Bedtime moved to 10:00 PM tonight (instead of 10:30) — see Smart Bedtime."/>
      </div>

      <div className="scroll-pad"/>
      <TabBar active="health"/>
    </FrameScreen>
  );
}
window.CognitiveDetail = CognitiveDetail;
