/* global React */
const { useState, useEffect, useRef, useCallback } = React;

// ============================================
// LOGO — Real Talos brand assets
// ============================================
const TalosMark = ({ color = "#003C70", size = 32 }) => {
  // color: #003C70 (navy) -> isotip blau corporatiu
  //        #fff (white)   -> versió negativa
  //        other          -> default isotip
  const src = color === '#fff' || color === '#ffffff' || color === 'white'
    ? '/assets/logo-negatiu.svg'
    : '/assets/logo-oficial-color-transparent.png';
  return (
    <img
      src={src}
      alt="Talos"
      width={size}
      height={size}
      style={{ display: 'block', objectFit: 'contain' }}
    />
  );
};

// Horizontal logo (isotip + wordmark) — for navbar / footer
const TalosLogoHorizontal = ({ variant = 'color', height = 32 }) => {
  const src = variant === 'white'
    ? '/assets/logo-negatiu.svg'
    : variant === 'mono'
      ? '/assets/logo-horizontal.svg'
      : '/assets/logo-oficial-color-transparent.png';
  return (
    <img
      className="talos-logo-img"
      src={src}
      alt="Talos Technology"
      style={{ height, width: 'auto', display: 'block' }}
    />
  );
};

// ============================================
// CURSOR WALLPAPER — global interactive background
// Segueix el cursor. Blanc pur + blau corporatiu (fiabilitat).
// ============================================
const CursorWallpaper = ({ active = true }) => {
  const ref = useRef(null);
  useEffect(() => {
    if (!active) return;
    let mx = window.innerWidth / 2;
    let my = window.innerHeight / 2;
    let tx = mx, ty = my;
    let raf = null;
    const apply = () => {
      tx += (mx - tx) * 0.18;
      ty += (my - ty) * 0.18;
      if (ref.current) {
        ref.current.style.setProperty('--mx', tx + 'px');
        ref.current.style.setProperty('--my', ty + 'px');
      }
      raf = requestAnimationFrame(apply);
    };
    const onMove = (e) => { mx = e.clientX; my = e.clientY; };
    window.addEventListener('mousemove', onMove, { passive: true });
    raf = requestAnimationFrame(apply);
    return () => { window.removeEventListener('mousemove', onMove); if (raf) cancelAnimationFrame(raf); };
  }, [active]);
  if (!active) return null;
  return <div ref={ref} className="cursor-wallpaper" aria-hidden="true" />;
};

// ============================================
// NAVBAR
// ============================================
const Navbar = () => {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <header className={`nav ${scrolled ? 'is-scrolled' : ''}`}>
      <div className="container-wide nav-inner">
        <a href="/" className="nav-logo" aria-label="Talos — inicio">
          <TalosLogoHorizontal variant="color" height={64} />
        </a>
        <nav className="nav-links">
          <a className="nav-link" href="/gobernanza-de-datos">Gobernanza de datos</a>
          <a className="nav-link" href="/digitalizacion-de-procesos">Digitalización</a>
          <a className="nav-link" href="/ia-aplicada">IA aplicada</a>
          <a className="nav-link" href="/simulacion-y-formacion-inmersiva">Inmersión</a>
          <span className="nav-sep" />
          <a className="nav-link" href="/metodologia">Metodología</a>
          <a className="nav-link" href="/equipo">Equipo</a>
          <a className="nav-link" href="/contacto">Contacto</a>
          <a className="nav-cta" href="/diagnostico">Solicita tu diagnóstico</a>
        </nav>
      </div>
    </header>
  );
};

// ============================================
// GOVERNANCE WALLPAPER (scroll-driven background)
// ============================================
const GovernanceWallpaper = ({ active }) => {
  const [spot, setSpot] = useState({ x: 50, y: 30 });
  const [gridPx, setGridPx] = useState(48);

  useEffect(() => {
    if (!active) return;
    let raf = null;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        const p = Math.min(1, window.scrollY / (document.body.scrollHeight - window.innerHeight));
        // Grid starts wide (chaotic space), tightens as user scrolls (order)
        setGridPx(48 - p * 16);
        setSpot({ x: 50, y: 20 + p * 60 });
        raf = null;
      });
    };
    const onMove = (e) => setSpot({ x: (e.clientX / window.innerWidth) * 100, y: (e.clientY / window.innerHeight) * 100 });
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('mousemove', onMove, { passive: true });
    return () => { window.removeEventListener('scroll', onScroll); window.removeEventListener('mousemove', onMove); };
  }, [active]);

  return (
    <>
      <div
        className={`governance-wallpaper ${active ? 'is-active' : ''}`}
        style={{ backgroundSize: `${gridPx}px ${gridPx}px` }}
      />
      <div
        className={`governance-spotlight ${active ? 'is-active' : ''}`}
        style={{ '--spot-x': `${spot.x}%`, '--spot-y': `${spot.y}%` }}
      />
    </>
  );
};

// ============================================
// JOURNEY PATH — fil subtil de seguiment de la home
// ============================================
const JourneyPath = () => {
  const pathRef = useRef(null);
  const nodeRefs = useRef([]);
  const labelRefs = useRef([]);
  const rafRef = useRef(null);

  useEffect(() => {
    const path = pathRef.current;
    if (!path) return;

    const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const length = path.getTotalLength();
    path.style.strokeDasharray = `${length}`;
    const sectionIds = ['problema', 'capacidades', 'metodologia', 'sectores', 'contacto'];

    const apply = () => {
      const scrollable = Math.max(1, document.documentElement.scrollHeight - window.innerHeight);
      const progress = prefersReduced ? 1 : Math.min(1, Math.max(0, window.scrollY / scrollable));
      path.style.strokeDashoffset = `${length * (1 - progress)}`;
      const current = sectionIds.reduce((active, id, i) => {
        const section = document.getElementById(id);
        if (!section) return active;
        return section.getBoundingClientRect().top < window.innerHeight * 0.48 ? i + 1 : active;
      }, 0);
      nodeRefs.current.forEach((node, i) => {
        if (!node) return;
        node.classList.toggle('is-active', i <= current);
        node.classList.toggle('is-current', i === current);
      });
      labelRefs.current.forEach((label, i) => {
        if (!label) return;
        label.classList.toggle('is-current', i === current);
      });
      rafRef.current = null;
    };

    const onScroll = () => {
      if (rafRef.current) return;
      rafRef.current = requestAnimationFrame(apply);
    };

    apply();
    if (!prefersReduced) {
      window.addEventListener('scroll', onScroll, { passive: true });
      window.addEventListener('resize', onScroll, { passive: true });
    }

    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      if (rafRef.current) cancelAnimationFrame(rafRef.current);
    };
  }, []);

  const nodes = [
    { x: 12, y: 14, label: 'Datos' },
    { x: 12, y: 32, label: 'Problema' },
    { x: 12, y: 50, label: 'Soluciones' },
    { x: 12, y: 68, label: 'Camino' },
    { x: 12, y: 86, label: 'Casos' },
    { x: 12, y: 104, label: 'Diagnóstico' },
  ];

  return (
    <div className="journey-path" aria-hidden="true">
      <svg viewBox="0 0 120 120" preserveAspectRatio="xMinYMid meet">
        <path
          className="journey-route-base"
          d="M12 14 L12 104"
        />
        <path
          ref={pathRef}
          className="journey-route-progress"
          d="M12 14 L12 104"
        />
        {nodes.map((n, i) => (
          <g key={i}>
            <circle
              ref={(el) => { nodeRefs.current[i] = el; }}
              className="journey-node"
              cx={n.x}
              cy={n.y}
              r="2.1"
            />
            <text
              ref={(el) => { labelRefs.current[i] = el; }}
              className="journey-label"
              x="20"
              y={n.y + 1.4}
            >
              {n.label}
            </text>
          </g>
        ))}
      </svg>
    </div>
  );
};

// ============================================
// Reveal-on-scroll helper (IntersectionObserver)
// ============================================
const useRevealOnScroll = (selector = '.fade-up', threshold = 0.15) => {
  useEffect(() => {
    const els = document.querySelectorAll(selector);
    if (!els.length) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add('is-in');
          io.unobserve(e.target);
        }
      });
    }, { threshold, rootMargin: '0px 0px -50px 0px' });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, [selector, threshold]);
};

// ============================================
// Arrow icon
// ============================================
const ArrowRight = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M5 12h14M13 6l6 6-6 6" />
  </svg>
);

// ============================================
// TWEAKS PANEL
// ============================================
const TweaksPanel = ({ state, setState }) => {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const onMsg = (e) => {
      if (!e.data) return;
      if (e.data.type === '__activate_edit_mode') setVisible(true);
      if (e.data.type === '__deactivate_edit_mode') setVisible(false);
    };
    window.addEventListener('message', onMsg);
    // Announce
    try {
      window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    } catch(_) {}
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const update = (patch) => {
    setState((s) => ({ ...s, ...patch }));
    try {
      window.parent.postMessage({ type: '__edit_mode_set_keys', edits: patch }, '*');
    } catch(_) {}
  };

  if (!visible) return null;

  const heroOpts = [
    { id: 'chaos', label: 'Cubos → Orden' },
    { id: 'dashboard', label: 'Dashboard en vivo' },
    { id: 'editorial', label: 'Editorial' },
  ];
  const scrollOpts = [
    { id: 'subtle', label: 'Sutil' },
    { id: 'medium', label: 'Medio' },
    { id: 'strong', label: 'Fuerte' },
  ];

  return (
    <div className="tweaks-panel is-visible">
      <h3>Tweaks <span className="tag">LIVE</span></h3>

      <div className="tweaks-group">
        <div className="tweaks-label">Variante de hero</div>
        <div className="tweaks-chips">
          {heroOpts.map((o) => (
            <button key={o.id}
              className={`tweaks-chip ${state.heroVariant === o.id ? 'is-active' : ''}`}
              onClick={() => update({ heroVariant: o.id })}>{o.label}</button>
          ))}
        </div>
      </div>

      <div className="tweaks-group">
        <div className="tweaks-label">Intensidad de scroll</div>
        <div className="tweaks-chips">
          {scrollOpts.map((o) => (
            <button key={o.id}
              className={`tweaks-chip ${state.scrollIntensity === o.id ? 'is-active' : ''}`}
              onClick={() => update({ scrollIntensity: o.id })}>{o.label}</button>
          ))}
        </div>
      </div>

      <div className="tweaks-group">
        <div className="tweaks-toggle">
          <div>
            <div className="tweaks-label" style={{ marginBottom: 2 }}>Wallpaper de gobernanza</div>
            <div style={{ fontSize: 11, color: 'var(--muted-fg)' }}>Rejilla que se afina con el scroll</div>
          </div>
          <div className={`tweaks-switch ${state.governanceWallpaper ? 'on' : ''}`}
               onClick={() => update({ governanceWallpaper: !state.governanceWallpaper })} />
        </div>
      </div>
    </div>
  );
};

// Expose to other bundles
Object.assign(window, { TalosMark, TalosLogoHorizontal, CursorWallpaper, Navbar, GovernanceWallpaper, JourneyPath, useRevealOnScroll, ArrowRight, TweaksPanel });
