// screen-you.jsx — "You" tab: profile, community standing, achievements, settings.
// The community + badges blocks are fully interactive:
//   • tap any podium unit or the "You" row → neighbour detail sheet
//   • "Full list" → full block leaderboard sheet
//   • tap any badge → badge detail sheet (earned date or progress to unlock)

const BLOCK_LB = [
  { rank: 1,  handle: '#03-12', pct: 38, pts: 4920, delta: 2,  you: false },
  { rank: 2,  handle: '#14-07', pct: 34, pts: 4480, delta: 0,  you: false },
  { rank: 3,  handle: '#07-21', pct: 31, pts: 4120, delta: 1,  you: false },
  { rank: 4,  handle: '#29-03', pct: 28, pts: 3960, delta: -1, you: false },
  { rank: 5,  handle: '#11-18', pct: 26, pts: 3740, delta: 3,  you: false },
  { rank: 6,  handle: '#22-09', pct: 24, pts: 3510, delta: 1,  you: false },
  { rank: 7,  handle: '#05-14', pct: 23, pts: 3380, delta: -2, you: false },
  { rank: 8,  handle: '#31-02', pct: 22, pts: 3200, delta: 0,  you: false },
  { rank: 12, handle: '#45-06', pct: 19, pts: 2810, delta: 1,  you: false },
  { rank: 13, handle: '#19-11', pct: 19, pts: 2730, delta: -1, you: false },
  { rank: 14, handle: '#08-21', pct: 18, pts: 2640, delta: 5,  you: true  },
  { rank: 15, handle: '#33-04', pct: 17, pts: 2510, delta: -2, you: false },
];

const BADGES = [
  { id: 'first',   label: 'First save',    earned: true,  Icon: IcSparkle, color: '#2E6B4A', tone: 'primary', desc: 'Logged your very first saving action.', date: 'Earned 12 Mar' },
  { id: 'streak7', label: '7 day streak',  earned: true,  Icon: IcMedal,   color: '#8A5A1E', tone: 'accent',  desc: 'Completed at least one quest a day for a week.', date: 'Earned 3 May' },
  { id: 'budget',  label: 'Under budget',  earned: true,  Icon: IcShield,  color: '#345070', tone: 'sky',     desc: 'Finished a full month under your energy budget.', date: 'Earned 1 May' },
  { id: 'streak30',label: '30 day streak', earned: false, Icon: IcMedal,   color: '#8A5A1E', tone: 'accent',  desc: 'Keep a daily quest streak going for 30 days.', progress: 7, total: 30 },
  { id: 'ac',      label: 'AC master',     earned: false, Icon: IcAC,      color: '#2E6B4A', tone: 'primary', desc: 'Complete 20 aircon-related quests.', progress: 8, total: 20 },
  { id: 'saved50', label: '$50 saved',     earned: false, Icon: IcCoins,   color: '#8A5A1E', tone: 'sand',    desc: 'Save $50 versus your starting line.', progress: 24, total: 50 },
  { id: 'top10',   label: 'Top 10',        earned: false, Icon: IcUsers,   color: '#345070', tone: 'sky',     desc: 'Reach the top 10 of your block leaderboard.', progress: 14, total: 10, rank: true },
  { id: 'm100',    label: '100 quests',    earned: false, Icon: IcCheck,   color: '#2E6B4A', tone: 'primary', desc: 'Complete 100 quests in total.', progress: 41, total: 100 },
];

function medalTone(c, rank) {
  if (rank === 1) return { bg: c.accentSoft, fg: '#8A5A1E', bar: c.accent };
  if (rank === 2) return { bg: c.surfaceAlt, fg: c.textMuted, bar: c.textLight };
  return { bg: c.sand, fg: '#5A4A22', bar: c.sandDk };
}
function youBadgeTone(c, tone) {
  return {
    primary: { bg: c.primarySoft, fg: c.primary },
    accent:  { bg: c.accentSoft, fg: '#8A5A1E' },
    sky:     { bg: c.skySoft, fg: '#345070' },
    sand:    { bg: c.sand, fg: '#5A4A22' },
  }[tone] || { bg: c.surfaceAlt, fg: c.textMuted };
}

function YouScreen({ c, points, streak, onLogout }) {
  const [sheet, setSheet] = React.useState(null); // {type:'full'|'neighbour'|'badge', data}
  const me = BLOCK_LB.find(r => r.you);
  const podium = [BLOCK_LB[1], BLOCK_LB[0], BLOCK_LB[2]]; // 2,1,3 visual order
  const meIdx = BLOCK_LB.findIndex(r => r.you);
  const aboveYou = meIdx > 0 ? BLOCK_LB[meIdx - 1] : null;

  const openNeighbour = (row) => setSheet({ type: 'neighbour', data: row });
  const openBadge = (b) => setSheet({ type: 'badge', data: b });

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18, paddingBottom: 100 }}>

      {/* HEADER */}
      <div style={{ padding: '12px 20px 0', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ fontSize: 26, fontWeight: 700, color: c.text, letterSpacing: -0.5 }}>You</div>
        <button style={{ width: 36, height: 36, border: 'none', background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <IcSettings size={20} color={c.textMuted} />
        </button>
      </div>

      {/* PROFILE CARD */}
      <div style={{ padding: '0 20px' }}>
        <Card c={c} style={{ padding: '20px 22px', display: 'flex', alignItems: 'center', gap: 16 }}>
          <div style={{ position: 'relative' }}>
            <div style={{
              width: 64, height: 64, borderRadius: 20,
              background: c.primary, color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 22, fontWeight: 700, letterSpacing: -0.5,
            }}>CT</div>
            <div style={{ position: 'absolute', bottom: -4, right: -4, width: 24, height: 24, borderRadius: 12, background: c.surface, display: 'flex', alignItems: 'center', justifyContent: 'center', border: `2px solid ${c.bg}` }}>
              <Watt size={20} color={c.primary} mood="happy" />
            </div>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 18, fontWeight: 700, color: c.text, letterSpacing: -0.2 }}>Chong Household</div>
            <div style={{ fontSize: 12.5, color: c.textMuted, marginTop: 2, display: 'flex', alignItems: 'center', gap: 4 }}>
              <IcPin size={12} color={c.textMuted} />Block 472 · #08-21
            </div>
            <div style={{ marginTop: 8, display: 'flex', gap: 6 }}>
              <Chip tone="primary" size="sm" c={c} icon={<IcCoins size={11} color={c.primaryDk} />}>{points.toLocaleString()}</Chip>
              <Chip tone="accent" size="sm" c={c} icon={<IcMedal size={11} color="#8A5A1E" />}>{streak} day</Chip>
            </div>
          </div>
        </Card>
      </div>

      {/* COMMUNITY STANDING — interactive podium */}
      <div style={{ padding: '0 20px' }}>
        <YouSectionHd c={c} title="Your block" right={
          <button onClick={() => setSheet({ type: 'full' })} style={{ border: 'none', background: 'transparent', cursor: 'pointer', fontSize: 12.5, fontWeight: 700, color: c.primary, fontFamily: 'inherit', display: 'inline-flex', alignItems: 'center', gap: 3 }}>
            Full list <IcArrowR size={13} color={c.primary} />
          </button>} />
        <Card c={c} style={{ padding: '20px 18px 18px', marginTop: 10 }}>
          {/* podium — each column tappable, medal-toned, #1 gets Watt */}
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'center', gap: 10, marginBottom: 16 }}>
            {podium.map((p, idx) => {
              const t = medalTone(c, p.rank);
              const isFirst = p.rank === 1;
              const h = isFirst ? 100 : idx === 0 ? 76 : 64;
              return (
                <button key={p.rank} onClick={() => openNeighbour(p)} style={{
                  flex: 1, maxWidth: 92, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
                  border: 'none', background: 'transparent', cursor: 'pointer', fontFamily: 'inherit', padding: 0,
                }}>
                  <div style={{ position: 'relative' }}>
                    <div style={{ width: isFirst ? 54 : 42, height: isFirst ? 54 : 42, borderRadius: 16, background: t.bg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                      {isFirst ? <Watt size={32} color={c.primary} mood="cheer" /> : <IcMedal size={20} color={t.fg} />}
                    </div>
                    {isFirst && <div style={{ position: 'absolute', top: -5, right: -5 }}><IcSparkle size={15} color={c.accent} /></div>}
                  </div>
                  <div style={{ fontSize: 11.5, fontWeight: 700, color: c.textMuted }}>{p.handle.split('-')[0]}</div>
                  <div style={{
                    width: '100%', height: h, background: t.bg,
                    borderTop: `4px solid ${t.bar}`, borderRadius: '10px 10px 8px 8px',
                    display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 2,
                  }}>
                    <span style={{ fontSize: 17, fontWeight: 800, color: t.fg }}>#{p.rank}</span>
                    <span style={{ fontSize: 12, fontWeight: 700, color: t.fg }}>−{p.pct}%</span>
                  </div>
                </button>
              );
            })}
          </div>
          {/* you — tappable, with a fun nudge toward the rank above */}
          <button onClick={() => openNeighbour(me)} style={{
            width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: 14,
            background: c.primarySoft, borderRadius: 16, border: `1.5px solid ${c.primary}33`, cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
          }}>
            <div style={{ width: 44, height: 44, borderRadius: 14, background: c.primary, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <span style={{ fontSize: 14, fontWeight: 800, color: '#fff' }}>#{me.rank}</span>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14.5, fontWeight: 700, color: c.primaryDk }}>You · −{me.pct}%</div>
              <div style={{ fontSize: 12, fontWeight: 600, color: c.primaryDk, opacity: 0.7, marginTop: 2 }}>
                {aboveYou ? `${aboveYou.pts - me.pts} pts to pass #${aboveYou.rank}` : 'Leading your block!'}
              </div>
            </div>
            <Chip tone="good" size="sm" c={c} icon={<IcArrowU size={10} color="#2F6147" />}>+{me.delta}</Chip>
            <IcChevR size={16} color={c.primary} />
          </button>
        </Card>
      </div>

      {/* ACHIEVEMENTS — interactive badges */}
      <div style={{ padding: '0 20px' }}>
        <YouSectionHd c={c} title="Badges" right={<span style={{ fontSize: 12, color: c.textMuted, fontWeight: 600 }}>{BADGES.filter(b => b.earned).length} of {BADGES.length}</span>} />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8, marginTop: 10 }}>
          {BADGES.map((b) => {
            const t = youBadgeTone(c, b.tone);
            return (
              <button key={b.id} onClick={() => openBadge(b)} style={{
                aspectRatio: '1', borderRadius: 16,
                background: b.earned ? t.bg : c.surfaceAlt,
                border: 'none',
                display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 6,
                padding: 8, cursor: 'pointer', fontFamily: 'inherit', position: 'relative',
                opacity: b.earned ? 1 : 0.55,
              }}>
                {!b.earned && (
                  <div style={{ position: 'absolute', top: 8, right: 8 }}>
                    <IcLock size={11} color={c.textLight} />
                  </div>
                )}
                <b.Icon size={24} color={b.earned ? t.fg : c.textLight} />
                <div style={{ fontSize: 10.5, fontWeight: 700, color: b.earned ? t.fg : c.textMuted, textAlign: 'center', lineHeight: 1.15 }}>{b.label}</div>
              </button>
            );
          })}
        </div>
      </div>

      {/* COMPACT SETTINGS */}
      <div style={{ padding: '0 20px' }}>
        <YouSectionHd c={c} title="Settings" />
        <Card c={c} style={{ padding: 0, overflow: 'hidden', marginTop: 10 }}>
          {[
            { id: 'notifications', Icon: IcBell,   label: 'Notifications', sub: 'On · quiet after 10pm' },
            { id: 'language', Icon: IcGlobe,  label: 'Language',      sub: 'English' },
            { id: 'privacy', Icon: IcShield, label: 'Privacy',       sub: 'Leaderboard visibility' },
            { id: 'devices', Icon: IcBolt,   label: 'Devices',       sub: '3 connected' },
            { id: 'help', Icon: IcQuestion, label: 'Help & FAQ',  sub: 'Contact support' },
          ].map((r, i, a) => (
            <button key={r.label} onClick={() => setSheet({ type: 'settings', data: r.id })} style={{
              width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
              border: 'none', background: 'transparent', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
              borderBottom: i === a.length - 1 ? 'none' : `1px solid ${c.borderSoft}`,
            }}>
              <div style={{ width: 32, height: 32, borderRadius: 9, background: c.surfaceAlt, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <r.Icon size={16} color={c.textMuted} />
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: c.text }}>{r.label}</div>
                <div style={{ fontSize: 12, color: c.textMuted, marginTop: 1 }}>{r.sub}</div>
              </div>
              <IcChevR size={15} color={c.textLight} />
            </button>
          ))}
        </Card>
      </div>

      <div style={{ padding: '0 20px' }}>
        <button onClick={onLogout} style={{
          width: '100%', height: 48, padding: '0 16px', border: 'none',
          background: 'transparent', cursor: 'pointer', fontFamily: 'inherit',
          color: c.danger, fontWeight: 600, fontSize: 14,
        }}>Log out</button>
      </div>

      {/* SHEETS */}
      {sheet && (
        <YouSheet c={c} onClose={() => setSheet(null)}>
          {sheet.type === 'full' && <FullLeaderboard c={c} onPick={(row) => setSheet({ type: 'neighbour', data: row })} />}
          {sheet.type === 'neighbour' && <NeighbourDetail c={c} row={sheet.data} />}
          {sheet.type === 'badge' && <BadgeDetail c={c} b={sheet.data} />}
          {sheet.type === 'settings' && <SettingsDetail c={c} which={sheet.data} />}
        </YouSheet>
      )}
    </div>
  );
}

// Bottom sheet shell
function YouSheet({ c, onClose, children }) {
  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, background: 'rgba(20,30,25,0.42)', zIndex: 120,
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center', animation: 'm-fadeup .18s ease',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', maxHeight: '82%', background: c.surface, borderRadius: '24px 24px 0 0',
        padding: '12px 0 28px', display: 'flex', flexDirection: 'column',
        animation: 'sh-slideup .26s ease', overflow: 'hidden',
      }}>
        <div style={{ width: 36, height: 4, background: c.border, borderRadius: 2, alignSelf: 'center', marginBottom: 8, flexShrink: 0 }} />
        <div style={{ overflowY: 'auto', padding: '4px 20px 0' }}>{children}</div>
      </div>
    </div>
  );
}

// Full block leaderboard
function FullLeaderboard({ c, onPick }) {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
        <IcBuilding size={20} color={c.primary} />
        <div>
          <div style={{ fontSize: 18, fontWeight: 700, color: c.text, letterSpacing: -0.3 }}>Block 472</div>
          <div style={{ fontSize: 12, color: c.textMuted }}>Savings vs each home's own start · this month</div>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        {BLOCK_LB.map(row => (
          <button key={row.rank} onClick={() => onPick(row)} style={{
            display: 'flex', alignItems: 'center', gap: 12, padding: '11px 12px', minHeight: 56,
            background: row.you ? c.primarySoft : 'transparent', border: 'none', borderRadius: 12,
            cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left', width: '100%',
          }}>
            <div style={{ width: 28, fontSize: 13, fontWeight: 700, color: row.you ? c.primaryDk : c.textLight, fontVariantNumeric: 'tabular-nums' }}>#{row.rank}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: row.you ? 700 : 600, color: c.text }}>{row.you ? 'You' : row.handle}</div>
              <div style={{ fontSize: 11.5, color: c.textMuted, marginTop: 1 }}>{row.pts.toLocaleString()} pts</div>
            </div>
            <div style={{ fontSize: 14, fontWeight: 700, color: c.text, fontVariantNumeric: 'tabular-nums' }}>−{row.pct}%</div>
            <div style={{ width: 30, textAlign: 'right', fontSize: 11.5, fontWeight: 700, fontVariantNumeric: 'tabular-nums', color: row.delta > 0 ? c.good : row.delta < 0 ? c.danger : c.textLight }}>
              {row.delta === 0 ? '—' : row.delta > 0 ? `↑${row.delta}` : `↓${Math.abs(row.delta)}`}
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

// Deterministic pseudo-random 7-day trend around a home's headline %, so
// every neighbour gets a plausible sparkline without extra mock data.
function neighbourTrend(seedRank, pct) {
  let s = seedRank * 9301 + 49297;
  const bars = [];
  for (let i = 0; i < 7; i++) {
    s = (s * 9301 + 49297) % 233280;
    bars.push(Math.max(2, Math.round(pct + (s / 233280 - 0.5) * 16)));
  }
  return bars;
}
const NB_DAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

// Neighbour / you detail — scrubbable trend chart + plain-language stats
function NeighbourDetail({ c, row }) {
  const [dSel, setDSel] = React.useState(null);
  const trend = React.useMemo(() => neighbourTrend(row.rank, row.pct), [row]);
  const shown = dSel == null ? row.pct : trend[dSel];
  const shownLabel = dSel == null ? 'This week, on average' : NB_DAYS[dSel];
  const stats = [
    { label: 'Rank', value: `#${row.rank}`, sub: 'place on your block', Icon: IcMedal },
    { label: 'Saving', value: `−${row.pct}%`, sub: 'less than their own usual month', Icon: IcLeaf },
    { label: 'Points', value: row.pts.toLocaleString(), sub: 'earned from quests + streaks', Icon: IcCoins },
    { label: 'This week', value: row.delta === 0 ? 'Steady' : row.delta > 0 ? `+${row.delta}` : `−${Math.abs(row.delta)}`, sub: row.delta === 0 ? 'rank unchanged' : row.delta > 0 ? 'spots climbed' : 'spots dropped', Icon: IcTrend },
  ];
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 16 }}>
        <div style={{ width: 56, height: 56, borderRadius: 18, background: row.you ? c.primary : c.surfaceAlt, color: row.you ? '#fff' : c.textMuted, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, fontWeight: 800 }}>
          #{row.rank}
        </div>
        <div>
          <div style={{ fontSize: 20, fontWeight: 700, color: c.text, letterSpacing: -0.3 }}>{row.you ? 'You' : `Unit ${row.handle}`}</div>
          <div style={{ fontSize: 12.5, color: c.textMuted, marginTop: 2 }}>Block 472 · saving −{row.pct}% this month</div>
        </div>
      </div>

      {/* interactive trend — tap or drag a day, same chart language as Analysis */}
      <div style={{ background: c.surfaceAlt, borderRadius: 16, padding: '14px 14px 12px', marginBottom: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ fontSize: 11, fontWeight: 700, color: c.textLight, letterSpacing: 0.4, textTransform: 'uppercase' }}>Savings by day</span>
          {dSel != null && <AnClear c={c} onClick={() => setDSel(null)} />}
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, margin: '4px 0 10px' }}>
          <span style={{ fontSize: 26, fontWeight: 800, color: c.text, fontVariantNumeric: 'tabular-nums' }}>−{shown}%</span>
          <span style={{ fontSize: 12.5, fontWeight: 600, color: c.textMuted }}>{shownLabel} · less power used than usual</span>
        </div>
        <AnBars bars={trend} sel={dSel} onPick={setDSel} height={64} gap={6} radius={5}
          colorFor={(i, isSel) => isSel ? c.accent : row.you ? c.primary : c.sky} />
        <div style={{ marginTop: 6, display: 'flex', gap: 6 }}>
          {NB_DAYS.map((l, i) => <span key={i} style={{ flex: 1, textAlign: 'center', fontSize: 10.5, fontWeight: 600, color: dSel === i ? c.primaryDk : c.textLight }}>{l}</span>)}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 16 }}>
        {stats.map(s => (
          <div key={s.label} style={{ background: c.surfaceAlt, borderRadius: 14, padding: 14 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <s.Icon size={14} color={c.textMuted} />
              <span style={{ fontSize: 11, fontWeight: 700, color: c.textLight, letterSpacing: 0.3, textTransform: 'uppercase' }}>{s.label}</span>
            </div>
            <div style={{ fontSize: 21, fontWeight: 700, color: c.text, marginTop: 6, fontVariantNumeric: 'tabular-nums', letterSpacing: -0.3 }}>{s.value}</div>
            <div style={{ fontSize: 11, fontWeight: 500, color: c.textMuted, marginTop: 2, lineHeight: 1.3 }}>{s.sub}</div>
          </div>
        ))}
      </div>
      {!row.you && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px', background: c.primarySoft, borderRadius: 12 }}>
          <IcLock size={15} color={c.primaryDk} />
          <div style={{ fontSize: 12.5, color: c.primaryDk, lineHeight: 1.4 }}>Neighbours stay anonymous — only block + unit shown, never names.</div>
        </div>
      )}
    </div>
  );
}

// Badge detail
function BadgeDetail({ c, b }) {
  const tones = {
    primary: { bg: c.primarySoft, fg: c.primary },
    accent:  { bg: c.accentSoft, fg: '#8A5A1E' },
    sky:     { bg: c.skySoft, fg: '#345070' },
    sand:    { bg: c.sand, fg: '#5A4A22' },
  }[b.tone] || { bg: c.surfaceAlt, fg: c.textMuted };
  const pct = b.earned ? 100 : Math.min(100, Math.round((b.progress / b.total) * 100));
  return (
    <div style={{ textAlign: 'center', paddingBottom: 4 }}>
      <div style={{
        width: 88, height: 88, borderRadius: 26, margin: '4px auto 16px',
        background: b.earned ? tones.bg : c.surfaceAlt,
        display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative',
        opacity: b.earned ? 1 : 0.85,
      }}>
        <b.Icon size={42} color={b.earned ? tones.fg : c.textLight} />
        {!b.earned && (
          <div style={{ position: 'absolute', bottom: -4, right: -4, width: 28, height: 28, borderRadius: 14, background: c.surface, border: `2px solid ${c.bg}`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <IcLock size={13} color={c.textMuted} />
          </div>
        )}
      </div>
      <div style={{ fontSize: 20, fontWeight: 700, color: c.text, letterSpacing: -0.3 }}>{b.label}</div>
      <div style={{ fontSize: 13.5, color: c.textMuted, marginTop: 6, lineHeight: 1.5, maxWidth: 280, marginLeft: 'auto', marginRight: 'auto' }}>{b.desc}</div>

      {b.earned ? (
        <div style={{ marginTop: 18, display: 'inline-flex', alignItems: 'center', gap: 6, padding: '8px 14px', background: c.goodSoft, borderRadius: 999 }}>
          <IcCheck size={14} color={c.good} />
          <span style={{ fontSize: 13, fontWeight: 700, color: '#2F6147' }}>{b.date}</span>
        </div>
      ) : (
        <div style={{ marginTop: 18, padding: '0 8px' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
            <span style={{ fontSize: 12, fontWeight: 700, color: c.textLight, letterSpacing: 0.3, textTransform: 'uppercase' }}>Progress</span>
            <span style={{ fontSize: 13, fontWeight: 700, color: c.text, fontVariantNumeric: 'tabular-nums' }}>
              {b.rank ? `#${b.progress} → top ${b.total}` : `${b.progress} / ${b.total}`}
            </span>
          </div>
          <Bar value={b.rank ? 1 : b.progress} max={b.rank ? 2 : b.total} c={c} height={10} tone="primary" />
          <div style={{ fontSize: 12, color: c.textMuted, marginTop: 10 }}>{b.rank ? 'Climb 4 more spots to unlock' : `${b.total - b.progress} to go`}</div>
        </div>
      )}
    </div>
  );
}

function YouSectionHd({ c, title, right }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
      <div style={{ fontSize: 15, fontWeight: 700, color: c.text, letterSpacing: -0.2 }}>{title}</div>
      {right}
    </div>
  );
}

// ── Reusable controls for settings panels ──────────────────────────────────
function SetToggle({ c, label, sub, value, onChange }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 14px', background: c.surfaceAlt, borderRadius: 14 }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: c.text }}>{label}</div>
        {sub && <div style={{ fontSize: 12, color: c.textMuted, marginTop: 1 }}>{sub}</div>}
      </div>
      <button onClick={() => onChange(!value)} style={{
        width: 44, height: 26, padding: 0, border: 'none', flexShrink: 0,
        background: value ? c.primary : c.border, borderRadius: 999, position: 'relative', cursor: 'pointer',
        transition: 'background .2s',
      }}>
        <div style={{ position: 'absolute', top: 3, left: value ? 21 : 3, width: 20, height: 20, borderRadius: 10, background: '#fff', transition: 'left .2s', boxShadow: '0 1px 3px rgba(0,0,0,0.2)' }} />
      </button>
    </div>
  );
}

function SetRadioRow({ c, label, sub, selected, onClick }) {
  return (
    <button onClick={onClick} style={{
      width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: '13px 14px',
      background: selected ? c.primarySoft : c.surfaceAlt, borderRadius: 14, border: 'none',
      cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: c.text }}>{label}</div>
        {sub && <div style={{ fontSize: 12, color: c.textMuted, marginTop: 1 }}>{sub}</div>}
      </div>
      <div style={{
        width: 22, height: 22, borderRadius: 11, flexShrink: 0,
        border: `2px solid ${selected ? c.primary : c.border}`,
        background: selected ? c.primary : 'transparent',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {selected && <IcCheck size={13} color="#fff" />}
      </div>
    </button>
  );
}

function SettingsHead({ c, Icon, title, sub }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
      <div style={{ width: 44, height: 44, borderRadius: 13, background: c.primarySoft, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <Icon size={22} color={c.primary} />
      </div>
      <div>
        <div style={{ fontSize: 19, fontWeight: 700, color: c.text, letterSpacing: -0.3 }}>{title}</div>
        {sub && <div style={{ fontSize: 12.5, color: c.textMuted, marginTop: 1 }}>{sub}</div>}
      </div>
    </div>
  );
}

function SetGroupLabel({ c, children }) {
  return <div style={{ fontSize: 11, fontWeight: 700, color: c.textLight, letterSpacing: 0.4, textTransform: 'uppercase', margin: '16px 4px 8px' }}>{children}</div>;
}

// ── Settings panels — fully working state ──────────────────────────────────
function SettingsDetail({ c, which }) {
  if (which === 'notifications') return <NotificationsPanel c={c} />;
  if (which === 'language')      return <LanguagePanel c={c} />;
  if (which === 'privacy')       return <PrivacyPanel c={c} />;
  if (which === 'devices')       return <DevicesPanel c={c} />;
  if (which === 'help')          return <HelpPanel c={c} />;
  return null;
}

function NotificationsPanel({ c }) {
  const [s, setS] = React.useState({
    liveTips: true, questReminders: true, streakAlerts: true,
    weeklyRecap: false, leaderboard: true, quietHours: true,
  });
  const set = (k) => (v) => setS(p => ({ ...p, [k]: v }));
  return (
    <div style={{ paddingBottom: 8 }}>
      <SettingsHead c={c} Icon={IcBell} title="Notifications" sub="Choose what Sprig pings you about" />
      <SetGroupLabel c={c}>Energy</SetGroupLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <SetToggle c={c} label="Live tips" sub="“Open a window — it's cooler out”" value={s.liveTips} onChange={set('liveTips')} />
        <SetToggle c={c} label="Quest reminders" sub="Before a timed quest expires" value={s.questReminders} onChange={set('questReminders')} />
      </div>
      <SetGroupLabel c={c}>Progress</SetGroupLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <SetToggle c={c} label="Streak alerts" sub="When your streak is at risk" value={s.streakAlerts} onChange={set('streakAlerts')} />
        <SetToggle c={c} label="Weekly recap" sub="Sunday summary of your savings" value={s.weeklyRecap} onChange={set('weeklyRecap')} />
        <SetToggle c={c} label="Leaderboard moves" sub="When your block rank changes" value={s.leaderboard} onChange={set('leaderboard')} />
      </div>
      <SetGroupLabel c={c}>Timing</SetGroupLabel>
      <SetToggle c={c} label="Quiet hours" sub="Mute 10pm – 7am" value={s.quietHours} onChange={set('quietHours')} />
    </div>
  );
}

function LanguagePanel({ c }) {
  const [lang, setLang] = React.useState('en');
  const langs = [
    { id: 'en', label: 'English', sub: 'English' },
    { id: 'zh', label: '中文', sub: 'Chinese (Simplified)' },
    { id: 'ms', label: 'Bahasa Melayu', sub: 'Malay' },
    { id: 'ta', label: 'தமிழ்', sub: 'Tamil' },
  ];
  return (
    <div style={{ paddingBottom: 8 }}>
      <SettingsHead c={c} Icon={IcGlobe} title="Language" sub="Singapore's four official languages" />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {langs.map(l => (
          <SetRadioRow key={l.id} c={c} label={l.label} sub={l.sub} selected={lang === l.id} onClick={() => setLang(l.id)} />
        ))}
      </div>
    </div>
  );
}

function PrivacyPanel({ c }) {
  const [s, setS] = React.useState({ leaderboard: true, anonHandle: true, shareData: false, neighbourCompare: true });
  const set = (k) => (v) => setS(p => ({ ...p, [k]: v }));
  return (
    <div style={{ paddingBottom: 8 }}>
      <SettingsHead c={c} Icon={IcShield} title="Privacy" sub="You're always in control" />
      <SetGroupLabel c={c}>Community</SetGroupLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <SetToggle c={c} label="Show on leaderboard" sub="Appear in your block ranking" value={s.leaderboard} onChange={set('leaderboard')} />
        <SetToggle c={c} label="Hide unit number" sub="Show only “Block 472” to others" value={s.anonHandle} onChange={set('anonHandle')} />
        <SetToggle c={c} label="Neighbour comparison" sub="Compare to similar homes" value={s.neighbourCompare} onChange={set('neighbourCompare')} />
      </div>
      <SetGroupLabel c={c}>Data</SetGroupLabel>
      <SetToggle c={c} label="Share anonymised usage" sub="Helps EMA improve the grid" value={s.shareData} onChange={set('shareData')} />
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: '12px 14px', background: c.primarySoft, borderRadius: 12, marginTop: 14 }}>
        <IcLock size={15} color={c.primaryDk} />
        <div style={{ fontSize: 12.5, color: c.primaryDk, lineHeight: 1.45 }}>Your name and exact address are never shared. Neighbours only ever see block + unit.</div>
      </div>
    </div>
  );
}

function DevicesPanel({ c }) {
  const [devices, setDevices] = React.useState([
    { id: 'ac', name: 'Aircon', room: 'Living room', Icon: IcAC, online: true, watts: 1180 },
    { id: 'water', name: 'Water heater', room: 'Bathroom', Icon: IcWater, online: true, watts: 0 },
    { id: 'fridge', name: 'Fridge', room: 'Kitchen', Icon: IcFridge, online: true, watts: 95 },
  ]);
  return (
    <div style={{ paddingBottom: 8 }}>
      <SettingsHead c={c} Icon={IcBolt} title="Devices" sub={`${devices.filter(d => d.online).length} connected`} />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {devices.map(d => (
          <div key={d.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 14px', background: c.surfaceAlt, borderRadius: 14 }}>
            <div style={{ width: 40, height: 40, borderRadius: 11, background: c.surface, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <d.Icon size={20} color={c.textMuted} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: c.text }}>{d.name}</div>
              <div style={{ fontSize: 12, color: c.textMuted, marginTop: 1, display: 'flex', alignItems: 'center', gap: 6 }}>
                <IcPin size={11} color={c.textMuted} />{d.room}
              </div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <div style={{ width: 7, height: 7, borderRadius: 4, background: d.online ? c.good : c.textLight }} />
              <span style={{ fontSize: 11.5, fontWeight: 600, color: d.online ? c.good : c.textLight }}>
                {d.online ? (d.watts > 0 ? `${d.watts}W` : 'Idle') : 'Offline'}
              </span>
            </div>
          </div>
        ))}
      </div>
      <button style={{
        width: '100%', marginTop: 12, height: 50, border: `1.5px dashed ${c.border}`, background: 'transparent',
        borderRadius: 14, cursor: 'pointer', fontFamily: 'inherit', color: c.primary, fontWeight: 600, fontSize: 14,
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      }}>
        <IcPlus size={18} color={c.primary} /> Add a device
      </button>
    </div>
  );
}

function HelpPanel({ c }) {
  const [open, setOpen] = React.useState(null);
  const faqs = [
    { q: 'How is my daily budget set?', a: 'We take the monthly savings goal you chose at sign-up and divide it across the month, so each day gets a fair share. Use less than your daily budget and you bank the difference.' },
    { q: 'Where does my usage data come from?', a: 'From the smart plugs and meter connected to your home. Readings update every few minutes — no manual entry needed.' },
    { q: 'How do I earn points?', a: 'Complete quests, follow live tips, and keep daily streaks. Points convert to bill credits, vouchers, and donations in the Play tab.' },
    { q: 'Who can see my ranking?', a: 'Only other homes in your block, shown as “Block 472 · #08-21”. Your name and full address are never shared. Turn this off anytime in Privacy.' },
    { q: 'What if a device shows offline?', a: 'Check the smart plug is powered and on Wi-Fi. If it stays offline, re-pair it from Settings → Devices.' },
  ];
  return (
    <div style={{ paddingBottom: 8 }}>
      <SettingsHead c={c} Icon={IcQuestion} title="Help & FAQ" sub="Quick answers, or reach a human" />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {faqs.map((f, i) => (
          <div key={i} style={{ background: c.surfaceAlt, borderRadius: 14, overflow: 'hidden' }}>
            <button onClick={() => setOpen(open === i ? null : i)} style={{
              width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: '14px',
              border: 'none', background: 'transparent', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
            }}>
              <div style={{ flex: 1, fontSize: 14, fontWeight: 600, color: c.text }}>{f.q}</div>
              <div style={{ color: c.textLight, transform: open === i ? 'rotate(180deg)' : 'none', transition: 'transform .2s' }}>
                <IcChevD size={16} color={c.textLight} />
              </div>
            </button>
            {open === i && (
              <div style={{ padding: '0 14px 14px', fontSize: 13.5, color: c.textMuted, lineHeight: 1.55 }}>{f.a}</div>
            )}
          </div>
        ))}
      </div>
      <button style={{
        width: '100%', marginTop: 14, height: 52, border: 'none', background: c.primary,
        borderRadius: 14, cursor: 'pointer', fontFamily: 'inherit', color: '#fff', fontWeight: 700, fontSize: 15,
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      }}>
        <IcBell size={18} color="#fff" /> Contact support
      </button>
    </div>
  );
}

Object.assign(window, { YouScreen });
