// Дополнительные интерактивы: кастомный курсор, magnetic-кнопка, hover-карточка с tilt,
// бегущая строка-маркер, число-счётчик при появлении.

// Кастомный курсор — два кольца, ловят hover на интерактивных элементах
function CustomCursor() {
  const dot = React.useRef(); const ring = React.useRef();
  const [hover, setHover] = React.useState(false);
  const [label, setLabel] = React.useState('');
  React.useEffect(() => {
    let x=0,y=0,rx=0,ry=0,raf;
    const onMove = (e) => {
      x = e.clientX; y = e.clientY;
      const t = e.target.closest('[data-cursor]');
      setHover(!!t);
      setLabel(t ? (t.getAttribute('data-cursor') || '') : '');
    };
    const tick = () => {
      rx += (x - rx) * 0.18; ry += (y - ry) * 0.18;
      if (dot.current) dot.current.style.transform = `translate(${x-3}px,${y-3}px)`;
      if (ring.current) ring.current.style.transform = `translate(${rx-18}px,${ry-18}px) scale(${hover?1.6:1})`;
      raf = requestAnimationFrame(tick);
    };
    window.addEventListener('mousemove', onMove);
    raf = requestAnimationFrame(tick);
    return () => { window.removeEventListener('mousemove', onMove); cancelAnimationFrame(raf); };
  }, [hover]);
  return (
    <>
      <div ref={dot} style={{ position:'fixed', top:0, left:0, width:6, height:6,
        background:'var(--accent)', borderRadius:'50%', zIndex:9999, pointerEvents:'none' }}/>
      <div ref={ring} style={{ position:'fixed', top:0, left:0, width:36, height:36,
        border:'1.5px solid var(--ink)', borderRadius:'50%', zIndex:9998, pointerEvents:'none',
        transition:'width .2s, height .2s, background .2s',
        background: hover ? 'var(--accent)' : 'transparent',
        mixBlendMode: hover ? 'normal' : 'difference', opacity:0.9 }}>
        {hover && label && (
          <div style={{ position:'absolute', top:'100%', left:'50%', transform:'translate(-50%, 8px)',
            fontFamily:'JetBrains Mono,monospace', fontSize:9, fontWeight:700, letterSpacing:'0.3em',
            textTransform:'uppercase', color:'var(--bg)', background:'var(--ink)', padding:'4px 8px',
            whiteSpace:'nowrap' }}>{label}</div>
        )}
      </div>
    </>
  );
}

// Магнитная кнопка — притягивается к курсору
function MagnetBtn({ children, onClick, style }) {
  const ref = React.useRef();
  const onMove = (e) => {
    const r = ref.current.getBoundingClientRect();
    const x = e.clientX - (r.left + r.width/2);
    const y = e.clientY - (r.top + r.height/2);
    ref.current.style.transform = `translate(${x*0.25}px, ${y*0.4}px)`;
  };
  const onLeave = () => { ref.current.style.transform = 'translate(0,0)'; };
  return (
    <button ref={ref} onClick={onClick}
      onMouseMove={onMove} onMouseLeave={onLeave}
      data-cursor="нажми"
      style={{ display:'inline-flex', alignItems:'center', gap:10, padding:'18px 28px',
        background:'var(--ink)', color:'var(--bg)', border:'none',
        fontFamily:'JetBrains Mono,monospace', fontWeight:700, fontSize:12,
        letterSpacing:'0.25em', textTransform:'uppercase', cursor:'pointer',
        transition:'transform .25s cubic-bezier(.2,1,.3,1), background .2s',
        ...style }}>
      {children}
    </button>
  );
}

// Tilt-карточка
function TiltCard({ children, style, label }) {
  const ref = React.useRef();
  const onMove = (e) => {
    const r = ref.current.getBoundingClientRect();
    const x = (e.clientX - r.left)/r.width - 0.5;
    const y = (e.clientY - r.top)/r.height - 0.5;
    ref.current.style.transform = `perspective(900px) rotateY(${x*8}deg) rotateX(${-y*8}deg) translateY(-4px)`;
  };
  const onLeave = () => { ref.current.style.transform = 'perspective(900px) rotateY(0) rotateX(0) translateY(0)'; };
  return (
    <div ref={ref} onMouseMove={onMove} onMouseLeave={onLeave}
      data-cursor={label||'смотреть'}
      style={{ transition:'transform .3s cubic-bezier(.2,1,.3,1)', transformStyle:'preserve-3d',
        willChange:'transform', ...style }}>
      {children}
    </div>
  );
}

// Бегущая строка
function Marquee({ items, speed = 60 }) {
  const arr = [...items, ...items, ...items];
  return (
    <div style={{ overflow:'hidden', whiteSpace:'nowrap', borderTop:'2px solid var(--ink)',
      borderBottom:'2px solid var(--ink)', background:'var(--accent)', color:'var(--ink)' }}>
      <div style={{ display:'inline-flex', gap:32, padding:'14px 0',
        animation:`marq ${speed}s linear infinite` }}>
        {arr.map((it,i) => (
          <span key={i} style={{ fontFamily:'JetBrains Mono,monospace', fontWeight:700, fontSize:13,
            letterSpacing:'0.3em', textTransform:'uppercase', display:'inline-flex', gap:32, alignItems:'center' }}>
            {it}<span style={{ opacity:0.5 }}>✦</span>
          </span>
        ))}
      </div>
      <style>{`@keyframes marq{from{transform:translateX(0)}to{transform:translateX(-33.33%)}}`}</style>
    </div>
  );
}

// Счётчик-число (анимируется при появлении)
function CountUp({ to, suffix='', dur=1400 }) {
  const [v, setV] = React.useState(0);
  const ref = React.useRef(); const started = React.useRef(false);
  React.useEffect(() => {
    const io = new IntersectionObserver((es) => {
      es.forEach(e => {
        if (e.isIntersecting && !started.current) {
          started.current = true;
          const t0 = performance.now();
          const tick = () => {
            const p = Math.min(1, (performance.now()-t0)/dur);
            const eased = 1 - Math.pow(1-p, 3);
            setV(Math.round(to * eased));
            if (p < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.5 });
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, [to, dur]);
  return <span ref={ref}>{v}{suffix}</span>;
}

// Hover-выделение строки услуг (раскрытие справа описания)
function ServiceRow({ n, title, desc, price }) {
  const [open, setOpen] = React.useState(false);
  return (
    <div onMouseEnter={()=>setOpen(true)} onMouseLeave={()=>setOpen(false)}
      data-cursor="узнать"
      style={{ display:'grid', gridTemplateColumns:'70px 1fr auto', alignItems:'center',
        padding:'24px 4px', borderTop:'1.5px solid var(--ink)', cursor:'pointer',
        background: open ? 'var(--accent)' : 'transparent',
        color: open ? 'var(--bg)' : 'var(--ink)',
        transition:'background .25s, color .25s, padding .25s',
        paddingLeft: open ? 24 : 4 }}>
      <div style={{ fontFamily:'JetBrains Mono,monospace', fontSize:11, fontWeight:700, letterSpacing:'0.2em' }}>
        № 0{n}
      </div>
      <div>
        <div style={{ fontWeight:900, fontSize:34, letterSpacing:'-0.04em', textTransform:'uppercase',
          lineHeight:1 }}>{title}</div>
        <div style={{ marginTop: open ? 8 : 0, maxHeight: open ? 60 : 0, overflow:'hidden',
          transition:'max-height .35s, margin-top .25s', fontSize:14, opacity:0.9 }}>
          {desc}
        </div>
      </div>
      <div style={{ display:'flex', gap:18, alignItems:'center' }}>
        <div style={{ fontFamily:'JetBrains Mono,monospace', fontSize:13, fontWeight:700, letterSpacing:'0.1em' }}>{price}</div>
        <div style={{ width:46, height:46, border:`2px solid ${open ? 'var(--bg)' : 'var(--ink)'}`,
          borderRadius:'50%', display:'flex', alignItems:'center', justifyContent:'center',
          transform: open ? 'rotate(45deg)' : 'rotate(0)', transition:'transform .3s' }}>+</div>
      </div>
    </div>
  );
}

Object.assign(window, { CustomCursor, MagnetBtn, TiltCard, Marquee, CountUp, ServiceRow });
