// Heavens Shot - Components
// Shared UI primitives, character cards, effects

// ============================================================
// SVG Effect Layers
// ============================================================

const GodRays = ({ opacity = 0.55, count = 9, hue = 'gold' }) => {
  const color = hue === 'gold' ? 'rgba(255,216,122,' : 'rgba(142,220,255,';
  return (
    <svg className="godrays" viewBox="0 0 1000 1000" preserveAspectRatio="none"
      style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none', opacity, mixBlendMode: 'screen' }}>
      <defs>
        <linearGradient id="ray" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={`${color}0)`} />
          <stop offset="50%" stopColor={`${color}0.7)`} />
          <stop offset="100%" stopColor={`${color}0)`} />
        </linearGradient>
      </defs>
      {Array.from({ length: count }).map((_, i) => {
        const angle = -45 + (90 / (count - 1)) * i;
        return (
          <rect key={i} x={495} y={-200} width={10 + (i % 3) * 6} height={1400}
            fill="url(#ray)" transform={`rotate(${angle} 500 100)`} />
        );
      })}
    </svg>
  );
};

const Sparkles = ({ count = 24, size = 8, color = '#FFE8A3' }) => {
  const sparkles = React.useMemo(() =>
    Array.from({ length: count }).map((_, i) => ({
      left: Math.random() * 100,
      top: Math.random() * 100,
      delay: Math.random() * 4,
      dur: 2 + Math.random() * 3,
      scale: 0.4 + Math.random() * 0.9,
    })), [count]);
  return (
    <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', overflow: 'hidden' }}>
      {sparkles.map((s, i) => (
        <div key={i} className="sparkle" style={{
          position: 'absolute',
          left: `${s.left}%`, top: `${s.top}%`,
          width: size, height: size,
          animationDelay: `${s.delay}s`,
          animationDuration: `${s.dur}s`,
          transform: `scale(${s.scale})`,
        }}>
          <svg viewBox="0 0 20 20" width={size} height={size}>
            <path d="M10 0 L11.5 8.5 L20 10 L11.5 11.5 L10 20 L8.5 11.5 L0 10 L8.5 8.5 Z" fill={color} />
          </svg>
        </div>
      ))}
    </div>
  );
};

const FloatingClouds = () => (
  <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', overflow: 'hidden' }}>
    {[
      { top: '8%', left: '-8%', scale: 1, dur: 38, delay: 0 },
      { top: '32%', left: '-12%', scale: 0.7, dur: 52, delay: -10 },
      { top: '55%', left: '-6%', scale: 1.2, dur: 45, delay: -25 },
      { top: '78%', left: '-10%', scale: 0.9, dur: 60, delay: -5 },
    ].map((c, i) => (
      <svg key={i} className="float-cloud" viewBox="0 0 200 80" width={160 * c.scale} height={64 * c.scale}
        style={{ position: 'absolute', top: c.top, left: c.left, animationDuration: `${c.dur}s`, animationDelay: `${c.delay}s`, opacity: 0.55 }}>
        <defs>
          <linearGradient id={`cg${i}`} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#ffffff" stopOpacity="0.95" />
            <stop offset="100%" stopColor="#E7F4FF" stopOpacity="0.7" />
          </linearGradient>
        </defs>
        <path d="M30 50 Q30 30 50 30 Q55 15 75 20 Q85 8 105 15 Q125 5 135 25 Q160 25 160 45 Q175 48 172 62 Q160 72 140 68 L40 68 Q20 65 30 50 Z"
          fill={`url(#cg${i})`} stroke="#B8D8F0" strokeWidth="1.5" />
      </svg>
    ))}
  </div>
);

const Lightning = ({ variant = 'single', intensity = 1 }) => {
  // Zigzag lightning bolts
  const bolts = variant === 'single' ? [
    { x: 50, rot: 0, scale: 1 },
  ] : [
    { x: 20, rot: -15, scale: 0.7, delay: 0.3 },
    { x: 50, rot: 0, scale: 1, delay: 0 },
    { x: 80, rot: 12, scale: 0.8, delay: 0.6 },
  ];
  return (
    <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', overflow: 'hidden', opacity: intensity }}>
      {bolts.map((b, i) => (
        <svg key={i} className="lightning-bolt" viewBox="0 0 60 200" width={80 * b.scale} height={260 * b.scale}
          style={{
            position: 'absolute',
            left: `${b.x}%`, top: '0',
            transform: `translateX(-50%) rotate(${b.rot}deg)`,
            transformOrigin: 'top center',
            animationDelay: `${b.delay || 0}s`,
            filter: 'drop-shadow(0 0 20px rgba(255,229,77,0.9)) drop-shadow(0 0 40px rgba(255,180,50,0.6))',
          }}>
          <defs>
            <linearGradient id={`bolt${i}`} x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#FFF9D6" />
              <stop offset="40%" stopColor="#FFE54D" />
              <stop offset="100%" stopColor="#FFA530" />
            </linearGradient>
          </defs>
          <path d="M32 0 L18 80 L28 85 L10 200 L42 95 L30 90 L48 10 Z"
            fill={`url(#bolt${i})`} stroke="#FFF" strokeWidth="1.5" strokeLinejoin="round" />
        </svg>
      ))}
    </div>
  );
};

// ============================================================
// Counter (animated count-up)
// ============================================================
const CountUp = ({ to, duration = 1200, prefix = '', suffix = '', trigger = 0 }) => {
  const [value, setValue] = React.useState(0);
  React.useEffect(() => {
    let raf;
    const start = performance.now();
    const tick = (now) => {
      const t = Math.min(1, (now - start) / duration);
      const eased = 1 - Math.pow(1 - t, 3);
      setValue(Math.floor(to * eased));
      if (t < 1) raf = requestAnimationFrame(tick);
      else setValue(to);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [to, duration, trigger]);
  return <>{prefix}{value.toLocaleString()}{suffix}</>;
};

// ============================================================
// Character Badge - chibi character with halo glow
// ============================================================
const CharacterBadge = ({ src, size = 180, glow = 'gold', floating = true, ring = true }) => {
  const glowColor = {
    gold: 'rgba(255,216,122,0.9)',
    sky: 'rgba(142,220,255,0.9)',
    crimson: 'rgba(255,90,120,0.9)',
    violet: 'rgba(180,120,255,0.9)',
  }[glow];
  return (
    <div className={floating ? 'char-badge floating' : 'char-badge'} style={{ width: size, height: size }}>
      {ring && (
        <div className="char-ring" style={{
          position: 'absolute', inset: -4, borderRadius: '50%',
          background: `radial-gradient(circle, transparent 55%, ${glowColor} 62%, transparent 75%)`,
          filter: 'blur(4px)',
        }} />
      )}
      <div className="char-glow" style={{
        position: 'absolute', inset: '8%', borderRadius: '50%',
        background: `radial-gradient(circle, ${glowColor} 0%, transparent 65%)`,
        filter: 'blur(18px)',
        opacity: 0.75,
      }} />
      <img src={src} alt="" style={{
        position: 'relative', width: '100%', height: '100%', objectFit: 'contain',
        filter: 'drop-shadow(0 6px 12px rgba(0,0,0,0.25))',
      }} />
    </div>
  );
};

// ============================================================
// Heavenly Card - the panel chrome for steps etc.
// ============================================================
const HeavenlyCard = ({ children, style, className = '', variant = 'light' }) => {
  const bg = variant === 'light'
    ? 'linear-gradient(180deg, rgba(255,255,255,0.96) 0%, rgba(245,250,255,0.92) 100%)'
    : 'linear-gradient(180deg, rgba(20,28,70,0.9) 0%, rgba(10,14,40,0.95) 100%)';
  const border = variant === 'light' ? '#E8C661' : '#3A4684';
  return (
    <div className={`heavenly-card ${className}`} style={{
      position: 'relative',
      background: bg,
      border: `2px solid ${border}`,
      borderRadius: 22,
      boxShadow: variant === 'light'
        ? '0 8px 32px rgba(60,40,0,0.18), inset 0 0 0 1px rgba(255,255,255,0.7)'
        : '0 8px 32px rgba(0,0,0,0.5), inset 0 0 0 1px rgba(255,255,255,0.08)',
      ...style,
    }}>
      {/* gold corner ornaments */}
      <svg viewBox="0 0 40 40" width={26} height={26} style={{ position: 'absolute', top: -2, left: -2 }}>
        <path d="M2 15 L2 2 L15 2" stroke="#D4A83A" strokeWidth="3" fill="none" strokeLinecap="round"/>
        <circle cx="2" cy="2" r="3" fill="#FFD87A" stroke="#8B6B1C" strokeWidth="1"/>
      </svg>
      <svg viewBox="0 0 40 40" width={26} height={26} style={{ position: 'absolute', top: -2, right: -2, transform: 'scaleX(-1)' }}>
        <path d="M2 15 L2 2 L15 2" stroke="#D4A83A" strokeWidth="3" fill="none" strokeLinecap="round"/>
        <circle cx="2" cy="2" r="3" fill="#FFD87A" stroke="#8B6B1C" strokeWidth="1"/>
      </svg>
      <svg viewBox="0 0 40 40" width={26} height={26} style={{ position: 'absolute', bottom: -2, left: -2, transform: 'scaleY(-1)' }}>
        <path d="M2 15 L2 2 L15 2" stroke="#D4A83A" strokeWidth="3" fill="none" strokeLinecap="round"/>
        <circle cx="2" cy="2" r="3" fill="#FFD87A" stroke="#8B6B1C" strokeWidth="1"/>
      </svg>
      <svg viewBox="0 0 40 40" width={26} height={26} style={{ position: 'absolute', bottom: -2, right: -2, transform: 'scale(-1,-1)' }}>
        <path d="M2 15 L2 2 L15 2" stroke="#D4A83A" strokeWidth="3" fill="none" strokeLinecap="round"/>
        <circle cx="2" cy="2" r="3" fill="#FFD87A" stroke="#8B6B1C" strokeWidth="1"/>
      </svg>
      {children}
    </div>
  );
};

// ============================================================
// Gold Ornament Divider
// ============================================================
const GoldDivider = ({ width = 280 }) => (
  <svg viewBox="0 0 300 20" width={width} height={20} style={{ display: 'block', margin: '0 auto' }}>
    <defs>
      <linearGradient id="goldGrad" x1="0" y1="0" x2="1" y2="0">
        <stop offset="0%" stopColor="#8B6B1C" stopOpacity="0"/>
        <stop offset="50%" stopColor="#FFD87A"/>
        <stop offset="100%" stopColor="#8B6B1C" stopOpacity="0"/>
      </linearGradient>
    </defs>
    <line x1="0" y1="10" x2="300" y2="10" stroke="url(#goldGrad)" strokeWidth="2"/>
    <g transform="translate(150 10)">
      <path d="M-18 0 L0 -7 L18 0 L0 7 Z" fill="#FFD87A" stroke="#8B6B1C" strokeWidth="1"/>
      <circle cx="0" cy="0" r="3" fill="#FFF7DC" stroke="#8B6B1C" strokeWidth="0.5"/>
    </g>
  </svg>
);

// ============================================================
// Slot Reel - mini animated slot machine (noble style)
// ============================================================
const SlotReel = ({ running = false, size = 80 }) => {
  const [symbols, setSymbols] = React.useState(['VII', 'VII', 'VII']);
  React.useEffect(() => {
    if (!running) return;
    const opts = ['VII', 'III', 'I', 'V', 'X'];
    const id = setInterval(() => {
      setSymbols([
        opts[Math.floor(Math.random() * opts.length)],
        opts[Math.floor(Math.random() * opts.length)],
        opts[Math.floor(Math.random() * opts.length)],
      ]);
    }, 120);
    setTimeout(() => {
      clearInterval(id);
      setSymbols(['VII', 'VII', 'VII']);
    }, 1800);
    return () => clearInterval(id);
  }, [running]);
  return (
    <div style={{
      display: 'inline-flex', gap: 6, padding: '10px 14px',
      background: 'linear-gradient(180deg, #0A1338 0%, #050714 100%)',
      border: '1px solid #D9B356',
      boxShadow: '0 0 0 2px rgba(240,217,140,0.15), inset 0 2px 12px rgba(0,0,0,0.8), 0 6px 20px rgba(10,14,40,0.5)',
    }}>
      {symbols.map((s, i) => (
        <div key={i} style={{
          width: size * 0.48, height: size * 0.62,
          background: 'linear-gradient(180deg, #FAF4E4 0%, #F0D98C 100%)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontWeight: 600, fontSize: size * 0.28,
          fontFamily: '"Cormorant Garamond", "Shippori Mincho", serif',
          fontStyle: 'italic',
          background: 'linear-gradient(180deg, #FAF4E4 0%, #F0D98C 60%, #B8892A 100%)',
          WebkitBackgroundClip: 'text',
          backgroundClip: 'text',
          color: 'transparent',
          border: '1px solid rgba(240,217,140,0.3)',
          position: 'relative',
        }}>
          <div style={{
            position: 'absolute', inset: 0,
            background: 'linear-gradient(180deg, rgba(250,244,228,0.08) 0%, rgba(10,14,40,0.4) 100%)',
            pointerEvents: 'none',
          }} />
          <span style={{ position: 'relative', zIndex: 1 }}>{s}</span>
        </div>
      ))}
    </div>
  );
};

// ============================================================
// Coin
// ============================================================
const Coin = ({ size = 24, style = {} }) => (
  <svg viewBox="0 0 40 40" width={size} height={size} style={style}>
    <defs>
      <radialGradient id="coinG" cx="0.35" cy="0.35">
        <stop offset="0%" stopColor="#FFF5C6"/>
        <stop offset="55%" stopColor="#FFD15A"/>
        <stop offset="100%" stopColor="#B57B12"/>
      </radialGradient>
    </defs>
    <circle cx="20" cy="20" r="18" fill="url(#coinG)" stroke="#8B5E0D" strokeWidth="1.5"/>
    <circle cx="20" cy="20" r="13" fill="none" stroke="#8B5E0D" strokeWidth="1" opacity="0.5"/>
    <text x="20" y="27" textAnchor="middle" fontSize="18" fontWeight="900" fill="#8B5E0D" fontFamily="serif">¥</text>
  </svg>
);

// Export to window
Object.assign(window, {
  GodRays, Sparkles, FloatingClouds, Lightning,
  CountUp, CharacterBadge, HeavenlyCard, GoldDivider, SlotReel, Coin,
});
