// Orbit logo + node system — reusable React components for 360 Buzz

const APP_COLORS = {
  gold:    'var(--hive)',
  amber:   'var(--amber)',
  blue:    'var(--blue)',
  lime:    'var(--lime)',
  magenta: 'var(--magenta)',
};

// Tech logo map — filename in /assets/tech-logos/
const TECH_LOGOS = {
  'Xcode':            'XCode.png',
  'Swift':            'Swift.png',
  'Firebase':         'Firebase.png',
  'GitHub':           'GitHub.png',
  'Node':             'Node.png',
  'MongoDB':          'MongoDB.png',
  'Google Cloud':     'Google-Cloud.png',
  'Android Studio':   'Andoid-Studio.png',
  'Jetpack Compose':  'JetPack-Compose.png',
  'React':            'React.png',
  'TypeScript':       'TypeScript.png',
  'Postgres':         'Postgres.png',
};

const APPS = [
  { id: '1glance',  name: '1Glance',   tag: 'Dynamic Apple TV Screens',  color: 'gold',  accent: '#F2A900',
    logo: '/assets/logos/1Glance.png',
    tech: ['Xcode','Swift','Firebase','GitHub'],
    platforms: ['AppleTV','iOS'],
    blurb: 'Transform your TV into a dynamic information hub. Build and manage custom screens for Apple TV — weather, news, calendars — all controlled from your phone in real time.',
    storeLinks: [
      { badge: '/assets/Apple-Store-Badge.svg', label: 'Download on the App Store', url: 'https://apps.apple.com/app/id6468119714' },
      { badge: '/assets/Apple-TV-Badge.svg', label: 'Download for Apple TV', url: 'https://apps.apple.com/app/id6468119714' },
    ] },
  { id: 'abhcare',  name: 'ABH.Care',  tag: 'Behavioral Health Portal',  color: 'blue',  accent: '#3a73B4',
    logo: '/assets/logos/ABH.png',
    tech: ['Xcode','Swift','Node','MongoDB','Google Cloud','GitHub'],
    platforms: ['iOS'],
    blurb: 'A patient and provider portal for Alpha Behavioral Health. Manage appointments, view schedules, and handle secure messaging — backed by a Node API integrated with Tebra and deployed on Google Cloud.',
    storeLinks: [
      { badge: '/assets/Apple-Store-Badge.svg', label: 'Download on the App Store', url: 'https://apps.apple.com/us/app/abh-care/id6756860067' },
    ] },
  { id: 'countrpt', name: 'CountrPT',  tag: 'AI Career Management',     color: 'lime',  accent: '#57AAB3',
    logo: '/assets/logos/CountrPT.png',
    tech: ['Xcode','Android Studio','Jetpack Compose','Node','React','TypeScript','Postgres','GitHub'],
    platforms: ['iOS','Android'],
    blurb: 'An AI-powered tool for documenting daily work, planning one-on-ones, and owning your performance reviews. Voice-to-text meets AI agents for effortless career self-management.',
    note: 'This app is not published by our studio. We were contracted to write the app.' },
];

// — Orbit —
// size: viewbox edge in px. nodes: array. radius: orbit radius (in viewbox units).
// activeId: which node is highlighted. center: optional inner mark (e.g. wordmark).
function OrbitLogo({
  size = 480,
  nodes = APPS,
  radius = 180,
  activeId = null,
  spin = 28,            // seconds per revolution
  paused = false,
  onSelect,
  showLines = true,
  asymmetry = 0,        // 0 = perfect circle
  nodeSize = 18,
  className,
  style,
}) {
  const cx = size / 2;
  const cy = size / 2;
  const rx = radius;
  const ry = radius * (1 - asymmetry);

  const positions = React.useMemo(() => {
    const N = nodes.length;
    return nodes.map((n, i) => {
      const t = (i / N) * Math.PI * 2 - Math.PI / 2;
      return {
        ...n,
        x: cx + Math.cos(t) * rx,
        y: cy + Math.sin(t) * ry,
        angle: t,
      };
    });
  }, [nodes, cx, cy, rx, ry]);

  // All unique node-to-node pairs for stochastic pulse animation
  const lines = React.useMemo(() => {
    const out = [];
    const N = positions.length;
    for (let i = 0; i < N; i++) {
      for (let j = i + 1; j < N; j++) {
        out.push([positions[i], positions[j]]);
      }
    }
    return out;
  }, [positions]);

  const lineDurations = [11, 17, 13, 19, 23, 14];
  const lineDelays    = [0, 3, 6, 2, 5, 8];

  return (
    <div
      className={className}
      style={{
        position: 'relative',
        width: '100%',
        aspectRatio: '1 / 1',
        maxWidth: size,
        margin: '0 auto',
        ...style,
      }}
    >
      <svg
        viewBox={`0 0 ${size} ${size}`}
        style={{
          position: 'absolute', inset: 0, width: '100%', height: '100%',
          animation: paused ? 'none' : `bz-orbit-spin ${spin}s linear infinite`,
          transformOrigin: '50% 50%',
        }}
      >
        <defs>
          <radialGradient id="bz-glow" cx="50%" cy="50%" r="50%">
            <stop offset="0%"  stopColor="var(--accent)" stopOpacity="0.35" />
            <stop offset="60%" stopColor="var(--accent)" stopOpacity="0.05" />
            <stop offset="100%" stopColor="var(--accent)" stopOpacity="0" />
          </radialGradient>
          <filter id="bz-soft" x="-50%" y="-50%" width="200%" height="200%">
            <feGaussianBlur stdDeviation="8" />
          </filter>
        </defs>

        {/* Center subtle glow */}
        <circle cx={cx} cy={cy} r={radius * 0.55} fill="url(#bz-glow)" />

        {/* Orbit circle */}
        <circle
          cx={cx} cy={cy} r={rx}
          fill="none"
          stroke="rgba(245,244,238,0.18)"
          strokeWidth="1"
          strokeDasharray="2 6"
        />
        {/* A second, fainter, slightly smaller orbit for depth */}
        <circle
          cx={cx} cy={cy} r={rx * 0.78}
          fill="none"
          stroke="rgba(245,244,238,0.07)"
          strokeWidth="1"
        />

        {/* Connecting lines — stochastic pulse */}
        {showLines && lines.map(([a, b], i) => {
          const isAccent = a.color === 'gold' || b.color === 'gold';
          return (
            <line
              key={i}
              x1={a.x} y1={a.y} x2={b.x} y2={b.y}
              stroke={isAccent ? a.accent || b.accent : 'rgba(245,244,238,0.45)'}
              strokeWidth="1"
              style={{
                opacity: 0,
                animation: `bz-line-pulse ${lineDurations[i % lineDurations.length]}s ease infinite`,
                animationDelay: `${lineDelays[i % lineDelays.length]}s`,
              }}
            />
          );
        })}

        {/* Nodes */}
        {positions.map((n) => {
          const isActive = activeId ? n.id === activeId : n.color === 'gold';
          const r = isActive ? nodeSize * 0.7 : nodeSize * 0.5;
          return (
            <g
              key={n.id}
              style={{ cursor: onSelect ? 'pointer' : 'default' }}
              onClick={() => onSelect && onSelect(n)}
            >
              {isActive && (
                <circle cx={n.x} cy={n.y} r={r * 2.2} fill={n.accent} opacity="0.18" filter="url(#bz-soft)" />
              )}
              <circle
                cx={n.x} cy={n.y} r={r}
                fill={isActive ? n.accent : '#1B1B20'}
                stroke={isActive ? n.accent : 'rgba(245,244,238,0.45)'}
                strokeWidth={isActive ? 0 : 1.2}
              />
              {isActive && (
                <circle cx={n.x} cy={n.y} r={r + 4} fill="none" stroke={n.accent} strokeWidth="1" opacity="0.55" />
              )}
            </g>
          );
        })}
      </svg>
    </div>
  );
}

// Logo — raster asset (root-relative for /pages/*, /directions/*, etc.)
function brandLogoSrc() {
  return '/assets/360Buzz-On-Black_1@3x.png';
}

// Wordmark (historical name) — renders the official logo image
function Wordmark({ size = 28, style, className }) {
  const heightPx = Math.round(size * 1.85 * 3);
  return (
    <img
      src={brandLogoSrc()}
      alt="360 Buzz"
      className={`bz-brand-logo ${className || ''}`}
      style={{ height: heightPx, width: 'auto', ...style }}
      decoding="async"
    />
  );
}

// Horizontal lockup — same raster logo (asset is already a full lockup)
function LockupHorizontal({ size = 32 }) {
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center' }}>
      <Wordmark size={size} />
    </div>
  );
}

// Compact icon-only orbit mark for headers/footers
function MiniOrbitMark({ size = 36, accent = 'var(--accent)' }) {
  const s = size;
  const cx = s / 2, cy = s / 2;
  const r = s * 0.38;
  return (
    <svg width={s} height={s} viewBox={`0 0 ${s} ${s}`} style={{ display: 'block' }}>
      <circle cx={cx} cy={cy} r={r} fill="none" stroke="currentColor" strokeOpacity="0.45" strokeWidth="1" />
      {[0, 1, 2].map(i => {
        const t = (i / 3) * Math.PI * 2 - Math.PI / 2;
        const x = cx + Math.cos(t) * r;
        const y = cy + Math.sin(t) * r;
        const isActive = i === 0;
        return (
          <circle
            key={i} cx={x} cy={y} r={isActive ? 3 : 1.8}
            fill={isActive ? accent : 'currentColor'}
            opacity={isActive ? 1 : 0.6}
          />
        );
      })}
    </svg>
  );
}

// Inject the spin keyframes once
if (typeof document !== 'undefined' && !document.getElementById('bz-orbit-style')) {
  const s = document.createElement('style');
  s.id = 'bz-orbit-style';
  s.textContent = `
    @keyframes bz-orbit-spin { from { transform: rotate(0); } to { transform: rotate(360deg); } }
    @keyframes bz-counter-spin { from { transform: rotate(0); } to { transform: rotate(-360deg); } }
    @keyframes bz-fade-up { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }
    @keyframes bz-flicker { 0%,100%{opacity:1} 50%{opacity:0.55} }
    @keyframes bz-line-pulse { 0%,100%{opacity:0} 10%{opacity:0.55} 18%{opacity:0.55} 28%{opacity:0} }

    /* Responsive editorial hero */
    @media (max-width: 900px) {
      .bz-hero-grid { grid-template-columns: 1fr !important; }
      .bz-hero-orbit {
        height: auto !important;
        min-height: auto !important;
        padding-top: 0 !important;
        display: flex !important;
        flex-direction: column !important;
        align-items: center !important;
        gap: 16px;
      }
      .bz-hero-orbit > div:first-child {
        position: relative !important;
        top: auto !important;
        height: auto !important;
        width: 100%;
        max-width: 320px;
        aspect-ratio: 1;
      }
      .bz-hero-card {
        position: relative !important;
        bottom: auto !important;
        left: auto !important;
        transform: none !important;
        width: min(100%, 340px) !important;
      }
      .bz-hero-section { padding-left: 24px !important; padding-right: 24px !important; padding-top: 8px !important; }
      .bz-hero-strip { flex-direction: column !important; align-items: flex-start !important; gap: 20px !important; }
      .bz-brand-bar { padding: 16px 24px 0 !important; }
    }
    @media (max-width: 900px) {
      .bz-testimonials-section { padding: 80px 24px !important; }
    }
    @media (max-width: 600px) {
      .bz-reviews-carousel { padding-left: 40px !important; padding-right: 40px !important; }
    }
    @media (max-width: 480px) {
      .bz-hero-orbit > div:first-child { max-width: 260px; }
    }

    @media (max-width: 900px) {
      .bz-app-section {
        grid-template-columns: 1fr !important;
        padding: 60px 24px !important;
        gap: 40px !important;
        min-height: auto !important;
      }
      .bz-app-section > div { order: unset !important; }
      .bz-app-section > div:first-child {
        width: 100% !important;
        display: block !important;
      }
      .bz-app-video {
        transform: none !important;
        animation: none !important;
        width: 100% !important;
        max-width: 100% !important;
        margin-left: 0;
        margin-right: 0;
      }
      .bz-process-section {
        padding: 80px 24px 100px !important;
      }
      .bz-process-intro {
        grid-template-columns: 1fr !important;
        gap: 24px !important;
        margin-bottom: 48px !important;
        align-items: start !important;
      }
      .bz-process-intro-lede {
        justify-self: start !important;
        max-width: none !important;
      }
      .bz-process-line {
        display: none !important;
      }
      .bz-process-steps {
        grid-template-columns: 1fr !important;
        gap: 0 !important;
      }
      .bz-process-step {
        padding: 0 0 32px 20px !important;
        border-left: 1px solid var(--line-2);
        margin-left: 7px;
      }
      .bz-process-step:last-child {
        padding-bottom: 0 !important;
      }
      .bz-process-node {
        margin-left: -27px !important;
      }
    }
  `;
  document.head.appendChild(s);
}

Object.assign(window, { APPS, APP_COLORS, OrbitLogo, Wordmark, LockupHorizontal, MiniOrbitMark });
