/* global React, OrbitTab, ThreeLogo */
const { useEffect, useRef, useState, useMemo } = React;

/**
 * A single label on the orbit ring (horizontal carousel — Y-axis rotation).
 * Tabs slide along the X axis past the logo as `theta` advances.
 *   θ = 0     → in front of logo, closest to camera, largest
 *   θ = π/2   → at the logo's right edge, side-on
 *   θ = π     → directly behind logo, hidden
 *   θ = 3π/2  → at the logo's left edge, side-on
 */
function OrbitTab({ label, theta, radius, depth, onClick, active, settled }) {
  const [hovered, setHovered] = useState(false);
  const style = useMemo(() => {
    // Horizontal merry-go-round around the logo.
    const x = Math.sin(theta) * radius;            // horizontal position
    const z = Math.cos(theta) * depth;             // +depth front, -depth back
    const front = (Math.cos(theta) + 1) / 2;       // 0..1 — 1 when in front
    const scale = 0.60 + 0.40 * front;
    const opacity = 0.55 + 0.45 * front;
    const blur = (1 - front) * 1.0;
    return {
      transform: `translate3d(calc(-50% + ${x}px), -24px, ${z}px) scale(${scale})`,
      opacity,
      filter: blur > 0.2 ? `blur(${blur.toFixed(2)}px)` : 'none',
      zIndex: Math.round(front * 100),
      pointerEvents: front > 0.45 ? 'auto' : 'none',
    };
  }, [theta, radius, depth]);

  // sin(theta) — горизонтальное смещение; порог 0.06 = 3% от диаметра орбиты
  const isCentered = Math.abs(Math.sin(theta)) < 0.06;
  const showDropdown = active && settled && hovered && label.dropdown && isCentered;

  return (
    <button
      className={'wt-orbit-tab' + (active ? ' is-active' : '')}
      style={style}
      onClick={onClick}
      aria-current={active ? 'true' : undefined}
      onMouseEnter={() => active && settled && setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      <span className="wt-orbit-tab__header">
        <span className="wt-orbit-tab__line" aria-hidden="true"></span>
        <span className="wt-orbit-tab__label">
          {window.WTi18n ? WTi18n.t(label.i18n) : (label.text || label.i18n)}
        </span>
        <span className="wt-orbit-tab__line" aria-hidden="true"></span>
      </span>
      {label.dropdown && (
        <div className={'wt-orbit-tab__dropdown-wrap' + (showDropdown ? ' is-open' : '')}>
          <div className="wt-orbit-tab__dropdown">
            <div className="wt-orbit-tab__divider" />
            <div className="wt-orbit-tab__dropdown-inner">
              {label.dropdown.map((key, idx) => (
                <div key={idx} className="wt-orbit-tab__dropdown-line">
                  {window.WTi18n ? WTi18n.t(key) : key}
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </button>
  );
}

window.OrbitTab = OrbitTab;
