/* SUPERMEDIA storefront — B2B "Pravna lica" banner with a brutal scroll-driven
 * canvas scene: a rotating ringed planet, a staircase of pillars, and a ball
 * that climbs them leaving a glowing comet trail. All scrubbed by scroll. */
const { useRef: useRefB2B, useEffect: useEffectB2B } = React;

function B2BPlanetBanner({ onNav }) {
  const wrapRef = useRefB2B(null);
  const sceneRef = useRefB2B(null);
  const canvasRef = useRefB2B(null);
  const progRef = useRefB2B(0);
  const smoothRef = useRefB2B(0);

  useEffectB2B(() => {
    const canvas = canvasRef.current, scene = sceneRef.current, wrap = wrapRef.current;
    if (!canvas || !scene || !wrap) return;
    const ctx = canvas.getContext('2d');
    const TAU = Math.PI * 2;
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    let raf, W = 0, H = 0, dpr = 1, stars = [];

    const lerp = (a, b, t) => a + (b - a) * t;
    const clamp = (v, a, b) => Math.max(a, Math.min(b, v));

    function resize() {
      dpr = Math.min(2, window.devicePixelRatio || 1);
      W = scene.clientWidth; H = scene.clientHeight;
      canvas.width = Math.round(W * dpr); canvas.height = Math.round(H * dpr);
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      stars = Array.from({ length: Math.round(W * 0.10) }, () => ({
        x: Math.random() * W, y: Math.random() * H, r: Math.random() * 1.5 + 0.3,
        p: Math.random() * TAU, s: Math.random() * 0.7 + 0.25, dx: Math.random() * 0.3 + 0.05,
      }));
    }
    resize();
    window.addEventListener('resize', resize);

    function updateProgress() {
      const r = wrap.getBoundingClientRect();
      const vh = window.innerHeight || 800;
      progRef.current = clamp((vh - r.top) / (vh + r.height), 0, 1);
    }
    updateProgress();
    window.addEventListener('scroll', updateProgress, { passive: true });

    function roundRect(c, x, y, w, h, r) {
      r = Math.min(r, w / 2, h / 2);
      c.beginPath();
      c.moveTo(x + r, y); c.arcTo(x + w, y, x + w, y + h, r); c.arcTo(x + w, y + h, x, y + h, r);
      c.arcTo(x, y + h, x, y, r); c.arcTo(x, y, x + w, y, r); c.closePath();
    }

    function drawRing(cx, cy, r, tilt, front) {
      ctx.save();
      ctx.translate(cx, cy); ctx.rotate(tilt); ctx.scale(1, 0.34);
      ctx.lineCap = 'round';
      const arcs = [[1.42, 0.13, 'rgba(196,156,236,0.7)'], [1.62, 0.06, 'rgba(150,110,205,0.45)'], [1.28, 0.05, 'rgba(220,190,250,0.5)']];
      arcs.forEach(([rad, w, col]) => {
        ctx.lineWidth = r * w; ctx.strokeStyle = col;
        ctx.beginPath();
        if (front) ctx.arc(0, 0, r * rad, 0.04, Math.PI - 0.04);
        else ctx.arc(0, 0, r * rad, Math.PI + 0.04, TAU - 0.04);
        ctx.stroke();
      });
      ctx.restore();
    }

    function drawPlanet(cx, cy, r, rot, t) {
      // outer atmosphere glow
      let gl = ctx.createRadialGradient(cx, cy, r * 0.55, cx, cy, r * 1.8);
      gl.addColorStop(0, 'rgba(150,86,212,0.5)'); gl.addColorStop(0.5, 'rgba(120,70,190,0.18)'); gl.addColorStop(1, 'rgba(120,70,190,0)');
      ctx.fillStyle = gl; ctx.beginPath(); ctx.arc(cx, cy, r * 1.8, 0, TAU); ctx.fill();

      drawRing(cx, cy, r, -0.46, false); // back of ring

      // sphere body with rotating banded surface
      ctx.save();
      ctx.beginPath(); ctx.arc(cx, cy, r, 0, TAU); ctx.clip();
      ctx.fillStyle = '#2c1850'; ctx.fillRect(cx - r, cy - r, r * 2, r * 2);
      const slices = 54;
      for (let i = 0; i < slices; i++) {
        const a = (i / slices) * TAU + rot;
        const ca = Math.cos(a);
        if (ca <= 0) continue;              // hide far hemisphere
        const x = cx + Math.sin(a) * r;
        const w = ca * (TAU * r / slices) + 1.2;
        const band = 0.5 + 0.5 * Math.sin(a * 5 + Math.sin(a * 2) * 2);
        const hue = 268 + 34 * Math.sin(a * 2 + 1);
        const light = 26 + 30 * band;
        ctx.fillStyle = `hsl(${hue}, 60%, ${light}%)`;
        ctx.fillRect(x - w / 2, cy - r - 1, w + 1, r * 2 + 2);
      }
      // day/night shading + specular
      let sh = ctx.createRadialGradient(cx - r * 0.4, cy - r * 0.42, r * 0.15, cx + r * 0.18, cy + r * 0.2, r * 1.25);
      sh.addColorStop(0, 'rgba(255,236,255,0.30)'); sh.addColorStop(0.42, 'rgba(120,70,180,0)'); sh.addColorStop(1, 'rgba(8,4,20,0.72)');
      ctx.fillStyle = sh; ctx.fillRect(cx - r, cy - r, r * 2, r * 2);
      ctx.restore();

      // rim light
      ctx.lineWidth = 2.4; ctx.strokeStyle = 'rgba(214,176,255,0.55)';
      ctx.beginPath(); ctx.arc(cx, cy, r, Math.PI * 0.86, Math.PI * 1.46); ctx.stroke();

      drawRing(cx, cy, r, -0.46, true); // front of ring
    }

    // a glowing point travels between stars, drawing a constellation as you scroll
    function drawStar(x, y, s, bright) {
      let g = ctx.createRadialGradient(x, y, 0, x, y, s * 2.6);
      g.addColorStop(0, `rgba(236,214,255,${0.55 * bright})`); g.addColorStop(1, 'rgba(236,214,255,0)');
      ctx.fillStyle = g; ctx.beginPath(); ctx.arc(x, y, s * 2.6, 0, TAU); ctx.fill();
      ctx.strokeStyle = `rgba(255,255,255,${0.7 * bright})`; ctx.lineWidth = 1.2; ctx.lineCap = 'round';
      ctx.beginPath(); ctx.moveTo(x - s, y); ctx.lineTo(x + s, y); ctx.moveTo(x, y - s); ctx.lineTo(x, y + s); ctx.stroke();
      ctx.fillStyle = `rgba(255,255,255,${0.85 * bright + 0.15})`;
      ctx.beginPath(); ctx.arc(x, y, Math.max(1.3, s * 0.26), 0, TAU); ctx.fill();
    }

    function drawConstellation(prog, t) {
      const nodes = [[0.07, 0.80], [0.15, 0.58], [0.245, 0.75], [0.34, 0.47], [0.44, 0.63], [0.54, 0.40], [0.63, 0.55]]
        .map(([nx, ny]) => ({ x: nx * W, y: ny * H }));

      let segLen = [], total = 0;
      for (let i = 1; i < nodes.length; i++) { const d = Math.hypot(nodes[i].x - nodes[i - 1].x, nodes[i].y - nodes[i - 1].y); segLen.push(d); total += d; }
      const dist = prog * total;

      let acc = 0, bx = nodes[0].x, by = nodes[0].y, reachedIdx = 0, partial = null;
      for (let i = 1; i < nodes.length; i++) {
        const d = segLen[i - 1];
        if (acc + d >= dist) { const f = (dist - acc) / d; bx = lerp(nodes[i - 1].x, nodes[i].x, f); by = lerp(nodes[i - 1].y, nodes[i].y, f); reachedIdx = i - 1; partial = { from: i - 1, f }; break; }
        acc += d; reachedIdx = i; bx = nodes[i].x; by = nodes[i].y;
      }

      // formed constellation lines
      ctx.lineCap = 'round'; ctx.lineJoin = 'round';
      ctx.shadowColor = 'rgba(176,128,240,0.85)'; ctx.shadowBlur = 12;
      for (let i = 1; i <= reachedIdx; i++) {
        ctx.strokeStyle = 'rgba(198,162,242,0.78)'; ctx.lineWidth = 2;
        ctx.beginPath(); ctx.moveTo(nodes[i - 1].x, nodes[i - 1].y); ctx.lineTo(nodes[i].x, nodes[i].y); ctx.stroke();
      }
      if (partial) {
        ctx.strokeStyle = 'rgba(232,208,255,0.95)'; ctx.lineWidth = 2.4;
        ctx.beginPath(); ctx.moveTo(nodes[partial.from].x, nodes[partial.from].y); ctx.lineTo(bx, by); ctx.stroke();
      }
      ctx.shadowBlur = 0;

      // star nodes — reached ones scale/twinkle ("sazvežđe scaling")
      nodes.forEach((n, i) => {
        const reached = i <= reachedIdx;
        const tw = reduce ? 0.7 : 0.6 + 0.4 * Math.sin(t * 0.004 + i * 1.7);
        const size = reached ? 7 + tw * 2.4 : 4.2;
        drawStar(n.x, n.y, size, reached ? 1 : 0.5);
      });

      // leading comet orb
      const br = clamp(W * 0.012, 8, 15);
      const pulse = reduce ? 0 : Math.sin(t * 0.006) * 1.4;
      let bg = ctx.createRadialGradient(bx - br * 0.35, by - br * 0.4, br * 0.2, bx, by, br + 2);
      bg.addColorStop(0, '#fff'); bg.addColorStop(0.4, '#e6c9ff'); bg.addColorStop(1, '#9a5fd6');
      ctx.shadowColor = 'rgba(214,176,255,0.95)'; ctx.shadowBlur = 22 + pulse * 2;
      ctx.fillStyle = bg; ctx.beginPath(); ctx.arc(bx, by, br + pulse, 0, TAU); ctx.fill();
      ctx.shadowBlur = 0;
      ctx.fillStyle = 'rgba(255,255,255,0.9)'; ctx.beginPath(); ctx.arc(bx - br * 0.3, by - br * 0.34, br * 0.3, 0, TAU); ctx.fill();
    }

    function frame(t) {
      // ease the scrubbed progress for buttery motion
      smoothRef.current += (progRef.current - smoothRef.current) * 0.12;
      const prog = smoothRef.current;

      // backdrop
      const bg = ctx.createLinearGradient(0, 0, W, H);
      bg.addColorStop(0, '#1b1030'); bg.addColorStop(0.55, '#241341'); bg.addColorStop(1, '#0d0a1c');
      ctx.fillStyle = bg; ctx.fillRect(0, 0, W, H);
      // nebula wash
      let neb = ctx.createRadialGradient(W * 0.3, H * 0.2, 0, W * 0.3, H * 0.2, W * 0.5);
      neb.addColorStop(0, 'rgba(120,64,180,0.22)'); neb.addColorStop(1, 'rgba(120,64,180,0)');
      ctx.fillStyle = neb; ctx.fillRect(0, 0, W, H);

      // stars (parallax with progress + twinkle)
      for (const s of stars) {
        const tw = reduce ? 0.8 : 0.55 + 0.45 * Math.sin(t * 0.002 * s.s + s.p);
        const sx = (s.x - prog * 40 * s.dx + W) % W;
        ctx.fillStyle = `rgba(232,222,255,${0.25 + tw * 0.6})`;
        ctx.beginPath(); ctx.arc(sx, s.y, s.r, 0, TAU); ctx.fill();
      }

      // planet (rotation scrubbed by scroll, subtle scale = "schaling")
      const pr = Math.min(H * 0.72, W * 0.30) * (0.92 + prog * 0.16);
      const pcx = W * 0.80, pcy = H * 0.44;
      const rot = prog * TAU * 3 + (reduce ? 0 : t * 0.00003);
      drawPlanet(pcx, pcy, pr, rot, t);

      drawConstellation(prog, t);

      raf = requestAnimationFrame(frame);
    }
    raf = requestAnimationFrame(frame);

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('resize', resize);
      window.removeEventListener('scroll', updateProgress);
    };
  }, []);

  return (
    <div ref={wrapRef} onClick={() => onNav({ view: 'page', key: 'pravna-lica' })} style={{ cursor: 'pointer', borderRadius: 'var(--sm-radius-xl)', overflow: 'hidden', boxShadow: 'var(--sm-shadow-md)', background: '#fff', display: 'flex', flexDirection: 'column' }}>
      {/* animated scene */}
      <div ref={sceneRef} style={{ position: 'relative', height: 300, background: '#1b1030' }}>
        <canvas ref={canvasRef} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', display: 'block' }} />
        <div style={{ position: 'absolute', left: 28, top: 22, display: 'inline-flex', alignItems: 'center', gap: 8, background: 'rgba(255,255,255,.12)', border: '1px solid rgba(255,255,255,.22)', backdropFilter: 'blur(6px)', borderRadius: 'var(--sm-radius-pill)', padding: '7px 14px', color: '#fff', fontFamily: 'var(--sm-font-techno)', textTransform: 'uppercase', letterSpacing: '.16em', fontSize: 12 }}>
          {I('rocket', 15)} Skaliraj svoj biznis
        </div>
      </div>
      {/* purple band — copy + CTA */}
      <div style={{ position: 'relative', background: 'var(--sm-purple-500)', color: '#fff', padding: '26px 28px 28px' }}>
        <div style={{ fontFamily: 'var(--sm-font-techno)', textTransform: 'uppercase', letterSpacing: '.12em', fontSize: 12, opacity: .85, marginBottom: 8 }}>Pravna lica</div>
        <h3 style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 800, fontSize: 28, color: '#fff', margin: 0, letterSpacing: '-.01em', maxWidth: '68%' }}>Podigni svoj biznis na viši nivo!</h3>
        <p style={{ fontFamily: 'var(--sm-font-body)', fontSize: 16, lineHeight: 1.5, margin: '8px 0 0', color: 'rgba(255,255,255,.92)', maxWidth: '60%' }}>Posebne <b>B2B</b> cene, stručna podrška i rešenja prilagođena tvojoj količini. Jedan partner za sve što ti treba.</p>
        <div style={{ position: 'absolute', right: 28, bottom: 26 }}>
          <Button variant="light" onClick={(e) => { e.stopPropagation(); onNav({ view: 'page', key: 'pravna-lica' }); }} iconRight={I('arrow-right', 18)}>Saznajte više</Button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { B2BPlanetBanner });
