// grittt — AI Coach analysis: two screens.
// Reuses globals: A, AWrap, AHeader, ATabBar, Iq, ISpark, HE_GREEN, HE_GREEN_BG, HE_RED, HE_RED_BG.
// Screen 1 (A_Insights): your pattern — verdict + where you're lacking + the fix.
// Screen 2 (A_InsightsGraph): the crowd — how many share it + where everyone loses the streak.

// small section label
function InsSection({ children }) {
  return (
    <div style={{
      fontFamily: A.mono, fontSize: 10.5, fontWeight: 600, letterSpacing: '0.14em',
      textTransform: 'uppercase', color: A.ink3, margin: '4px 2px 10px',
    }}>{children}</div>
  );
}

function InsCard({ children, style }) {
  return (
    <div style={{
      background: A.card, borderRadius: 20, padding: 18,
      border: `1px solid ${A.rule}`, ...style,
    }}>{children}</div>
  );
}

// ── Streak-survival chart: % of users still going at each day-bucket ──
// big = hero treatment for the dedicated graph screen.
function SurvivalChart({ big = false }) {
  // buckets of days reached → share of people still keeping the habit
  const data = [
    { label: '1–5',   pct: 100, drop: 0 },
    { label: '6–10',  pct: 61,  drop: 39, cliff: true }, // the cliff — most people quit here
    { label: '11–15', pct: 42,  drop: 19 },
    { label: '16–20', pct: 30,  drop: 12, you: true },   // you are here, day 16
    { label: '21–25', pct: 23,  drop: 7 },
    { label: '26–30', pct: 18,  drop: 5 },
  ];
  const H = big ? 188 : 132;
  const W = 6; // columns
  // build the survival line points (in a 0..100 box) for an overlay
  const linePts = data.map((d, i) => {
    const x = ((i + 0.5) / W) * 100;
    const y = 100 - d.pct;
    return [x, y];
  });
  const linePath = linePts.map((p, i) => `${i ? 'L' : 'M'}${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(' ');
  const areaPath = `${linePath} L100 100 L0 100 Z`;

  return (
    <InsCard style={{ padding: big ? '20px 16px 16px' : '18px 16px 14px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 4 }}>
        <div>
          <div style={{ fontFamily: A.display, fontWeight: 800, fontSize: big ? 19 : 16.5, color: A.ink, letterSpacing: '-0.01em' }}>Where people lose it</div>
          <div style={{ fontFamily: A.body, fontSize: 12, color: A.ink3, marginTop: 2 }}>% of 48,210 still running</div>
        </div>
      </div>

      {/* bars + survival line overlay */}
      <div style={{ position: 'relative', height: H + 28, marginTop: 16 }}>
        {/* gridlines */}
        <div style={{ position: 'absolute', inset: `0 0 28px 0` }}>
          {[0, 0.5, 1].map((g) => (
            <div key={g} style={{ position: 'absolute', left: 0, right: 0, top: `${g * 100}%`, borderTop: `1px dashed ${A.rule}` }} />
          ))}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6,1fr)', gap: 8, alignItems: 'end', height: '100%', position: 'relative' }}>
          {data.map((d, i) => {
            const h = Math.max(6, (d.pct / 100) * H);
            const isYou = d.you;
            const isCliff = d.cliff;
            const barBg = isYou ? HE_GREEN : isCliff ? HE_RED_BG : A.rest;
            const barBd = isYou ? HE_GREEN : isCliff ? HE_RED : 'transparent';
            return (
              <div key={i} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-end', height: '100%' }}>
                {isYou && (
                  <div style={{
                    fontFamily: A.display, fontWeight: 800, fontSize: 9, letterSpacing: '0.08em',
                    color: '#fff', background: HE_GREEN, borderRadius: 6, padding: '2px 6px', marginBottom: 5,
                  }}>YOU</div>
                )}
                <div style={{ fontFamily: A.display, fontWeight: 800, fontSize: big ? 13.5 : 12.5, color: isYou ? HE_GREEN : isCliff ? HE_RED : A.ink2, marginBottom: 5 }}>{d.pct}%</div>
                <div style={{
                  width: '100%', height: h, borderRadius: 8,
                  background: barBg, border: `1.5px solid ${barBd}`,
                  boxShadow: isYou ? '0 4px 12px rgba(34,166,100,0.30)' : 'none',
                }} />
                <div style={{ fontFamily: A.mono, fontSize: 9.5, color: isCliff ? HE_RED : A.ink3, fontWeight: isCliff ? 700 : 500, marginTop: 7, whiteSpace: 'nowrap' }}>{d.label}</div>
              </div>
            );
          })}
        </div>
        {/* survival curve over the bars */}
        <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ position: 'absolute', left: 0, right: 0, top: 0, width: '100%', height: H, pointerEvents: 'none' }}>
          <path d={areaPath} fill={A.ink} opacity="0.05" />
          <path d={linePath} fill="none" stroke={A.ink} strokeWidth="1.4" strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke" />
        </svg>
      </div>

      {/* cliff caption */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8, marginTop: 14,
        background: HE_RED_BG, border: `1px solid ${HE_RED}`, borderRadius: 12, padding: '9px 12px',
      }}>
        <span style={{ color: HE_RED, display: 'flex' }}><Iq width={16} height={16} strokeWidth="2.4"><path d="M12 9v4M12 17h.01M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z"/></Iq></span>
        <div style={{ fontFamily: A.body, fontSize: 12.5, color: A.ink2, lineHeight: 1.35 }}>
          <strong style={{ color: HE_RED }}>39% quit at days 6–10.</strong> The danger zone — you're already past it.
        </div>
      </div>
    </InsCard>
  );
}

// ─────────────────────────────────────────────
// SCREEN 1 — your pattern
// ─────────────────────────────────────────────
function A_Insights() {
  // weekday vs weekend miss pattern → where you're lacking
  const week = [
    { d: 'Mon', rate: 100 }, { d: 'Tue', rate: 100 }, { d: 'Wed', rate: 86 },
    { d: 'Thu', rate: 100 }, { d: 'Fri', rate: 71 }, { d: 'Sat', rate: 29 }, { d: 'Sun', rate: 43 },
  ];
  return (
    <AWrap>
      <AHeader mode="AI ANALYSIS" title="COACH" action={
        <Iq width={18} height={18}><path d="M21 12a9 9 0 1 1-6.2-8.6"/><path d="M21 4v5h-5"/></Iq>
      }/>
      <div className="scr-body">

        {/* AI verdict hero */}
        <div style={{
          background: A.ink, borderRadius: 22, padding: '18px 18px 20px', position: 'relative', overflow: 'hidden',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{
              width: 30, height: 30, borderRadius: 10, 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.5, fontWeight: 600, letterSpacing: '0.14em', color: A.hype, textTransform: 'uppercase' }}>a message from your future self</div>
          </div>
          <div style={{ fontFamily: A.display, fontWeight: 800, fontSize: 21, color: '#fff', lineHeight: 1.18, letterSpacing: '-0.01em', marginTop: 14 }}>
            Your weekends are no<br/>longer breaking the chain.
          </div>
          <div style={{ fontFamily: A.body, fontSize: 13.5, color: 'rgba(255,255,255,0.66)', lineHeight: 1.5, marginTop: 10 }}>
            You're becoming more consistent each month. <strong style={{ color: '#fff' }}>Keep this trend and you'll outperform your past self.</strong>
          </div>
          <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid rgba(255,255,255,0.1)', display: 'flex', flexDirection: 'column', gap: 10 }}>
            {[
              'Your future is improving because of these choices.',
              'This pattern is making you more disciplined.',
            ].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>

        {/* where you're lacking — weekday bars */}
        <div style={{ marginTop: 18 }}>
          <InsSection>Your pattern this week</InsSection>
          <InsCard style={{ padding: '16px 16px 12px' }}>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 6, alignItems: 'end', height: 100 }}>
              {week.map((w, i) => {
                const weak = w.rate < 60;
                const h = Math.max(8, (w.rate / 100) * 80);
                return (
                  <div key={i} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-end', height: '100%' }}>
                    <div style={{ fontFamily: A.mono, fontSize: 9, color: weak ? HE_RED : A.ink3, fontWeight: 700, marginBottom: 4 }}>{w.rate}%</div>
                    <div style={{ width: '100%', height: h, borderRadius: 6, background: weak ? HE_RED : HE_GREEN, opacity: weak ? 1 : 0.9 }} />
                    <div style={{ fontFamily: A.mono, fontSize: 9.5, color: weak ? HE_RED : A.ink3, fontWeight: weak ? 700 : 500, marginTop: 6 }}>{w.d}</div>
                  </div>
                );
              })}
            </div>
            <div style={{ display: 'flex', gap: 16, marginTop: 12, paddingTop: 12, borderTop: `1px solid ${A.rule}`, fontFamily: A.body, fontSize: 12, color: A.ink2 }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ width: 11, height: 11, borderRadius: 3, background: HE_GREEN }} />On track</span>
              <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ width: 11, height: 11, borderRadius: 3, background: HE_RED }} />Slipping</span>
            </div>
          </InsCard>
        </div>

        {/* coach action */}
        <div style={{ marginTop: 18, marginBottom: 8 }}>
          <InsSection>The fix</InsSection>
          <InsCard style={{ background: A.hype, border: 'none', display: 'flex', alignItems: 'center', gap: 12 }}>
            <span style={{ flex: '0 0 auto', width: 34, height: 34, borderRadius: 11, background: A.ink, color: A.hype, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><ISpark /></span>
            <div style={{ fontFamily: A.body, fontSize: 13, color: A.ink, lineHeight: 1.4 }}>
              <strong>This week:</strong> set a Saturday 9AM alarm. Beat one weekend and your odds jump.
            </div>
          </InsCard>
        </div>

        {/* link to crowd view */}
        <div style={{ marginBottom: 8 }}>
          <InsCard style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '14px 16px' }}>
            <div style={{ fontFamily: A.body, fontSize: 13, color: A.ink2, lineHeight: 1.35 }}>
              See where <strong style={{ color: A.ink }}>48,210 others</strong> lose this streak →
            </div>
            <span style={{ flex: '0 0 auto', width: 30, height: 30, borderRadius: 10, background: A.rest, color: A.ink, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Iq width={16} height={16}><path d="M9 5l7 7-7 7"/></Iq>
            </span>
          </InsCard>
        </div>

      </div>
      <ATabBar active="user" />
    </AWrap>
  );
}

// ─────────────────────────────────────────────
// SCREEN 2 — the crowd / the graph
// ─────────────────────────────────────────────
function A_InsightsGraph() {
  return (
    <AWrap>
      <AHeader mode="AI ANALYSIS" title="THE CROWD" action={
        <Iq width={18} height={18}><path d="M15 19l-7-7 7-7"/></Iq>
      }/>
      <div className="scr-body">

        {/* community count */}
        <InsCard style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            {['#22A664', '#F0A12E', '#E07878', '#14110D'].map((c, i) => (
              <span key={i} style={{
                width: 36, height: 36, borderRadius: '50%', background: c, border: '2.5px solid ' + A.card,
                marginLeft: i ? -13 : 0, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <Iq width={16} height={16}><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-6 8-6s8 2 8 6"/></Iq>
              </span>
            ))}
          </div>
          <div>
            <div style={{ fontFamily: A.display, fontWeight: 800, fontSize: 24, color: A.ink, lineHeight: 1 }}>48,210</div>
            <div style={{ fontFamily: A.body, fontSize: 12.5, color: A.ink2, marginTop: 3 }}>building <strong style={{ color: A.ink }}>Morning Run</strong> right now</div>
          </div>
        </InsCard>

        {/* the graph — hero */}
        <div style={{ marginTop: 18 }}>
          <InsSection>The drop-off curve</InsSection>
          <SurvivalChart big />
        </div>

        {/* your standing */}
        <div style={{ marginTop: 18, marginBottom: 8 }}>
          <InsSection>Your standing</InsSection>
          <InsCard style={{ display: 'flex', alignItems: 'center', gap: 14, borderColor: HE_GREEN, borderWidth: 1.5 }}>
            <div style={{
              flex: '0 0 auto', width: 58, height: 58, borderRadius: 16, background: HE_GREEN_BG,
              border: `1.5px solid ${HE_GREEN}`, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
            }}>
              <div style={{ fontFamily: A.display, fontWeight: 800, fontSize: 19, color: HE_GREEN, lineHeight: 1 }}>30%</div>
              <div style={{ fontFamily: A.mono, fontSize: 7.5, fontWeight: 600, letterSpacing: '0.06em', color: HE_GREEN, marginTop: 2 }}>TOP</div>
            </div>
            <div style={{ fontFamily: A.body, fontSize: 13, color: A.ink2, lineHeight: 1.45 }}>
              On day 16, you're in the <strong style={{ color: A.ink }}>top 30%</strong> who make it this far. Most who reach here finish the month.
            </div>
          </InsCard>
        </div>

      </div>
      <ATabBar active="user" />
    </AWrap>
  );
}

Object.assign(window, { A_Insights, A_InsightsGraph });
