'use client';

import { useEffect, useRef } from 'react';
import { usePathname } from 'next/navigation';

/**
 * Route → hero visual. Paths are WITHOUT the locale prefix (/en, /cs, /de are stripped).
 * Home ("/") has its own hero and is intentionally not listed.
 */
export const HERO_VIZ_ROUTES: Record<string, string> = {
  '/services': 'services',
  '/services/cloud-development': 'development',
  '/services/azure': 'azure',
  '/services/devops-cicd': 'devops',
  '/services/ai-agents': 'data',
  '/services/it-consulting': 'consulting',
  '/services/project-management': 'pm',
  '/process': 'process',
  '/case-studies': 'case-studies',
  '/insights': 'insights',
  '/about': 'about',
  '/career': 'career',
  '/contact': 'contact',
  '/booking': 'contact',
  '/audit': 'audit',
};

export function heroVizForPath(pathname: string | null): string | null {
  if (!pathname) return null;
  const path = pathname.replace(/^\/(en|cs|de)(?=\/|$)/, '').replace(/\/+$/, '') || '/';
  return HERO_VIZ_ROUTES[path] ?? null;
}

const THREE_SRC = 'https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js';
const VIZ_SRC = '/cd-hero-viz.js'; // put cd-hero-viz.js into /public

let loading: Promise<void> | null = null;

function loadScript(src: string): Promise<void> {
  return new Promise((resolve, reject) => {
    const existing = document.querySelector<HTMLScriptElement>(`script[src="${src}"]`);
    if (existing) {
      if (existing.dataset.loaded) return resolve();
      existing.addEventListener('load', () => resolve());
      existing.addEventListener('error', () => reject(new Error(`Failed to load ${src}`)));
      return;
    }
    const s = document.createElement('script');
    s.src = src;
    s.async = true;
    s.onload = () => { s.dataset.loaded = '1'; resolve(); };
    s.onerror = () => reject(new Error(`Failed to load ${src}`));
    document.head.appendChild(s);
  });
}

function ensureLoaded(): Promise<void> {
  const w = window as any;
  if (w.THREE && w.CDHeroViz) return Promise.resolve();
  if (!loading) {
    loading = (w.THREE ? Promise.resolve() : loadScript(THREE_SRC))
      .then(() => (w.CDHeroViz ? undefined : loadScript(VIZ_SRC)))
      .catch(err => { loading = null; throw err; });
  }
  return loading;
}

type Props = {
  /** Force a variant; otherwise it is picked from the current URL. */
  variant?: string;
  className?: string;
  style?: React.CSSProperties;
};

export default function HeroViz({ variant, className, style }: Props) {
  const ref = useRef<HTMLDivElement>(null);
  const pathname = usePathname();
  const v = variant ?? heroVizForPath(pathname);

  useEffect(() => {
    const el = ref.current;
    if (!el || !v) return;
    let alive = true;
    ensureLoaded()
      .then(() => { if (alive) (window as any).CDHeroViz?.mount(el); })
      .catch(() => { /* visual is decorative; fail silently */ });
    return () => {
      alive = false;
      (window as any).CDHeroViz?.unmount(el);
    };
  }, [v]);

  if (!v) return null;
  return (
    <div
      ref={ref}
      key={v}
      className={className}
      data-variant={v}
      aria-hidden="true"
      style={{ position: 'relative', width: '100%', height: '100%', minHeight: 280, ...style }}
    />
  );
}
