// grittt — Screen Time / Digital Detox screen (interactive).
// Reuses globals: A, AWrap, AHeader, ATabBar, Iq, ISpark.
// App list → tap a row → bottom-sheet popup with the past-week usage graph
// and an AI detox analysis (time saved, sleep, focus).

const ST_APPS = [
  {
    id: 'ig', name: 'Instagram', initial: 'Ig', tile: '#E1306C',
    today: '1h 04m', mins: 64, trend: -41, down: true,
    week: [108, 96, 82, 71, 64, 58, 64], lastAvg: 109, // Mon..Sun minutes
    saved: '4h 50m',
    verdict: 'Down 41% this week — about 4h 50m handed back to you.',
    detox: 'Your evenings are calmer and you fall asleep ~18 min faster since the 9PM cut-off. The dopamine loop is loosening — keep starving it.',
    impact: [{ k: 'Time saved', v: '4h 50m' }, { k: 'Sleep onset', v: '+18 min' }, { k: 'Pickups', v: '−37' }],
  },
  {
    id: 'yt', name: 'YouTube', initial: 'Yt', tile: '#E8463A',
    today: '52m', mins: 52, trend: 12, down: false,
    week: [38, 41, 47, 44, 49, 58, 52], lastAvg: 44,
    saved: '−56m',
    verdict: 'Up 12% — the late-night rabbit holes are creeping back.',
    detox: 'Most of this lands after 11PM and pushes your bedtime later. Set a wind-down reminder and move it to mornings — your focus score follows your sleep.',
    impact: [{ k: 'After 11PM', v: '34m' }, { k: 'Sessions', v: '+9' }, { k: 'Focus', v: '−6' }],
  },
  {
    id: 'tt', name: 'TikTok', initial: 'Tk', tile: '#111014',
    today: '31m', mins: 31, trend: -58, down: true,
    week: [82, 64, 51, 42, 36, 29, 31], lastAvg: 78,
    saved: '5h 29m',
    verdict: 'Down 58% — your biggest win this week.',
    detox: 'Cutting the endless scroll freed your attention span the most. People who hold this for 21 days report sharper focus and less restless boredom. You\u2019re on day 12.',
    impact: [{ k: 'Time saved', v: '5h 29m' }, { k: 'Focus', v: '+14' }, { k: 'Pickups', v: '−61' }],
  },
  {
    id: 'x', name: 'X', initial: 'X', tile: '#16140F',
    today: '24m', mins: 24, trend: -22, down: true,
    week: [41, 36, 33, 28, 26, 22, 24], lastAvg: 33,
    saved: '1h 03m',
    verdict: 'Down 22% — the outrage doom-scroll is fading.',
    detox: 'Less time here means a measurably calmer mood baseline. Your morning check-ins read less anxious. Protect the first hour of your day from it.',
    impact: [{ k: 'Time saved', v: '1h 03m' }, { k: 'Mood', v: '+9' }, { k: 'Pickups', v: '−18' }],
  },
  {
    id: 'wa', name: 'WhatsApp', initial: 'Wa', tile: '#1FA855',
    today: '18m', mins: 18, trend: -8, down: true,
    week: [24, 22, 21, 19, 20, 17, 18], lastAvg: 21,
    saved: '21m',
    verdict: 'Steady — this one\u2019s mostly real connection.',
    detox: 'Not every minute is a leak. Messaging the people who matter is healthy — the coach leaves this one alone. Spend it well.',
    impact: [{ k: 'Time saved', v: '21m' }, { k: 'Tone', v: 'Healthy' }, { k: 'Pickups', v: '−4' }],
  },
];

const ST_MAX = Math.max(...ST_APPS.map(a => a.mins));

// ── usage bar in the list row ──
function STBar({ mins, down }) {
  const pct = Math.max(6, (mins / ST_MAX) * 100);
  return (
    <div style={{ height: 8, borderRadius: 999, background: A.rest, overflow: 'hidden', marginTop: 7 }}>
      <div style={{ width: pct + '%', height: '100%', borderRadius: 999, background: down ? A.good : A.bad }} />
    </div>
  );
}

function STAppTile({ app, size = 40 }) {
  return (
    <span style={{
      width: size, height: size, borderRadius: size * 0.28, background: app.tile, color: '#fff',
      display: 'flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 auto',
      fontFamily: A.display, fontWeight: 800, fontSize: size * 0.36, letterSpacing: '-0.02em',
    }}>{app.initial}</span>
  );
}

function STTrendPill({ trend, down }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 3,
      fontFamily: A.mono, fontSize: 10.5, fontWeight: 700,
      color: down ? A.good : A.bad, background: down ? '#E4F4EA' : '#FBE6E6',
      borderRadius: 999, padding: '3px 7px',
    }}>
      <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round" style={{ transform: down ? 'none' : 'scaleY(-1)' }}>
        <path d="M5 12l7 7M12 19V5" />
      </svg>
      {Math.abs(trend)}%
    </span>
  );
}

// ── weekly graph for the popup ──
function STWeekGraph({ app }) {
  const days = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
  const max = Math.max(app.lastAvg, ...app.week) * 1.08;
  const H = 124;
  const lastY = (1 - app.lastAvg / max) * H;
  return (
    <div style={{ position: 'relative', height: H + 24, marginTop: 4 }}>
      {/* last-week average reference line */}
      <div style={{ position: 'absolute', left: 0, right: 0, top: lastY, borderTop: `1.5px dashed ${A.ink3}` }}>
        <span style={{
          position: 'absolute', right: 0, top: -16, fontFamily: A.mono, fontSize: 9, fontWeight: 600,
          color: A.ink3, background: A.card, padding: '0 4px',
        }}>last wk avg</span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 7, alignItems: 'end', height: H, position: 'relative' }}>
        {app.week.map((m, i) => {
          const h = Math.max(6, (m / max) * H);
          const isToday = i === app.week.length - 1;
          const col = app.down ? (isToday ? A.good : '#9FD9B4') : (isToday ? A.bad : '#E6A6A6');
          return (
            <div key={i} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-end', height: '100%' }}>
              <div style={{
                width: '100%', height: h, borderRadius: 7, background: col,
                boxShadow: isToday ? `0 4px 10px ${app.down ? 'rgba(34,166,100,0.30)' : 'rgba(232,74,74,0.30)'}` : 'none',
              }} />
              <div style={{ fontFamily: A.mono, fontSize: 9.5, color: isToday ? A.ink : A.ink3, fontWeight: isToday ? 700 : 500, marginTop: 6 }}>{days[i]}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── the bottom-sheet popup ──
function STSheet({ app, onClose }) {
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 80, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
      {/* backdrop */}
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(20,17,13,0.42)', backdropFilter: 'blur(2px)' }} />
      {/* sheet */}
      <div className="st-sheet" style={{
        position: 'relative', background: A.bg, borderRadius: '26px 26px 0 0',
        padding: '12px 18px 30px', maxHeight: '88%', overflowY: 'auto',
        boxShadow: '0 -16px 40px rgba(20,17,13,0.22)',
      }}>
        <div style={{ width: 40, height: 5, borderRadius: 999, background: A.rule, margin: '0 auto 16px' }} />

        {/* app header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
          <STAppTile app={app} size={46} />
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: A.display, fontWeight: 800, fontSize: 19, color: A.ink, letterSpacing: '-0.01em' }}>{app.name}</div>
            <div style={{ fontFamily: A.body, fontSize: 12.5, color: A.ink3 }}>{app.today} today</div>
          </div>
          <STTrendPill trend={app.trend} down={app.down} />
          <button onClick={onClose} style={{
            width: 32, height: 32, borderRadius: 10, border: `1px solid ${A.rule}`, background: A.card,
            color: A.ink2, display: 'flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 auto',
          }}><Iq width={16} height={16} strokeWidth="2.4"><path d="M6 6l12 12M18 6L6 18"/></Iq></button>
        </div>

        {/* weekly graph card */}
        <div style={{ background: A.card, border: `1px solid ${A.rule}`, borderRadius: 18, padding: '16px 16px 12px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
            <div style={{ fontFamily: A.display, fontWeight: 800, fontSize: 15, color: A.ink }}>Past 7 days</div>
            <div style={{ fontFamily: A.mono, fontSize: 11, fontWeight: 600, color: app.down ? A.good : A.bad }}>{app.down ? 'saved ' : 'extra '}{app.saved.replace('−', '')}</div>
          </div>
          <STWeekGraph app={app} />
        </div>

        {/* AI detox analysis */}
        <div style={{ background: A.ink, borderRadius: 18, padding: '16px 16px 18px', marginTop: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
            <span style={{ width: 26, height: 26, borderRadius: 8, background: A.hype, color: A.ink, display: 'flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 auto' }}><ISpark /></span>
            <div style={{ fontFamily: A.mono, fontSize: 10, fontWeight: 600, letterSpacing: '0.14em', color: A.hype, textTransform: 'uppercase' }}>Coach · detox read</div>
          </div>
          <div style={{ fontFamily: A.display, fontWeight: 800, fontSize: 16.5, color: '#fff', lineHeight: 1.25, letterSpacing: '-0.01em' }}>{app.verdict}</div>
          <div style={{ fontFamily: A.body, fontSize: 13, color: 'rgba(255,255,255,0.66)', lineHeight: 1.5, marginTop: 9 }}>{app.detox}</div>

          {/* impact stats */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8, marginTop: 14 }}>
            {app.impact.map((s, i) => (
              <div key={i} style={{ background: 'rgba(255,255,255,0.06)', borderRadius: 12, padding: '10px 8px', textAlign: 'center' }}>
                <div style={{ fontFamily: A.display, fontWeight: 800, fontSize: 16, color: A.hype, lineHeight: 1 }}>{s.v}</div>
                <div style={{ fontFamily: A.body, fontSize: 9, color: 'rgba(255,255,255,0.55)', fontWeight: 600, letterSpacing: '0.04em', marginTop: 5 }}>{s.k}</div>
              </div>
            ))}
          </div>

          {/* who you're becoming */}
          <div style={{ marginTop: 14, paddingTop: 14, borderTop: '1px solid rgba(255,255,255,0.1)', display: 'flex', flexDirection: 'column', gap: 10 }}>
            {[
              'You spent more time creating than consuming.',
              'Sleep quality improved after reducing late-night scrolling.',
            ].map((line) => (
              <div key={line} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ color: A.hype, flex: '0 0 auto' }}><ICheck /></span>
                <div style={{ fontFamily: A.body, fontSize: 13.5, color: 'rgba(255,255,255,0.85)', lineHeight: 1.4 }}>{line}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function A_ScreenTime() {
  const [open, setOpen] = React.useState(null);
  const totalMins = ST_APPS.reduce((s, a) => s + a.mins, 0);
  const h = Math.floor(totalMins / 60), m = totalMins % 60;

  return (
    <AWrap>
      <AHeader mode="DIGITAL DETOX" title="SCREEN TIME" action={
        <Iq width={18} height={18}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></Iq>
      }/>
      <div className="scr-body">

        {/* total today hero */}
        <div style={{ background: A.ink, borderRadius: 22, padding: '18px 18px 20px' }}>
          <div style={{ fontFamily: A.mono, fontSize: 10.5, fontWeight: 600, letterSpacing: '0.14em', color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase' }}>Total today</div>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 12, marginTop: 8 }}>
            <div style={{ fontFamily: A.display, fontWeight: 800, fontSize: 44, color: '#fff', lineHeight: 0.9, letterSpacing: '-0.03em' }}>{h}h {String(m).padStart(2, '0')}m</div>
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: 4, marginBottom: 6,
              fontFamily: A.mono, fontSize: 12, fontWeight: 700, color: A.ink, background: A.hype,
              borderRadius: 999, padding: '4px 9px',
            }}>
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12l7 7M12 19V5"/></svg>
              34%
            </span>
          </div>
          <div style={{ fontFamily: A.body, fontSize: 13, color: 'rgba(255,255,255,0.62)', marginTop: 10, lineHeight: 1.45 }}>
            That’s <strong style={{ color: '#fff' }}>1h 38m</strong> less than your weekly average. Tap an app to see your detox progress.
          </div>
          <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid rgba(255,255,255,0.1)', display: 'flex', flexDirection: 'column', gap: 10 }}>
            {[
              '5 hours handed back this week.',
              'Your evenings belong to you again.',
              'Attention reclaimed.',
            ].map((line) => (
              <div key={line} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ color: A.hype, flex: '0 0 auto' }}><ICheck /></span>
                <div style={{ fontFamily: A.body, fontSize: 13.5, color: 'rgba(255,255,255,0.85)', lineHeight: 1.4 }}>{line}</div>
              </div>
            ))}
          </div>
        </div>

        {/* app list */}
        <div style={{ marginTop: 18 }}>
          <div style={{ fontFamily: A.mono, fontSize: 10.5, fontWeight: 600, letterSpacing: '0.14em', textTransform: 'uppercase', color: A.ink3, margin: '0 2px 10px' }}>Most used · tap for analysis</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {ST_APPS.map(app => (
              <button key={app.id} onClick={() => setOpen(app)} style={{
                textAlign: 'left', width: '100%', cursor: 'pointer',
                background: A.card, border: `1px solid ${A.rule}`, borderRadius: 16, padding: '13px 14px',
                display: 'block',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <STAppTile app={app} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
                      <span style={{ fontFamily: A.display, fontWeight: 700, fontSize: 15.5, color: A.ink }}>{app.name}</span>
                      <span style={{ fontFamily: A.display, fontWeight: 800, fontSize: 14, color: A.ink2 }}>{app.today}</span>
                    </div>
                    <STBar mins={app.mins} down={app.down} />
                  </div>
                  <span style={{ flex: '0 0 auto', display: 'flex', alignItems: 'center', gap: 8 }}>
                    <STTrendPill trend={app.trend} down={app.down} />
                    <span style={{ color: A.ink3, display: 'flex' }}><Iq width={16} height={16}><path d="M9 5l7 7-7 7"/></Iq></span>
                  </span>
                </div>
              </button>
            ))}
          </div>
        </div>

        <div style={{ height: 8 }} />
      </div>

      {open && <STSheet app={open} onClose={() => setOpen(null)} />}
      <ATabBar active="user" />
    </AWrap>
  );
}

// ───────────────────────────────────────────────────────
// SCREEN TIME DETAIL — static "AI analysis" page: the app
// list dimmed behind the tapped-app sheet (week graph +
// coach's detox read).
// ───────────────────────────────────────────────────────
function A_ScreenTimeDetail() {
  const app = ST_APPS[0]; // Instagram — the headline win
  return (
    <div style={{ position: 'relative', width: '100%', height: '100%', overflow: 'hidden', background: A.bg }}>
      <div style={{ opacity: 0.4, pointerEvents: 'none' }}><A_ScreenTime /></div>
      <STSheet app={app} onClose={() => {}} />
    </div>
  );
}

Object.assign(window, { A_ScreenTime, A_ScreenTimeDetail });
