// extras.jsx — onboarding, modals, level-up, loading skeleton, empty state

// ──────────────────────────────────────────────────────────────
// BADGE MODAL with confetti
// ──────────────────────────────────────────────────────────────
function BadgeModal({ badge, onClose }) {
  React.useEffect(() => {
    if (typeof confetti !== 'function') return;
    const colors = ({
      common:     ['#94A3B8', '#CBD5E1', '#E2E8F0'],
      uncommon:   ['#34D399', '#6EE7B7', '#A7F3D0'],
      rare:       ['#60A5FA', '#93C5FD', '#A78BFA'],
      epic:       ['#A78BFA', '#C4B5FD', '#F472B6'],
      legendary:  ['#F59E0B', '#FCD34D', '#FBBF24'],
    })[badge.rarity] || ['#FBBF24'];
    confetti({
      particleCount: 160,
      spread: 90,
      startVelocity: 38,
      colors,
      origin: { y: 0.4 },
      ticks: 250,
    });
    confetti({ particleCount: 60, angle: 60,  spread: 55, origin: { x: 0, y: 0.6 }, colors });
    confetti({ particleCount: 60, angle: 120, spread: 55, origin: { x: 1, y: 0.6 }, colors });
  }, [badge]);
  return (
    <div className="modal-back" onClick={onClose}>
      <div className={`modal-card rarity-${badge.rarity}`} onClick={(e) => e.stopPropagation()}>
        <div className="eyebrow" style={{ color: 'var(--gold-2)' }}>Получен бейдж</div>
        <div className="big-badge mt-3">{badge.icon}</div>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 22, letterSpacing: '-0.01em' }}>{badge.name}</div>
        <div className="dim mt-2" style={{ fontSize: 13 }}>{badge.desc}</div>
        <div className="row mt-4" style={{ gap: 10, justifyContent: 'center' }}>
          <span className={`chip rarity-${badge.rarity}`} style={{
            background: 'transparent', color: 'var(--rar-1)', borderColor: 'var(--rar-1)',
            textTransform: 'uppercase', letterSpacing: '0.06em', fontSize: 10,
          }}>{badge.rarity}</span>
          <span className="mono" style={{ background: 'rgba(245,166,35,0.15)', color: 'var(--gold-2)', padding: '3px 9px', borderRadius: 9999, fontSize: 12, fontWeight: 700 }}>
            +250 XP
          </span>
        </div>
        <button className="btn primary mt-4" style={{ width: '100%', justifyContent: 'center' }} onClick={onClose}>Закрепить в профиле</button>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────
// LEVEL-UP FLASH
// ──────────────────────────────────────────────────────────────
function LevelUpFlash({ from, to, onClose }) {
  React.useEffect(() => {
    if (typeof confetti === 'function') {
      confetti({ particleCount: 220, spread: 120, colors: ['#6C3FE8','#A78BFA','#F5A623','#FBBF24'], origin: { y: 0.4 } });
    }
    const t = setTimeout(onClose, 3200);
    return () => clearTimeout(t);
  }, []);
  return (
    <div className="modal-back" style={{ background: 'rgba(0,0,0,0.7)' }} onClick={onClose}>
      <div style={{
        textAlign: 'center', color: '#fff',
        animation: 'badge-pop 600ms cubic-bezier(0.34, 1.56, 0.64, 1)',
      }}>
        <div style={{
          fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--gold-2)',
          letterSpacing: '0.16em', textTransform: 'uppercase', fontWeight: 600,
        }}>LEVEL UP</div>
        <div style={{
          fontFamily: 'var(--font-display)', fontWeight: 800,
          fontSize: 92, letterSpacing: '-0.04em', lineHeight: 1,
          background: 'linear-gradient(135deg, #FBBF24, #F472B6, #6C3FE8)',
          WebkitBackgroundClip: 'text', backgroundClip: 'text', color: 'transparent',
          margin: '10px 0',
          filter: 'drop-shadow(0 0 40px rgba(108, 63, 232, 0.6))',
        }}>
          LVL {to}
        </div>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 700 }}>
          {PROGRESSION.names[to]}
        </div>
        <div className="dim2 mt-3" style={{ maxWidth: 340, margin: '0 auto', fontSize: 13 }}>
          Открыто: командная аналитика, целевое колесо с историей, тёмная тема.
        </div>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────
// ONBOARDING (5 steps in a small "demo card")
// ──────────────────────────────────────────────────────────────
function OnboardingDemo({ onClose }) {
  const [step, setStep] = React.useState(0);
  const [zones, setZones] = React.useState(['health', 'family', 'growth']);
  const [wishZone, setWishZone] = React.useState('health');
  const [wishTitle, setWishTitle] = React.useState('Пробежать первую десятку');
  const next = () => {
    if (step < 4) setStep(step + 1);
    else { if (typeof confetti === 'function') confetti({ particleCount: 220, spread: 130, colors: ['#6C3FE8','#FBBF24','#F472B6','#34D399'] }); onClose(); }
  };

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal-card" onClick={(e) => e.stopPropagation()}
           style={{ width: 460, padding: 0, overflow: 'hidden', animation: 'fade-in 240ms' }}>
        {/* Progress */}
        <div style={{ height: 4, background: 'var(--border)' }}>
          <div style={{ width: `${((step + 1) / 5) * 100}%`, height: '100%',
                        background: 'linear-gradient(90deg, var(--accent), var(--accent-2))', transition: 'width 240ms' }} />
        </div>
        <div style={{ padding: 28 }}>
          <div className="eyebrow" style={{ textAlign: 'left' }}>Онбординг · шаг {step + 1} из 5</div>

          {step === 0 && (
            <>
              <div className="ttl-xl mt-2" style={{ textAlign: 'left' }}>Привет 👋</div>
              <p className="dim2 mt-3" style={{ fontSize: 14, textAlign: 'left' }}>
                Карта желаний — это инструмент для семьи или команды.
                Создавайте цели, отмечайте привычки, отслеживайте баланс жизни вместе.
              </p>
              <div className="row mt-4" style={{ gap: 8, textAlign: 'left' }}>
                <input className="topbar search" style={{ flex: 1, padding: '10px 14px', background: 'var(--bg-elev)', color: 'var(--text-primary)', border: '1px solid var(--border)' }}
                       defaultValue="Аня Соколова" />
              </div>
            </>
          )}

          {step === 1 && (
            <>
              <div className="ttl-xl mt-2" style={{ textAlign: 'left' }}>Аватар</div>
              <p className="dim2 mt-3" style={{ fontSize: 14, textAlign: 'left' }}>
                Можно выбрать из готовых градиентов или загрузить фото.
              </p>
              <div className="row mt-4" style={{ gap: 10, flexWrap: 'wrap', justifyContent: 'center' }}>
                {USERS.map((u, i) => (
                  <div key={u.id} style={{
                    padding: 3, borderRadius: '50%',
                    border: i === 0 ? '2px solid var(--accent)' : '2px solid transparent',
                  }}>
                    <Avatar user={u} size="xl" />
                  </div>
                ))}
              </div>
            </>
          )}

          {step === 2 && (
            <>
              <div className="ttl-xl mt-2" style={{ textAlign: 'left' }}>Зоны жизни</div>
              <p className="dim2 mt-3" style={{ fontSize: 14, textAlign: 'left' }}>
                С каких зон хочется начать? Можно выбрать любые, потом изменить.
              </p>
              <div className="mt-4" style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
                {ZONES.map(z => {
                  const on = zones.includes(z.id);
                  return (
                    <div key={z.id}
                      onClick={() => setZones(on ? zones.filter(x => x !== z.id) : [...zones, z.id])}
                      style={{
                        padding: 10,
                        borderRadius: 'var(--r-md)',
                        border: '1px solid ' + (on ? z.color : 'var(--border)'),
                        background: on ? `color-mix(in oklab, ${z.color} 12%, var(--bg-card))` : 'var(--bg-card)',
                        cursor: 'pointer',
                        display: 'flex', alignItems: 'center', gap: 10,
                        boxShadow: on ? `0 0 calc(12px * var(--glow-mult)) color-mix(in oklab, ${z.color} 30%, transparent)` : 'none',
                      }}>
                      <span style={{ fontSize: 16 }}>{z.icon}</span>
                      <span style={{ fontWeight: 500, fontSize: 13, flex: 1 }}>{z.name}</span>
                      <div style={{ width: 18, height: 18, '--zc': z.color }} className={`check-btn ${on ? 'done' : ''}`}>
                        {on && <Icon.check />}
                      </div>
                    </div>
                  );
                })}
              </div>
            </>
          )}

          {step === 3 && (
            <>
              <div className="ttl-xl mt-2" style={{ textAlign: 'left' }}>Первое желание</div>
              <p className="dim2 mt-3" style={{ fontSize: 14, textAlign: 'left' }}>
                Чтобы система ожила, добавь одно желание. Можно потом изменить.
              </p>
              <div className="col mt-4" style={{ gap: 10 }}>
                <div className="eyebrow" style={{ textAlign: 'left' }}>Зона</div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {ZONES.filter(z => zones.includes(z.id)).map(z => (
                    <button key={z.id} onClick={() => setWishZone(z.id)}
                      className={`chip ${z.cls}`}
                      style={{ background: wishZone === z.id ? z.color : undefined, color: wishZone === z.id ? '#fff' : undefined }}>
                      {z.icon} {z.name}
                    </button>
                  ))}
                </div>
                <div className="eyebrow mt-2" style={{ textAlign: 'left' }}>Название</div>
                <input value={wishTitle} onChange={(e) => setWishTitle(e.target.value)}
                       style={{
                         padding: '10px 12px', borderRadius: 'var(--r-md)',
                         background: 'var(--bg-elev)', border: '1px solid var(--border)',
                         color: 'var(--text-primary)', fontSize: 14, fontFamily: 'var(--font-body)',
                       }}/>
              </div>
            </>
          )}

          {step === 4 && (
            <>
              <div className="ttl-xl mt-2" style={{ textAlign: 'left' }}>Пригласи свою группу</div>
              <p className="dim2 mt-3" style={{ fontSize: 14, textAlign: 'left' }}>
                До 10 человек. Семья, команда или друзья. Каждый видит общие цели и активность.
              </p>
              <div className="card mt-4" style={{ background: 'var(--bg-elev)', padding: 14 }}>
                <div className="eyebrow" style={{ textAlign: 'left' }}>Ваш инвайт-код</div>
                <div className="mono mt-2" style={{ fontSize: 22, fontWeight: 700, letterSpacing: '0.06em', color: 'var(--accent-2)' }}>
                  SOKOLOVY-12
                </div>
                <div className="dim mono mt-2" style={{ fontSize: 11, textAlign: 'left' }}>app.wishmap.local/invite/SOKOLOVY-12</div>
              </div>
              <div className="row mt-3" style={{ gap: 8 }}>
                <button className="btn" style={{ flex: 1, justifyContent: 'center' }}>📋 Копировать</button>
                <button className="btn" style={{ flex: 1, justifyContent: 'center' }}>✉️ Email</button>
              </div>
            </>
          )}

          <div className="row mt-4" style={{ gap: 8 }}>
            {step > 0 && <button className="btn" onClick={() => setStep(step - 1)}>Назад</button>}
            <div style={{ flex: 1 }}></div>
            <button className="btn ghost" onClick={onClose}>Пропустить</button>
            <button className="btn primary" onClick={next}>
              {step < 4 ? 'Дальше →' : '🎉 Готово!'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────
// EMPTY / SKELETON examples
// ──────────────────────────────────────────────────────────────
function EmptyState({ icon = '🌱', title = 'Здесь пока пусто', desc = 'Добавь первое желание, чтобы команда увидела его в дашборде.', cta = 'Новое желание' }) {
  return (
    <div className="card">
      <div className="empty">
        <div className="icon">{icon}</div>
        <h3>{title}</h3>
        <p>{desc}</p>
        <button className="btn primary"><Icon.plus /> {cta}</button>
      </div>
    </div>
  );
}

function LoadingSkeleton() {
  return (
    <div className="col" style={{ gap: 10 }}>
      <div className="skel" style={{ height: 24, width: '40%' }}></div>
      <div className="skel" style={{ height: 12, width: '60%' }}></div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginTop: 12 }}>
        {[0,1,2,3].map(i => <div key={i} className="skel" style={{ height: 130 }}></div>)}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 8 }}>
        {[0,1,2,3,4,5].map(i => <div key={i} className="skel" style={{ height: 86 }}></div>)}
      </div>
    </div>
  );
}

// Floating +XP — positioned absolutely in viewport-relative coords
function XPFloater({ x, y, xp = 1 }) {
  return <div className="xp-float" style={{ left: x, top: y }}>+{xp} XP</div>;
}

// Toast stack
function ToastStack({ toasts }) {
  return (
    <div className="toast-stack">
      {toasts.map(t => <Toast key={t.id} icon={t.icon} title={t.title} sub={t.sub} xp={t.xp} />)}
    </div>
  );
}

Object.assign(window, {
  BadgeModal, LevelUpFlash, OnboardingDemo,
  EmptyState, LoadingSkeleton, XPFloater, ToastStack,
});
