// p12-me.jsx — Me screen + ad flow (P-ad-pre / P-ad-consent / P-ad-reward)

function ScreenMe({ state, onNavigate, user }) {
  const T = window.T;
  const offline = state === 'offline';
  const denied  = state === 'denied';        // user has denied ATT app-wide
  const todayPouch = user?.todayPouch ?? 7;
  const todayCap   = user?.todayCap   ?? 10;
  const todayBoost = user?.todayBoost ?? 2;
  const isFull = todayPouch >= todayCap;
  const boosted = todayCap > 10;             // ad boost has been applied today
  const adAmount = denied ? 1 : 3;            // per-ad slots based on tracking consent
  const bubbles = [
    '오늘도 같이 채워봐요!',
    '한 입씩, 천천히도 좋아요',
    '여행이 점점 가까워지네요',
    '오늘 만난 첫 씨앗은 뭐였어요?',
    '꺼내 들으면 더 잘 기억돼요',
  ];
  // Bubble state: each click cycles to a NEW message (not the same one again)
  // and auto-dismisses after BUBBLE_TTL. Bumping `bubbleSeq` re-keys the node
  // so the entry animation replays even when transitioning bubble→bubble.
  const BUBBLE_TTL = 3200;
  const [bubble, setBubble] = React.useState(
    state === 'bubble' ? { idx: 0, seq: 0 } : null
  );
  const dismissTimer = React.useRef(null);
  const showBubble = () => {
    setBubble(prev => {
      // Pick a random index that isn't the current one.
      let next;
      do { next = Math.floor(Math.random() * bubbles.length); }
      while (bubbles.length > 1 && prev && next === prev.idx);
      return { idx: next, seq: (prev?.seq ?? 0) + 1 };
    });
  };
  React.useEffect(() => {
    if (!bubble) return;
    clearTimeout(dismissTimer.current);
    dismissTimer.current = setTimeout(() => setBubble(null), BUBBLE_TTL);
    return () => clearTimeout(dismissTimer.current);
  }, [bubble?.seq]);

  return (
    <div style={{
      position: 'absolute', inset: 0, background: T.bg,
      display: 'flex', flexDirection: 'column',
    }}>
      {/* Profile hero — single line, matches P02 brand-bar rhythm.
          Avatar + name + total-seed count + gear. No today's-cap here
          (that lives in the mascot card so we don't duplicate it). */}
      <div style={{
        flexShrink: 0,
        padding: '8px 12px 10px 20px',
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <div style={{
          width: 36, height: 36, borderRadius: '50%',
          background: '#F2EBE0', overflow: 'hidden',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
          border: '0.5px solid rgba(60,42,20,0.10)',
        }}>
          <Hamster count={todayPouch} max={todayCap} size={36} headOnly/>
        </div>
        <div style={{
          flex: 1, minWidth: 0,
          display: 'flex', alignItems: 'baseline', gap: 8,
          whiteSpace: 'nowrap', overflow: 'hidden',
        }}>
          <span style={{ fontSize: 18, fontWeight: 800, color: T.ink, letterSpacing: '-0.03em' }}>
            {user?.name || '여행자'}<span style={{ fontWeight: 600, color: T.ink2 }}>님</span>
          </span>
          <span style={{ color: T.ink4, fontSize: 12 }}>·</span>
          <span style={{ fontSize: 13, color: T.ink3, fontWeight: 500, letterSpacing: '-0.01em' }}>
            씨앗 {user?.totalSeeds ?? 47}개
          </span>
        </div>
        {offline && <OfflineBadge/>}
        <IconButton icon={<Icons.Cog size={22} color={T.ink}/>}
                    onClick={() => onNavigate('P13')}/>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '0 20px 88px' }}>
        {/* Mascot card + speech bubble.
            Bubble is absolutely positioned at the top of the card. The
            card reserves ~50px of top padding so the bubble never covers
            the mascot AND the layout never shifts when it appears/hides. */}
        <div style={{
          background: T.surface, borderRadius: 18,
          border: `0.5px solid ${T.hairline}`,
          padding: '42px 20px 18px', marginBottom: 14,
          position: 'relative', overflow: 'hidden',
        }}>
          {/* Decorative radial */}
          <div style={{
            position: 'absolute', top: -40, right: -40,
            width: 180, height: 180, borderRadius: '50%',
            background: `radial-gradient(circle, ${T.accent}14 0%, transparent 70%)`,
          }}/>

          {/* Speech bubble — lives in the reserved top region.
              Position is independent of content flow, so showing/hiding
              never moves the mascot or anything below it. */}
          {bubble && (
            <div key={bubble.seq} style={{
              position: 'absolute',
              top: 10, left: 16, right: 16,
              display: 'flex', justifyContent: 'center',
              zIndex: 5, pointerEvents: 'none',
            }}>
              <div style={{
                position: 'relative', maxWidth: 280,
                background: T.surface2,
                border: `0.5px solid ${T.hairlineStrong}`,
                borderRadius: 16,
                padding: '8px 14px',
                fontSize: 13.5, color: T.ink, fontWeight: 500,
                lineHeight: 1.35, letterSpacing: '-0.01em',
                whiteSpace: 'nowrap',
                boxShadow: '0 6px 16px rgba(31,24,18,0.08)',
              }}>
                {bubbles[bubble.idx]}
                {/* Tail — points down toward the mascot */}
                <div style={{
                  position: 'absolute',
                  bottom: -5, left: '50%',
                  width: 10, height: 10,
                  transform: 'translateX(-50%) rotate(45deg)',
                  background: T.surface2,
                  borderRight: `0.5px solid ${T.hairlineStrong}`,
                  borderBottom: `0.5px solid ${T.hairlineStrong}`,
                }}/>
              </div>
            </div>
          )}

          <div style={{
            display: 'flex', flexDirection: 'column', alignItems: 'center',
            gap: 8, position: 'relative', zIndex: 1,
          }}>
            <div onClick={showBubble} style={{ cursor: 'pointer' }}>
              <Hamster count={todayPouch} max={todayCap} size={110}/>
            </div>
            <div style={{ textAlign: 'center' }}>
              <div style={{
                fontSize: 11, fontWeight: 700, color: T.ink3,
                letterSpacing: '0.08em', textTransform: 'uppercase',
                marginBottom: 6,
              }}>오늘 담은 씨앗</div>

              {/* Count + extensibility hint.
                  • boosted    → solid filled badge (e.g. +3)
                  • not boosted → dashed "광고로 +3" pill, hinting the cap can grow
                  • no boost left → nothing extra (just the count) */}
              <div style={{
                fontSize: 28, fontWeight: 800, color: T.ink,
                letterSpacing: '-0.03em', lineHeight: 1,
                display: 'inline-flex', alignItems: 'baseline', gap: 8,
              }}>
                <span>{todayPouch}<span style={{ color: T.ink3, fontWeight: 600 }}>/{todayCap}</span></span>
                {boosted ? (
                  <span style={{
                    fontSize: 10.5, fontWeight: 800, color: T.accent,
                    background: T.accentSoft, padding: '3px 7px',
                    borderRadius: 7, letterSpacing: '0.04em',
                  }}>+{todayCap - 10}</span>
                ) : (todayBoost > 0 && !offline && !isFull) && (
                  <button onClick={() => onNavigate('P-ad-pre')} style={{
                    fontSize: 10.5, fontWeight: 800, color: T.accent,
                    background: 'transparent',
                    border: `1px dashed ${T.accent}88`,
                    padding: '3px 8px',
                    borderRadius: 7, letterSpacing: '0.02em',
                    fontFamily: 'inherit', cursor: 'pointer',
                    whiteSpace: 'nowrap', flexShrink: 0,
                    transform: 'translateY(-2px)',
                    lineHeight: 1.1,
                  }}>
                    +{adAmount} 가능
                  </button>
                )}
              </div>
              <div style={{
                fontSize: 12.5, color: T.ink2,
                marginTop: 8, lineHeight: 1.4,
              }}>
                {todayPouch === 0 && '새로운 하루예요. 어떤 씨앗을 담아볼까요?'}
                {todayPouch > 0 && todayPouch < todayCap - 2 && (
                  boosted
                    ? `광고로 슬롯 이 늘어났어요. 현재 ${todayPouch}개 담았어요`
                    : `오늘 볼주머니에 ${todayPouch}개 담았어요`
                )}
                {todayPouch >= todayCap - 2 && todayPouch < todayCap && `${todayPouch}개나 담았어요. 거의 다 찼네요`}
                {todayPouch >= todayCap && '가득 찼어요. 내일 또 같이 채워봐요'}
              </div>
              {!offline && <ResetCountdownInline isFull={isFull}/>}
            </div>
          </div>
        </div>{/* /mascot card */}

        {/* Ad boost section */}
        <Button
          kind={isFull ? 'primary' : 'soft'}
          fullWidth
          disabled={offline || todayBoost === 0}
          onClick={() => onNavigate('P-ad-pre')}
          icon={<Icons.Sparkle size={18} color={isFull ? '#FFF' : T.accent}/>}
          style={{ height: 52, marginBottom: 10 }}
        >
          광고 보고 슬롯 추가하기 · 오늘 {todayBoost}회 남음
        </Button>
        <div style={{ fontSize: 12, color: T.ink3, textAlign: 'center', padding: '0 16px' }}>
          {offline
            ? '오프라인이라 광고를 볼 수 없어요'
            : denied
              ? '지금은 한 번에 1개. 추적 허용하면 3개씩 받아요'
              : todayBoost === 0
                ? '내일 또 받을 수 있어요'
                : '추적을 허용하면 한 번에 3개, 거부하면 1개 받아요'}
        </div>

        {/* Footer card — tracking persuasion only (자정 카운트다운은
            마스코트 카드 안으로 흡수). */}
        {denied && (
          <div style={{ marginTop: 22 }}>
            <TrackingPersuadeCard onOpen={() => onNavigate('P13')}/>
          </div>
        )}

        {/* 내 곳간 — 아껴둔 씨앗 영구 보관함. 볼주머니(오늘·임시)와 짝.
            맨 아래에 두어 "오늘 임시 → 영구 비축"의 흐름을 한 화면에. */}
        <GotganSection onNavigate={onNavigate} forceEmpty={state === 'noFav'}/>
      </div>
    </div>
  );
}

// ── Footer cards ──────────────────────────────────────────────

// 내 곳간 — 즐겨찾기(별표) 씨앗을 모아둔 영구 보관함.
// 가로 스크롤로 미리보기, "전체보기"로 P03을 곳간 필터 켠 채 진입.
function GotganSection({ onNavigate, forceEmpty }) {
  const T = window.T;
  const favIds = window.__cpSeedFavs || [];
  const seeds = (window.MOCK_SEEDS || []).filter(s => favIds.includes(s.id));
  const empty = forceEmpty || seeds.length === 0;

  return (
    <div style={{ marginTop: 26 }}>
      {/* heading */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 7,
                    marginBottom: empty ? 12 : 4, padding: '0 2px' }}>
        <Icons.Star size={16} color={T.accent} filled/>
        <span style={{ fontSize: 15, fontWeight: 800, color: T.ink,
                       letterSpacing: '-0.02em' }}>내 곳간</span>
        <span style={{ fontSize: 13, fontWeight: 600, color: T.ink3 }}>{empty ? 0 : seeds.length}개</span>
        <span style={{ flex: 1 }}/>
        {!empty && (
          <button onClick={() => onNavigate('P03', { fav: '1', from: 'P12' })} style={{
            background: 'transparent', border: 'none', color: T.accent,
            fontSize: 12.5, fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer',
            letterSpacing: '-0.01em', padding: '4px 0 4px 6px',
            display: 'inline-flex', alignItems: 'center', gap: 1,
            WebkitTapHighlightColor: 'transparent',
          }}>
            전체보기 <Icons.ChevronR size={15} color={T.accent}/>
          </button>
        )}
      </div>
      {!empty && (
        <div style={{ fontSize: 12, color: T.ink3, lineHeight: 1.45,
                      margin: '0 2px 12px' }}>
          아껴둔 씨앗을 집 곳간에 따로 모아둬요 · 골라서 다시 들어보세요
        </div>
      )}

      {empty ? (
        // 빈 곳간 — 먹이 없는 햄스터(count=0)로 "아직 비축 전" 상태를 은유.
        <div style={{
          background: T.surface, borderRadius: 16,
          border: `1px dashed ${T.hairlineStrong}`,
          padding: '22px 18px 20px', textAlign: 'center',
          position: 'relative', overflow: 'hidden',
        }}>
          <div style={{
            position: 'absolute', top: -34, right: -34,
            width: 150, height: 150, borderRadius: '50%',
            background: `radial-gradient(circle, ${T.accent}10 0%, transparent 70%)`,
          }}/>
          <div style={{
            width: 64, height: 64, borderRadius: '50%',
            background: '#F2EBE0', border: `0.5px solid ${T.hairline}`,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            overflow: 'hidden', marginBottom: 12, position: 'relative',
          }}>
            <Hamster count={0} max={10} size={64} headOnly/>
          </div>
          <div style={{
            fontSize: 14.5, fontWeight: 700, color: T.ink,
            letterSpacing: '-0.02em', marginBottom: 6, position: 'relative',
          }}>곳간이 아직 비어 있어요</div>
          <div style={{
            fontSize: 12.5, color: T.ink2, lineHeight: 1.55,
            maxWidth: 252, margin: '0 auto 16px', position: 'relative',
          }}>
            씨앗 상세에서 <b style={{ color: T.accent }}>★</b> 을 누르면<br/>
            아껴둔 표현이 여기 곳간에 차곡차곡 모여요
          </div>
          <button onClick={() => onNavigate('P03', { from: 'P12' })} style={{
            height: 40, padding: '0 18px', borderRadius: 12,
            background: T.accentSoft, color: T.accent, border: 'none',
            fontFamily: 'inherit', fontSize: 13, fontWeight: 700, cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', gap: 4,
            letterSpacing: '-0.01em', position: 'relative',
            WebkitTapHighlightColor: 'transparent',
          }}>
            씨앗 둘러보기 <Icons.ChevronR size={15} color={T.accent}/>
          </button>
        </div>
      ) : (
        // bleed to screen edges so the last card peeks past the right gutter
        <div style={{
          display: 'flex', gap: 10, overflowX: 'auto',
          margin: '0 -20px', padding: '2px 20px 6px',
          scrollbarWidth: 'none',
        }}>
          {seeds.map(s => (
            <SeedCardMini key={s.id} seed={s}
                          onClick={() => onNavigate('P05', { seedId: s.id })}/>
          ))}
        </div>
      )}
    </div>
  );
}

// "Allow tracking" persuasion — shown only when ATT is denied.
function TrackingPersuadeCard({ onOpen }) {
  const T = window.T;
  return (
    <div style={{
      background: T.surface, borderRadius: 14,
      border: `0.5px dashed ${T.accent}80`,
      padding: '14px 16px',
      display: 'flex', alignItems: 'center', gap: 12,
    }}>
      <div style={{
        width: 38, height: 38, borderRadius: 12,
        background: T.accentSoft,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        <Icons.Sparkle size={20} color={T.accent}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 13.5, fontWeight: 700, color: T.ink,
          letterSpacing: '-0.02em', marginBottom: 2,
        }}>추적 허용하면 한 번에 <span style={{ color: T.accent }}>3개</span></div>
        <div style={{ fontSize: 12, color: T.ink2, lineHeight: 1.4 }}>
          지금은 1개씩만 받고 있어요
        </div>
      </div>
      <button onClick={onOpen} style={{
        background: T.accent, color: '#FFF',
        border: 'none', borderRadius: 12,
        padding: '9px 12px', fontSize: 12, fontWeight: 700,
        fontFamily: 'inherit', cursor: 'pointer', flexShrink: 0,
        letterSpacing: '-0.01em', whiteSpace: 'nowrap',
      }}>설정 열기</button>
    </div>
  );
}

// Reset countdown — folded into the mascot card as a single subtle line.
// Uses only existing data (system clock); no new feature, just a meta line.
function ResetCountdownInline({ isFull }) {
  const T = window.T;
  const calc = () => {
    const now = new Date();
    const next = new Date(now); next.setHours(24, 0, 0, 0);
    const ms = next - now;
    return { h: Math.floor(ms / 3.6e6), m: Math.floor((ms % 3.6e6) / 6e4) };
  };
  const [{ h, m }, setT] = React.useState(calc);
  React.useEffect(() => {
    const id = setInterval(() => setT(calc()), 30000);
    return () => clearInterval(id);
  }, []);
  return (
    <div style={{
      fontSize: 11.5, color: T.ink3, marginTop: 7,
      letterSpacing: '-0.005em',
    }}>
      {isFull ? '내일 자정에 가득 다시 채워져요' : '자정에 다시 채워져요'}
      {' · '}
      <b style={{ color: T.ink2, fontWeight: 600 }}>{h}시간 {m}분 남음</b>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────
// Ad flow screens (full-screen modals)
// ──────────────────────────────────────────────────────────────
function ScreenAdPre({ onContinue, onClose }) {
  const T = window.T;
  return (
    <div style={{ position: 'absolute', inset: 0, background: T.bg,
                  display: 'flex', flexDirection: 'column' }}>
      <TopBar leading={<IconButton icon={<Icons.Close size={22} color={T.ink}/>} onClick={onClose}/>}/>
      <div style={{ flex: 1, padding: '20px 24px',
                    display: 'flex', flexDirection: 'column',
                    alignItems: 'center', justifyContent: 'center', textAlign: 'center' }}>
        <div style={{
          width: 88, height: 88, borderRadius: '50%',
          background: T.accentSoft,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          marginBottom: 24,
        }}>
          <Icons.Sparkle size={44} color={T.accent}/>
        </div>
        <div style={{
          fontSize: 22, fontWeight: 700, color: T.ink,
          letterSpacing: '-0.025em', marginBottom: 14, lineHeight: 1.3,
        }}>광고를 보면<br/>볼주머니가 늘어나요</div>
        <div style={{
          fontSize: 14.5, color: T.ink2,
          lineHeight: 1.6, maxWidth: 280, marginBottom: 28,
        }}>
          허용하면 한 번에 <b style={{ color: T.accent }}>3개</b>,<br/>
          거부해도 <b style={{ color: T.accent }}>1개</b>를 받을 수 있어요
        </div>
        <div style={{
          background: T.surface, borderRadius: 14,
          border: `0.5px solid ${T.hairline}`,
          padding: '14px 18px', marginBottom: 24,
          fontSize: 12.5, color: T.ink2, lineHeight: 1.5,
          maxWidth: 320,
        }}>
          하루 <b>3번</b>까지 볼주머니를 추가할 수 있어요.<br/>
          광고는 짧고, 보상은 즉시 주어져요.
        </div>
      </div>
      <div style={{ padding: '0 20px 24px' }}>
        <Button kind="primary" fullWidth onClick={onContinue} style={{ height: 52 }}>
          계속하기
        </Button>
      </div>
    </div>
  );
}

function ScreenAdConsent({ onAccept, onDeny }) {
  const T = window.T;
  // OS-style consent dialog overlay
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 100,
      background: 'rgba(0,0,0,0.55)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 30,
      animation: 'cp-fade-bg 0.2s ease',
    }}>
      <div style={{
        background: '#F8F8F8', borderRadius: 14,
        width: '100%', maxWidth: 280,
        overflow: 'hidden', animation: 'cp-modal-in 0.25s cubic-bezier(0.32, 0.72, 0, 1)',
      }}>
        <div style={{ padding: '22px 18px 16px', textAlign: 'center' }}>
          <div style={{ fontSize: 15, fontWeight: 700, color: '#000', marginBottom: 8 }}>
            "CheekPouch"이(가) 다른 회사의 앱 및 웹사이트에서 사용자의 활동을 추적하는 것을 허용하시겠습니까?
          </div>
          <div style={{ fontSize: 12, color: '#3C3C43', lineHeight: 1.45 }}>
            맞춤형 광고 제공을 위해 사용됩니다. 허용 시 한 번에 3개의 슬롯을 받을 수 있어요.
          </div>
        </div>
        <div style={{ borderTop: '0.5px solid rgba(60,60,67,0.18)',
                      display: 'flex', flexDirection: 'column' }}>
          <button onClick={onDeny} style={{
            height: 44, background: 'transparent', border: 'none',
            borderBottom: '0.5px solid rgba(60,60,67,0.18)',
            color: '#007AFF', fontSize: 15, fontWeight: 400,
            fontFamily: 'inherit', cursor: 'pointer',
          }}>앱이 추적하지 않도록 요청</button>
          <button onClick={onAccept} style={{
            height: 44, background: 'transparent', border: 'none',
            color: '#007AFF', fontSize: 15, fontWeight: 600,
            fontFamily: 'inherit', cursor: 'pointer',
          }}>허용</button>
        </div>
      </div>
    </div>
  );
}

function ScreenAdReward({ amount = 3, allowed = true, user, newCap, onDone, onOpenSettings }) {
  const T = window.T;
  const filled = user?.todayPouch ?? 7;
  const prevCap = (newCap ?? 13) - amount;
  return (
    <div style={{ position: 'absolute', inset: 0, background: T.bg,
                  display: 'flex', flexDirection: 'column' }}>
      <TopBar/>
      <div style={{ flex: 1, padding: '20px 24px',
                    display: 'flex', flexDirection: 'column',
                    alignItems: 'center', justifyContent: 'center', textAlign: 'center' }}>
        <Hamster count={filled} max={newCap ?? prevCap + amount} size={170}/>
        <div style={{
          fontSize: 26, fontWeight: 800, color: T.ink,
          letterSpacing: '-0.03em', marginTop: 20, marginBottom: 10,
        }}>+{amount} 슬롯 추가!</div>

        {/* Before → After cap pill — makes the 7/10 → 7/13 model explicit */}
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 10,
          padding: '8px 14px', borderRadius: 999,
          background: T.surface, border: `0.5px solid ${T.hairline}`,
          marginBottom: 16,
          fontSize: 14, fontWeight: 700, letterSpacing: '-0.01em',
        }}>
          <span style={{ color: T.ink3 }}>{filled}/{prevCap}</span>
          <span style={{ color: T.ink4, fontWeight: 500 }}>→</span>
          <span style={{ color: T.accent }}>{filled}/{newCap ?? prevCap + amount}</span>
        </div>

        <div style={{
          fontSize: 14, color: T.ink2,
          lineHeight: 1.5, maxWidth: 280,
        }}>
          {allowed
            ? '볼주머니가 한층 든든해졌어요. 어떤 씨앗을 담을 거예요?'
            : '추적을 허용하면 한 번에 3개씩 받을 수 있어요'}
        </div>
        {!allowed && (
          <button onClick={onOpenSettings} style={{
            marginTop: 18,
            background: 'transparent', border: 'none',
            color: T.accent, fontSize: 14, fontWeight: 700,
            cursor: 'pointer', fontFamily: 'inherit',
            textDecoration: 'underline',
          }}>설정 열기</button>
        )}
      </div>
      <div style={{ padding: '0 20px 24px' }}>
        <Button kind="primary" fullWidth onClick={onDone} style={{ height: 52 }}>
          확인
        </Button>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenMe, ScreenAdPre, ScreenAdConsent, ScreenAdReward });
