// Micro-interactions demo · 8 touchpoints used across the app
// All CSS-driven (no Lottie file dependency) — Lottie-grade polish via
// keyframes, particle bursts, and stagger reveals.

const { useState: muState, useEffect: muEffect, useRef: muRef } = React;

// ---------- 1. Pulse Glow Button (CTA) ----------
function PulseGlowDemo() {
  return (
    <button className="mi-cta">
      <span>시작하기</span>
      <span className="mi-cta-shine" />
    </button>
  );
}

// ---------- 2. Bounce + Sparkle on Click (캐릭터) ----------
function BounceSparkleDemo() {
  const [bouncing, setBouncing] = muState(false);
  const handleClick = () => {
    setBouncing(false);
    requestAnimationFrame(() => setBouncing(true));
    setTimeout(() => setBouncing(false), 1200);
  };
  return (
    <button className="mi-char" onClick={handleClick}>
      <div className={`mi-char-wrap ${bouncing ? 'bouncing' : ''}`}>
        <img src={window.__res("assets/avatar-1.png")} alt="" />
        {bouncing && (
          <>
            <span className="mi-spark" style={{ '--a': '-30deg', '--d': '60px' }}>✨</span>
            <span className="mi-spark" style={{ '--a': '30deg', '--d': '70px' }}>⭐</span>
            <span className="mi-spark" style={{ '--a': '-60deg', '--d': '50px' }}>✨</span>
            <span className="mi-spark" style={{ '--a': '90deg', '--d': '55px' }}>💫</span>
          </>
        )}
      </div>
    </button>
  );
}

// ---------- 3. Stagger Card Reveal ----------
function StaggerRevealDemo() {
  const [key, setKey] = muState(0);
  return (
    <div className="mi-stagger-wrap">
      <div key={key} className="mi-stagger">
        {['아브라함', '다윗', '모세'].map((name, i) => (
          <div key={i} className="mi-stagger-card" style={{ animationDelay: `${i * 0.12}s` }}>
            <div className="mi-stagger-dot" />
            <div>{name}</div>
          </div>
        ))}
      </div>
      <button className="mi-replay" onClick={() => setKey(k => k + 1)}>다시 보기 ↻</button>
    </div>
  );
}

// ---------- 4. Heart Burst (좋아요) ----------
function HeartBurstDemo() {
  const [liked, setLiked] = muState(false);
  const [bursting, setBursting] = muState(false);
  const handleClick = () => {
    setLiked(v => !v);
    if (!liked) {
      setBursting(true);
      setTimeout(() => setBursting(false), 700);
    }
  };
  return (
    <button className={`mi-heart ${liked ? 'liked' : ''} ${bursting ? 'bursting' : ''}`} onClick={handleClick}>
      <span className="mi-heart-icon">{liked ? '♥' : '♡'}</span>
      <span className="mi-heart-count">{liked ? 25 : 24}</span>
      {bursting && (
        <>
          <span className="mi-mini-heart" style={{ '--a': '-30deg' }}>♥</span>
          <span className="mi-mini-heart" style={{ '--a': '0deg' }}>♥</span>
          <span className="mi-mini-heart" style={{ '--a': '30deg' }}>♥</span>
          <span className="mi-mini-heart" style={{ '--a': '60deg' }}>♥</span>
          <span className="mi-mini-heart" style={{ '--a': '-60deg' }}>♥</span>
        </>
      )}
    </button>
  );
}

// ---------- 5. Stamp Press (마음 도장) ----------
function StampPressDemo() {
  const [stamped, setStamped] = muState([true, true, true, false, false, false, false]);
  const handleClick = (i) => {
    if (stamped[i]) return;
    setStamped(prev => prev.map((v, idx) => idx === i ? true : v));
  };
  return (
    <div className="mi-stamps">
      {['월','화','수','목','금','토','일'].map((d, i) => (
        <button
          key={i}
          className={`mi-stamp ${stamped[i] ? 'on' : ''}`}
          onClick={() => handleClick(i)}
        >
          {stamped[i] ? '✓' : d}
        </button>
      ))}
    </div>
  );
}

// ---------- 6. XP Fill with Glow ----------
function XpFillDemo() {
  const [xp, setXp] = muState(40);
  return (
    <div className="mi-xp-wrap">
      <div className="mi-xp-bar">
        <div className="mi-xp-fill" style={{ width: `${xp}%` }} />
        <div className="mi-xp-shine" style={{ left: `${xp}%` }} />
      </div>
      <div className="mi-xp-text">{xp} / 100 XP</div>
      <div className="mi-xp-actions">
        <button onClick={() => setXp(v => Math.max(0, v - 20))}>−20</button>
        <button onClick={() => setXp(v => Math.min(100, v + 20))}>+20 XP</button>
      </div>
    </div>
  );
}

// ---------- 7. Confetti Burst (레벨업) ----------
function ConfettiBurstDemo() {
  const [bursting, setBursting] = muState(false);
  const handleClick = () => {
    setBursting(false);
    requestAnimationFrame(() => setBursting(true));
    setTimeout(() => setBursting(false), 1500);
  };
  return (
    <button className={`mi-confetti-btn ${bursting ? 'bursting' : ''}`} onClick={handleClick}>
      <span className="mi-conf-label">레벨업 🎉</span>
      {bursting && (
        <span className="mi-conf-particles">
          {Array.from({ length: 14 }).map((_, i) => (
            <span
              key={i}
              className="mi-conf-piece"
              style={{
                '--a': `${(i * 360 / 14)}deg`,
                '--d': `${60 + (i % 3) * 20}px`,
                '--c': ['#FFE08A', '#58CC02', '#2EA8F0', '#E0517E'][i % 4],
                '--delay': `${(i % 5) * 0.03}s`,
              }}
            />
          ))}
        </span>
      )}
    </button>
  );
}

// ---------- 8. Typewriter Reveal (멘토 첫 인사) ----------
function TypewriterDemo() {
  const text = '안녕하세요. 저는 아브라함입니다.';
  const [shown, setShown] = muState(0);
  const [done, setDone] = muState(false);

  muEffect(() => {
    if (shown >= text.length) { setDone(true); return; }
    const t = setTimeout(() => setShown(s => s + 1), 60);
    return () => clearTimeout(t);
  }, [shown]);

  const replay = () => { setShown(0); setDone(false); };

  return (
    <div className="mi-type-wrap">
      <div className="mi-type-bubble">
        <span>{text.slice(0, shown)}</span>
        {!done && <span className="mi-type-cursor">|</span>}
      </div>
      <button className="mi-replay" onClick={replay}>다시 보기 ↻</button>
    </div>
  );
}

// ---------- Card wrapper ----------
function MiCard({ num, title, where, children }) {
  return (
    <div className="mi-card">
      <div className="mi-card-head">
        <span className="mi-num">{num}</span>
        <div className="mi-card-titles">
          <div className="mi-title">{title}</div>
          <div className="mi-where">{where}</div>
        </div>
      </div>
      <div className="mi-stage">{children}</div>
    </div>
  );
}

// ---------- Screen ----------
function MicroInteractionsScreen({ onBack }) {
  return (
    <>
      <div className="welcome-mockup-bg" style={{ background: '#0D1632' }} />
      <div className="welcome-shell mi-screen">
        <div className="home-night-topbar">
          <button className="hnt-icon" aria-label="Back" onClick={onBack}><Icon name="chev-left" /></button>
          <div className="hnt-brand"><span>마이크로 인터랙션</span></div>
          <div style={{ width: 34 }} />
        </div>

        <div className="mi-intro">
          <div className="mi-eyebrow">감각적 터치포인트 7가지</div>
          <div className="mi-h1">눌러보시거나<br/>호버해보세요</div>
          <div className="mi-sub">Lottie 없이 CSS·JS로 구현. 각 인터랙션이 어디에 쓰일지 표시했습니다.</div>
        </div>

        <div className="mi-grid">
          <MiCard num="1" title="펄스 글로우 CTA" where="시작하기 · 게시 · 응원 보내기">
            <PulseGlowDemo />
          </MiCard>

          <MiCard num="2" title="스태거 카드 등장" where="멘토 리스트 · 피드 진입">
            <StaggerRevealDemo />
          </MiCard>

          <MiCard num="3" title="하트 버스트" where="좋아요 · 응원 보내기">
            <HeartBurstDemo />
          </MiCard>

          <MiCard num="4" title="마음 도장 찍기" where="출석 도장 · 격려 카드">
            <StampPressDemo />
          </MiCard>

          <MiCard num="5" title="XP 게이지 글로우" where="홈 · 진행도 갱신 순간">
            <XpFillDemo />
          </MiCard>

          <MiCard num="6" title="컨페티 폭발" where="레벨업 · 마일스톤 달성">
            <ConfettiBurstDemo />
          </MiCard>

          <MiCard num="7" title="타이프라이터" where="멘토 첫 인사 · 말씀 등장">
            <TypewriterDemo />
          </MiCard>
        </div>

        <div className="mi-foot">
          <strong>이 데모는 코드 그대로</strong> 실제 화면 어디에든 붙일 수 있습니다.<br/>
          더 정교한 모션이 필요할 땐 Lottie/Rive 파일을 받아 같은 자리에 교체합니다.
        </div>
      </div>
    </>
  );
}

window.MicroInteractionsScreen = MicroInteractionsScreen;
