// Astrail — Loader Component System
// 5 variants: Arc · Orbit · Chain · Pulse · Signal
// Spec-compliant: no glow, no blur, no shadows, no gradients.
// Animate transform + opacity only (GPU-composited, no layout/paint).
// Reduced motion: all variants collapse to static opacity pulse.

// ── Size scale ────────────────────────────────────────────────────
const LOADER_SIZES = {
  sm:      { d: 20, stroke: 2,   dotD: 5,  barH: 14, barW: 2,   gap: 3  },
  md:      { d: 32, stroke: 2.5, dotD: 7,  barH: 20, barW: 2.5, gap: 3.5 },
  default: { d: 36, stroke: 2.5, dotD: 8,  barH: 24, barW: 3,   gap: 4  },
  lg:      { d: 48, stroke: 3,   dotD: 10, barH: 32, barW: 3.5, gap: 5  },
};

// ── 1. Arc — single rotating arc — use for: buttons, inline, page transitions
const LoaderArc = ({ size = 'default' }) => {
  const { d, stroke } = LOADER_SIZES[size] || LOADER_SIZES.default;
  const cx = d / 2, r = cx - stroke / 2;
  const C = 2 * Math.PI * r;
  const arc = C * 0.72; // ~260° active segment

  return (
    <svg width={d} height={d} viewBox={`0 0 ${d} ${d}`}
      style={{ display: 'block', flexShrink: 0 }}
      role="status" aria-label="Loading">
      {/* Track */}
      <circle cx={cx} cy={cx} r={r}
        fill="none"
        stroke="var(--col-accent)"
        strokeWidth={stroke}
        strokeOpacity="0.11" />
      {/* Active arc */}
      <circle cx={cx} cy={cx} r={r}
        fill="none"
        stroke="var(--col-accent)"
        strokeWidth={stroke}
        strokeLinecap="round"
        strokeDasharray={`${arc.toFixed(2)} ${(C - arc).toFixed(2)}`}
        className="nvx-loader-arc" />
    </svg>
  );
};

// ── 2. Orbit — dual counter-rotating arcs — use for: approvals, sig checks
const LoaderOrbit = ({ size = 'default' }) => {
  const { d, stroke } = LOADER_SIZES[size] || LOADER_SIZES.default;
  const cx = d / 2;
  const rO = cx - stroke / 2;
  const rI = rO * 0.58;
  const CO = 2 * Math.PI * rO;
  const CI = 2 * Math.PI * rI;
  const arcO = CO * 0.50; // ~180°
  const arcI = CI * 0.25; // ~90°

  return (
    <svg width={d} height={d} viewBox={`0 0 ${d} ${d}`}
      style={{ display: 'block', flexShrink: 0 }}
      role="status" aria-label="Loading">
      {/* Outer track */}
      <circle cx={cx} cy={cx} r={rO}
        fill="none" stroke="var(--col-accent)"
        strokeWidth={stroke} strokeOpacity="0.11" />
      {/* Inner track */}
      <circle cx={cx} cy={cx} r={rI}
        fill="none" stroke="var(--col-accent)"
        strokeWidth={stroke} strokeOpacity="0.11" />
      {/* Outer arc — clockwise */}
      <circle cx={cx} cy={cx} r={rO}
        fill="none" stroke="var(--col-accent)"
        strokeWidth={stroke} strokeLinecap="round"
        strokeDasharray={`${arcO.toFixed(2)} ${(CO - arcO).toFixed(2)}`}
        className="nvx-loader-orbit-outer" />
      {/* Inner arc — counter-clockwise */}
      <circle cx={cx} cy={cx} r={rI}
        fill="none" stroke="var(--col-accent)"
        strokeWidth={stroke} strokeLinecap="round"
        strokeDasharray={`${arcI.toFixed(2)} ${(CI - arcI).toFixed(2)}`}
        className="nvx-loader-orbit-inner" />
    </svg>
  );
};

// ── 3. Chain — three staggered pulse dots — use for: batch ops, wizards
const LoaderChain = ({ size = 'default' }) => {
  const { dotD } = LOADER_SIZES[size] || LOADER_SIZES.default;
  const gap = Math.round(dotD * 1.1);
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap }}
      role="status" aria-label="Loading">
      {[0, 0.2, 0.4].map((delay, i) => (
        <div key={i}
          className="nvx-loader-chain-dot"
          style={{
            width: dotD, height: dotD,
            borderRadius: '50%',
            background: 'var(--col-accent)',
            animationDelay: `${delay}s`,
          }} />
      ))}
    </div>
  );
};

// ── 4. Pulse — expanding rings — use for: blockchain confirms, external waits
const LoaderPulse = ({ size = 'default' }) => {
  const { d } = LOADER_SIZES[size] || LOADER_SIZES.default;
  const coreD = Math.round(d * 0.28);

  return (
    <div style={{ position: 'relative', width: d, height: d, flexShrink: 0 }}
      role="status" aria-label="Loading">
      {[0, 0.75].map((delay, i) => (
        <div key={i}
          className="nvx-loader-pulse-ring"
          style={{
            position: 'absolute', inset: 0,
            borderRadius: '50%',
            border: '2px solid var(--col-accent)',
            animationDelay: `${delay}s`,
          }} />
      ))}
      {/* Core dot */}
      <div style={{
        position: 'absolute',
        top: '50%', left: '50%',
        width: coreD, height: coreD,
        marginTop: -coreD / 2, marginLeft: -coreD / 2,
        borderRadius: '50%',
        background: 'var(--col-accent)',
      }} />
    </div>
  );
};

// ── 5. Signal — four vertical wave bars — use for: live sync, feed badges
const LoaderSignal = ({ size = 'default' }) => {
  const { barH, barW, gap } = LOADER_SIZES[size] || LOADER_SIZES.default;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap }}
      role="status" aria-label="Loading">
      {[0, 0.14, 0.28, 0.14].map((delay, i) => (
        <div key={i}
          className="nvx-loader-signal-bar"
          style={{
            width: barW, height: barH,
            borderRadius: barW / 2,
            background: 'var(--col-accent)',
            animationDelay: `${delay}s`,
          }} />
      ))}
    </div>
  );
};

// ── CSS — injected once at module load ────────────────────────────
const NVX_LOADER_CSS = `
  /* Arc */
  .nvx-loader-arc {
    transform-box: fill-box;
    transform-origin: center;
    animation: nvxArcSpin 1.15s linear infinite;
  }

  /* Orbit */
  .nvx-loader-orbit-outer {
    transform-box: fill-box;
    transform-origin: center;
    animation: nvxOrbitCW 1.9s cubic-bezier(0.6,0,0.4,1) infinite;
  }
  .nvx-loader-orbit-inner {
    transform-box: fill-box;
    transform-origin: center;
    animation: nvxOrbitCCW 1.1s cubic-bezier(0.6,0,0.4,1) infinite;
  }

  /* Chain */
  .nvx-loader-chain-dot {
    transform-origin: center;
    animation: nvxChainDot 1.4s ease-in-out infinite;
  }

  /* Pulse */
  .nvx-loader-pulse-ring {
    transform-origin: center;
    animation: nvxPulseRing 2.0s ease-out infinite;
  }

  /* Signal */
  .nvx-loader-signal-bar {
    transform-origin: center;
    animation: nvxSignalBar 1.2s ease-in-out infinite;
  }

  /* ── Keyframes ─────────────────────────────────────────────── */
  @keyframes nvxArcSpin {
    from { transform: rotate(-90deg); }
    to   { transform: rotate(270deg); }
  }

  @keyframes nvxOrbitCW {
    from { transform: rotate(-90deg); }
    to   { transform: rotate(270deg); }
  }

  @keyframes nvxOrbitCCW {
    from { transform: rotate(90deg); }
    to   { transform: rotate(-270deg); }
  }

  @keyframes nvxChainDot {
    0%    { transform: scale(0.55); opacity: 0.25; }
    40%   { transform: scale(1);    opacity: 1;    }
    80%   { transform: scale(0.55); opacity: 0.25; }
    100%  { transform: scale(0.55); opacity: 0.25; }
  }

  @keyframes nvxPulseRing {
    0%   { transform: scale(0.45); opacity: 0.55; }
    100% { transform: scale(2.4);  opacity: 0;    }
  }

  @keyframes nvxSignalBar {
    0%,100% { transform: scaleY(0.28); opacity: 0.3; }
    50%     { transform: scaleY(1);    opacity: 1;   }
  }

  /* ── Reduced motion ────────────────────────────────────────── */
  @media (prefers-reduced-motion: reduce) {
    .nvx-loader-arc,
    .nvx-loader-orbit-outer,
    .nvx-loader-orbit-inner,
    .nvx-loader-chain-dot,
    .nvx-loader-pulse-ring,
    .nvx-loader-signal-bar {
      animation: nvxStaticPulse 1.5s linear infinite !important;
      transform: none !important;
    }
  }
  @keyframes nvxStaticPulse {
    0%,100% { opacity: 0.35; }
    50%     { opacity: 1;    }
  }
`;

if (!document.getElementById('nvx-loaders-css')) {
  const s = document.createElement('style');
  s.id = 'nvx-loaders-css';
  s.textContent = NVX_LOADER_CSS;
  document.head.appendChild(s);
}

Object.assign(window, {
  LoaderArc, LoaderOrbit, LoaderChain, LoaderPulse, LoaderSignal,
  LOADER_SIZES,
});
