// Shared components — Navbar, Footer, primitives, icons
const { useState, useEffect, useRef, useMemo, useCallback } = React;

const WA_NUMBER = '5215511125961';
const WA_BASE = `https://wa.me/${WA_NUMBER}`;
const waLink = (msg) => msg ? `${WA_BASE}?text=${encodeURIComponent(msg)}` : WA_BASE;

// ───────────────────────────── Theme System ─────────────────────────────
const THEMES = {
  artista: {
    id: 'artista', label: 'Artista / Músico', emoji: '🎵', tagline: 'Crea. Comparte. Conecta.',
    bgPrimary: '#0C0A0F', bgSurface: '#130F1C', border: '#2A1F3D',
    accent: '#C084FC', accentSoft: 'rgba(192,132,252,0.12)',
    text: '#F3EEFF', textMuted: '#9B8EC4', accentRGB: [192, 132, 252],
    bodyGradient: `radial-gradient(1400px 700px at 30% -15%, rgba(192,132,252,0.09) 0%, transparent 55%),
      radial-gradient(900px 500px at 85% 25%, rgba(192,132,252,0.05) 0%, transparent 55%),
      radial-gradient(600px 300px at 10% 80%, rgba(139,92,246,0.06) 0%, transparent 60%)`,
    copy: {
      heroPart1: 'Tu música merece', heroPart2: 'una presencia real.',
      heroSub: 'Creo sitios web para artistas, músicos y creativos que quieren ser encontrados y contratados. Sin plantillas genéricas.',
      heroChips: ['Entrega en 7 días', 'Diseño que te representa', 'Para conciertos y clases'],
      badge: 'Para Artistas & Músicos',
      ctaWA: 'Hola Cristian, soy músico/artista y quiero un sitio web que represente mi trabajo.',
    },
  },
  emprendedor: {
    id: 'emprendedor', label: 'Emprendedor / Startup', emoji: '🚀', tagline: 'Lanza. Escala. Convierte.',
    bgPrimary: '#080C12', bgSurface: '#0D1320', border: '#1A2540',
    accent: '#38BDF8', accentSoft: 'rgba(56,189,248,0.12)',
    text: '#E8F4FF', textMuted: '#6B8CA8', accentRGB: [56, 189, 248],
    bodyGradient: `radial-gradient(1200px 600px at 50% -10%, rgba(56,189,248,0.07) 0%, transparent 60%),
      radial-gradient(800px 400px at 90% 20%, rgba(56,189,248,0.04) 0%, transparent 60%)`,
    copy: {
      heroPart1: 'Tu startup necesita', heroPart2: 'clientes desde el día 1.',
      heroSub: 'Lanzo tu landing en menos de 10 días y automatizo tu captación de leads. Para founders que no tienen tiempo que perder.',
      heroChips: ['MVP en 5-10 días', 'Automatización incluida', 'Integración CRM'],
      badge: 'Para Emprendedores & Startups',
      ctaWA: 'Hola Cristian, tengo una startup y necesito una landing que convierta leads.',
    },
  },
  empresa: {
    id: 'empresa', label: 'Empresa / Corporativo', emoji: '🏢', tagline: 'Profesional. Confiable. Escalable.',
    bgPrimary: '#080B0A', bgSurface: '#0D1210', border: '#1A2820',
    accent: '#34D399', accentSoft: 'rgba(52,211,153,0.12)',
    text: '#E8FFF5', textMuted: '#6B9A82', accentRGB: [52, 211, 153],
    bodyGradient: `radial-gradient(1200px 600px at 50% -10%, rgba(52,211,153,0.06) 0%, transparent 60%),
      radial-gradient(800px 400px at 90% 20%, rgba(52,211,153,0.03) 0%, transparent 60%)`,
    copy: {
      heroPart1: 'Tu empresa merece', heroPart2: 'una imagen que vende.',
      heroSub: 'Diseño sitios web corporativos y automatizo procesos de captación. Para negocios que quieren verse profesionales sin pagar precios de agencia.',
      heroChips: ['Entrega en 10 días', 'Dominio + hosting', 'Correo corporativo'],
      badge: 'Para Empresas & Corporativos',
      ctaWA: 'Hola Cristian, tengo una empresa y necesito un sitio web profesional.',
    },
  },
  restaurante: {
    id: 'restaurante', label: 'Restaurante / Negocio local', emoji: '🍽️', tagline: 'Más mesas. Más pedidos.',
    bgPrimary: '#0F0A06', bgSurface: '#1A1008', border: '#2D1E0A',
    accent: '#FB923C', accentSoft: 'rgba(251,146,60,0.12)',
    text: '#FFF7EE', textMuted: '#A07850', accentRGB: [251, 146, 60],
    bodyGradient: `radial-gradient(1200px 600px at 50% -10%, rgba(251,146,60,0.07) 0%, transparent 60%),
      radial-gradient(800px 400px at 90% 20%, rgba(251,146,60,0.03) 0%, transparent 60%)`,
    copy: {
      heroPart1: 'Más clientes para', heroPart2: 'tu negocio local.',
      heroSub: 'Diseño sitios web y automatizo pedidos por WhatsApp para restaurantes, pastelerías y negocios locales. Entrega rápida, presupuesto real.',
      heroChips: ['Catálogo en línea', 'Pedidos por WhatsApp', 'Listo en 5 días'],
      badge: 'Para Restaurantes & Negocios Locales',
      ctaWA: 'Hola Cristian, tengo un restaurante/negocio local y quiero más clientes en línea.',
    },
  },
};

const ThemeCtx = React.createContext(null);

function applyTheme(theme) {
  const r = document.documentElement.style;
  r.setProperty('--bg-primary',  theme.bgPrimary);
  r.setProperty('--bg-surface',  theme.bgSurface);
  r.setProperty('--border',      theme.border);
  r.setProperty('--accent',      theme.accent);
  r.setProperty('--accent-soft', theme.accentSoft);
  r.setProperty('--text',        theme.text);
  r.setProperty('--text-muted',  theme.textMuted);
  r.setProperty('--accent-r',    theme.accentRGB[0]);
  r.setProperty('--accent-g',    theme.accentRGB[1]);
  r.setProperty('--accent-b',    theme.accentRGB[2]);
  document.body.style.backgroundImage = theme.bodyGradient;
  document.body.style.backgroundColor = theme.bgPrimary;
}

function getInitialType() {
  try {
    const saved = localStorage.getItem('cs-client-type');
    if (saved && THEMES[saved]) return saved;
  } catch(e) {}
  try {
    const params = new URLSearchParams(window.location.search);
    const tipo = params.get('tipo');
    if (tipo && THEMES[tipo]) {
      try { localStorage.setItem('cs-client-type', tipo); } catch(e) {}
      return tipo;
    }
  } catch(e) {}
  return null;
}

function ThemeProvider({ children }) {
  const [clientType, setClientTypeRaw] = useState(getInitialType);
  const [showSelector, setShowSelector] = useState(!getInitialType());

  const setClientType = (id, persist = true) => {
    setClientTypeRaw(id);
    setShowSelector(false);
    if (persist) {
      try { localStorage.setItem('cs-client-type', id); } catch(e) {}
    }
    applyTheme(THEMES[id]);
  };

  React.useLayoutEffect(() => {
    const t = clientType ? THEMES[clientType] : THEMES.artista;
    applyTheme(t);
  }, [clientType]);

  const theme = clientType ? THEMES[clientType] : THEMES.artista;

  return (
    <ThemeCtx.Provider value={{ clientType, theme, setClientType, showSelector, setShowSelector }}>
      {showSelector && <ClientSelector onSelect={setClientType}/>}
      {!showSelector && <ThemeSwitcher onOpen={() => setShowSelector(true)}/>}
      {children}
    </ThemeCtx.Provider>
  );
}

function ClientSelector({ onSelect }) {
  const [hovered, setHovered] = useState(null);
  return (
    <div
      style={{
        position: 'fixed', inset: 0, zIndex: 9999,
        background: 'rgba(9,8,15,0.88)',
        backdropFilter: 'blur(10px)',
        WebkitBackdropFilter: 'blur(10px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: '24px',
      }}
    >
      <div
        className="anim-fadeUp"
        style={{
          background: 'rgba(13,11,22,0.80)',
          backdropFilter: 'blur(24px) saturate(160%)',
          WebkitBackdropFilter: 'blur(24px) saturate(160%)',
          border: '0.5px solid rgba(255,255,255,0.09)',
          boxShadow: '0 32px 80px rgba(0,0,0,0.55), 0 0 0 0.5px rgba(255,255,255,0.04)',
          borderRadius: '20px',
          padding: '40px 36px 32px',
          maxWidth: '520px',
          width: '100%',
        }}
      >
        <div style={{ textAlign: 'center', marginBottom: '28px' }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            width: '44px', height: '44px', borderRadius: '12px', marginBottom: '16px',
            background: 'var(--accent-soft)', border: '0.5px solid var(--accent)',
          }}>
            <span style={{ fontWeight: 700, fontSize: '16px', color: 'var(--accent)' }}>CS</span>
          </div>
          <h2 style={{ fontSize: '22px', fontWeight: 700, color: 'var(--text)', marginBottom: '8px', letterSpacing: '-0.02em' }}>
            Bienvenido
          </h2>
          <p style={{ fontSize: '14px', color: 'var(--text-muted)', lineHeight: '1.5' }}>
            ¿Para qué tipo de proyecto necesitas ayuda?
          </p>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '20px' }}>
          {Object.values(THEMES).map(t => (
            <button
              key={t.id}
              onClick={() => onSelect(t.id)}
              onMouseEnter={() => setHovered(t.id)}
              onMouseLeave={() => setHovered(null)}
              style={{
                background: hovered === t.id ? `rgba(${t.accentRGB[0]},${t.accentRGB[1]},${t.accentRGB[2]},0.08)` : 'rgba(255,255,255,0.02)',
                border: `0.5px solid ${hovered === t.id ? t.accent : 'rgba(255,255,255,0.07)'}`,
                borderRadius: '12px',
                padding: '16px 14px',
                textAlign: 'left',
                cursor: 'pointer',
                transition: 'border-color .2s ease, background .2s ease, transform .15s ease',
                transform: hovered === t.id ? 'translateY(-2px)' : 'none',
              }}
            >
              <div style={{ fontSize: '26px', marginBottom: '8px', lineHeight: 1 }}>{t.emoji}</div>
              <div style={{ fontSize: '13px', fontWeight: 600, color: 'var(--text)', marginBottom: '3px' }}>{t.label}</div>
              <div style={{ fontSize: '11px', color: 'var(--text-muted)' }}>{t.tagline}</div>
            </button>
          ))}
        </div>

        <div style={{ textAlign: 'center' }}>
          <button
            onClick={() => onSelect('artista', false)}
            style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: '13px', color: 'var(--text-muted)', display: 'inline-flex', alignItems: 'center', gap: '6px' }}
          >
            Solo explorar →
          </button>
        </div>
      </div>
    </div>
  );
}

function ThemeSwitcher({ onOpen }) {
  const [hovered, setHovered] = useState(false);
  return (
    <button
      onClick={onOpen}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      title="Cambiar perfil"
      style={{
        position: 'fixed', bottom: '20px', left: '20px', zIndex: 9000,
        background: hovered ? 'var(--bg-surface)' : 'rgba(13,11,22,0.7)',
        border: `0.5px solid ${hovered ? 'var(--accent)' : 'var(--border)'}`,
        borderRadius: '999px',
        padding: '7px 13px',
        fontSize: '12px', fontWeight: 600,
        color: hovered ? 'var(--accent)' : 'var(--text-muted)',
        cursor: 'pointer',
        backdropFilter: 'blur(10px)',
        WebkitBackdropFilter: 'blur(10px)',
        transition: 'all .2s ease',
        display: 'flex', alignItems: 'center', gap: '6px',
      }}
    >
      ⚡ Cambiar perfil
    </button>
  );
}

const useClientCopy = () => {
  const ctx = React.useContext(ThemeCtx);
  return ctx ? ctx.theme.copy : THEMES.artista.copy;
};

// ───────────────────────────── Router (custom, hash-based) ─────────────────────────────
const RouterCtx = React.createContext({ path: '/', navigate: () => {} });

function RouterProvider({ children }) {
  const [path, setPath] = useState(() => {
    const h = window.location.hash.replace(/^#/, '');
    return h || '/';
  });
  useEffect(() => {
    const onHash = () => {
      const h = window.location.hash.replace(/^#/, '') || '/';
      setPath(h);
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('hashchange', onHash);
    if (!window.location.hash) window.location.hash = '/';
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  const navigate = useCallback((to) => {
    if (to.startsWith('http')) { window.open(to, '_blank'); return; }
    window.location.hash = to;
  }, []);
  return <RouterCtx.Provider value={{ path, navigate }}>{children}</RouterCtx.Provider>;
}
const useRouter = () => React.useContext(RouterCtx);

function Link({ to, children, className = '', external = false, ...rest }) {
  const { navigate } = useRouter();
  const onClick = (e) => {
    if (external) return; // let it open natively
    e.preventDefault();
    navigate(to);
  };
  const href = external ? to : `#${to}`;
  return <a href={href} onClick={onClick} className={className} target={external ? '_blank' : undefined} rel={external ? 'noreferrer' : undefined} {...rest}>{children}</a>;
}

// ───────────────────────────── Icons (minimal stroke set) ─────────────────────────────
const Icon = {
  arrow: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12h14M13 6l6 6-6 6"/></svg>,
  wa: (p) => <svg viewBox="0 0 24 24" fill="currentColor" {...p}><path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.1-.7.1-.2.3-.7.9-.9 1.1-.2.2-.3.2-.6.1-.3-.1-1.2-.4-2.3-1.4-.9-.8-1.4-1.7-1.6-2-.2-.3 0-.5.1-.6.1-.1.3-.3.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5 0-.1-.7-1.6-.9-2.2-.2-.6-.5-.5-.6-.5h-.5c-.2 0-.5.1-.7.3-.2.3-1 1-1 2.3 0 1.4 1 2.7 1.1 2.9.1.2 2 3.1 4.9 4.3.7.3 1.2.5 1.6.6.7.2 1.3.2 1.8.1.6-.1 1.7-.7 1.9-1.3.2-.7.2-1.2.2-1.3-.1-.2-.3-.2-.6-.3z M12 2C6.5 2 2 6.5 2 12c0 1.7.5 3.4 1.3 4.8L2 22l5.4-1.3c1.3.7 2.9 1.1 4.6 1.1 5.5 0 10-4.5 10-10S17.5 2 12 2zm0 18.3c-1.5 0-3-.4-4.2-1.2l-.3-.2-3.1.8.8-3-.2-.3C4.2 15.1 3.8 13.6 3.8 12c0-4.5 3.7-8.2 8.2-8.2 4.5 0 8.2 3.7 8.2 8.2 0 4.5-3.7 8.3-8.2 8.3z"/></svg>,
  menu: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" {...p}><path d="M4 7h16M4 12h16M4 17h16"/></svg>,
  close: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" {...p}><path d="M6 6l12 12M18 6L6 18"/></svg>,
  check: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12l5 5L20 7"/></svg>,
  spark: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M5.6 18.4l2.8-2.8M15.6 8.4l2.8-2.8"/></svg>,
  layers: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 3l9 5-9 5-9-5 9-5z"/><path d="M3 13l9 5 9-5"/><path d="M3 18l9 5 9-5" opacity=".5"/></svg>,
  bolt: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M13 2L4 14h7l-1 8 9-12h-7l1-8z"/></svg>,
  mail: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 7 9-7"/></svg>,
  monitor: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="4" width="18" height="13" rx="2"/><path d="M8 21h8M12 17v4"/></svg>,
  workflow: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="3" width="6" height="6" rx="1"/><rect x="15" y="15" width="6" height="6" rx="1"/><path d="M9 6h6a3 3 0 0 1 3 3v6"/></svg>,
  globe: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></svg>,
  whatsapp: (p) => <svg viewBox="0 0 24 24" fill="currentColor" {...p}><path d="M19.05 4.91A10 10 0 0 0 4.07 18.5L3 22l3.62-.95a10 10 0 0 0 4.78 1.22h.01A10 10 0 0 0 19.05 4.91zM12.42 20.6h-.01a8.34 8.34 0 0 1-4.25-1.16l-.31-.18-2.15.56.57-2.1-.2-.32a8.35 8.35 0 1 1 15.46-4.43 8.35 8.35 0 0 1-9.11 7.63zm4.58-6.24c-.25-.13-1.49-.74-1.72-.82-.23-.08-.4-.13-.57.13-.17.25-.65.82-.8.98-.14.17-.29.19-.54.06-.25-.13-1.06-.39-2.02-1.25-.75-.67-1.25-1.49-1.4-1.74-.14-.25-.02-.39.1-.51.1-.11.25-.29.37-.43.13-.14.17-.25.25-.41.08-.17.04-.31-.02-.43-.06-.13-.57-1.37-.78-1.88-.21-.5-.42-.43-.57-.44h-.49a.92.92 0 0 0-.67.31c-.23.25-.88.86-.88 2.1 0 1.23.9 2.42 1.02 2.59.13.17 1.77 2.7 4.28 3.79.6.26 1.07.41 1.43.53.6.19 1.15.16 1.58.1.48-.07 1.49-.61 1.7-1.2.21-.59.21-1.1.15-1.2-.06-.1-.23-.17-.48-.29z"/></svg>,
  external: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M14 4h6v6M20 4l-9 9M10 6H6a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-4"/></svg>,
  trophy: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M8 4h8v6a4 4 0 0 1-8 0V4z"/><path d="M5 6H3v2a3 3 0 0 0 3 3M19 6h2v2a3 3 0 0 1-3 3M10 16h4M9 20h6M12 16v4"/></svg>,
  play: (p) => <svg viewBox="0 0 24 24" fill="currentColor" {...p}><path d="M8 5v14l11-7z"/></svg>,
  copy: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V6a2 2 0 0 1 2-2h9"/></svg>,
};

// ───────────────────────────── Navbar ─────────────────────────────
const NAV_LINKS = [
  { to: '/servicios', label: 'Servicios' },
  { to: '/automatizaciones', label: 'Automatizaciones' },
  { to: '/precios', label: 'Precios' },
  { to: '/portafolio', label: 'Portafolio' },
  { to: '/proceso', label: 'Proceso' },
  { to: '/blog', label: 'Notas' },
];

function Navbar() {
  const { path, navigate } = useRouter();
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => { setOpen(false); }, [path]);

  return (
    <header
      className="fixed top-0 inset-x-0 z-50"
      style={{
        background: scrolled ? 'rgba(9,8,15,0.75)' : 'var(--bg-primary)',
        backdropFilter: scrolled ? 'blur(14px) saturate(140%)' : 'none',
        WebkitBackdropFilter: scrolled ? 'blur(14px) saturate(140%)' : 'none',
        borderBottom: '0.5px solid var(--border)',
        transition: 'background .25s ease',
      }}
    >
      <div className="max-w-[1200px] mx-auto px-5 md:px-8 h-[68px] flex items-center justify-between">
        <Link to="/" className="flex items-center gap-2 group">
          <div className="w-9 h-9 rounded-lg grid place-items-center" style={{ background: 'var(--accent-soft)', border: '0.5px solid var(--accent)' }}>
            <span className="font-bold text-[15px]" style={{ color: 'var(--accent)' }}>CS</span>
          </div>
          <span className="hidden sm:inline text-[13px] text-muted font-medium">Cristian Salazar</span>
        </Link>

        <nav className="hidden md:flex items-center gap-1">
          {NAV_LINKS.map(l => (
            <Link key={l.to} to={l.to} className={`nav-link ${path.startsWith(l.to) ? 'active' : ''}`}>{l.label}</Link>
          ))}
        </nav>

        <div className="hidden md:flex items-center gap-3">
          <Link to="/contacto" className="btn-secondary !py-2 !px-4 text-sm">Contrátame</Link>
        </div>

        <button className="md:hidden w-10 h-10 grid place-items-center rounded-lg" style={{ border: '0.5px solid var(--border)' }} onClick={() => setOpen(v => !v)} aria-label="Menú">
          {open ? <Icon.close width="20" height="20"/> : <Icon.menu width="20" height="20"/>}
        </button>
      </div>

      {open && (
        <div className="md:hidden menu-drop" style={{ background: 'var(--bg-surface)', borderTop: '0.5px solid var(--border)' }}>
          <div className="px-5 py-4 flex flex-col gap-1">
            {NAV_LINKS.map(l => (
              <Link key={l.to} to={l.to} className={`nav-link !block ${path.startsWith(l.to) ? 'active' : ''}`}>{l.label}</Link>
            ))}
            <div className="pt-3">
              <Link to="/contacto" className="btn-primary w-full justify-center">Contrátame <Icon.arrow width="16" height="16"/></Link>
            </div>
          </div>
        </div>
      )}
    </header>
  );
}

// ───────────────────────────── Footer ─────────────────────────────
function Footer() {
  return (
    <footer className="mt-32" style={{ borderTop: '0.5px solid var(--border)' }}>
      <div className="max-w-[1200px] mx-auto px-5 md:px-8 py-14">
        <div className="grid md:grid-cols-12 gap-10">
          <div className="md:col-span-5">
            <Link to="/" className="inline-flex items-center gap-2">
              <div className="w-10 h-10 rounded-lg grid place-items-center" style={{ background: 'var(--accent-soft)', border: '0.5px solid var(--accent)' }}>
                <span className="font-bold" style={{ color: 'var(--accent)' }}>CS</span>
              </div>
              <span className="font-semibold">Cristian Salazar</span>
            </Link>
            <p className="mt-4 text-sm text-muted max-w-sm leading-relaxed">
              Diseño web y automatización con IA para emprendedores, artistas y profesionistas que quieren resultados reales.
            </p>
            <div className="mt-5 flex flex-wrap gap-2">
              <span className="chip">CDMX · 100% remoto</span>
              <span className="chip">Español · Inglés</span>
            </div>
          </div>

          <div className="md:col-span-3">
            <div className="label text-muted mb-3">Navegación</div>
            <ul className="space-y-2 text-sm">
              {[{to:'/',l:'Inicio'},...NAV_LINKS.map(n=>({to:n.to,l:n.label})),{to:'/contacto',l:'Contacto'}].map(n=>(
                <li key={n.to}><Link to={n.to} className="text-text hover:text-accent transition">{n.l}</Link></li>
              ))}
            </ul>
          </div>

          <div className="md:col-span-4">
            <div className="label text-muted mb-3">Contacto directo</div>
            <ul className="space-y-3 text-sm">
              <li className="flex items-center gap-3"><Icon.mail width="16" height="16" className="text-accent"/> <a className="hover:text-accent" href="mailto:cristian93salazar@gmail.com">cristian93salazar@gmail.com</a></li>
              <li className="flex items-center gap-3"><Icon.whatsapp width="16" height="16" className="text-accent"/> <a className="hover:text-accent" href={waLink()} target="_blank" rel="noreferrer">55 1112 5961</a></li>
              <li className="flex items-center gap-3"><Icon.globe width="16" height="16" className="text-accent"/> <span className="text-muted">cristiansalazar.com.mx</span></li>
            </ul>
          </div>
        </div>

        <div className="divider my-10"/>
        <div className="flex flex-col sm:flex-row items-center justify-between gap-3 text-xs text-muted">
          <div>© 2026 Cristian Salazar · CDMX</div>
          <div className="flex items-center gap-4">
            <Link to="/privacidad" className="hover:text-accent transition">Privacidad</Link>
            <Link to="/terminos" className="hover:text-accent transition">Términos</Link>
            <span className="flex items-center gap-2">
              <span className="inline-block w-1.5 h-1.5 rounded-full bg-green-400 pulse-dot"/> Disponible
            </span>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ───────────────────────────── Layout primitives ─────────────────────────────
function Section({ children, className = '', id }) {
  return (
    <section id={id} className={`max-w-[1200px] mx-auto px-5 md:px-8 ${className}`}>
      {children}
    </section>
  );
}

function SectionHeader({ label, title, sub, center = false }) {
  return (
    <div className={`mb-12 ${center ? 'text-center mx-auto max-w-2xl' : 'max-w-3xl'}`}>
      {label && <div className="badge mb-4">{label}</div>}
      <h2 className="text-3xl md:text-[40px] font-bold tracking-tight leading-[1.05]">{title}</h2>
      {sub && <p className="mt-4 text-muted text-lg leading-relaxed">{sub}</p>}
    </div>
  );
}

function Card({ children, className = '', as = 'div', ...rest }) {
  const Tag = as;
  return <Tag className={`card card-interactive p-6 ${className}`} {...rest}>{children}</Tag>;
}

function PromoBanner() {
  return (
    <div
      className="rounded-2xl p-6 md:p-8 flex flex-col md:flex-row items-start md:items-center justify-between gap-5"
      style={{
        background: 'linear-gradient(135deg, rgba(var(--accent-r),var(--accent-g),var(--accent-b),0.10) 0%, rgba(var(--accent-r),var(--accent-g),var(--accent-b),0.04) 100%)',
        border: '0.5px solid rgba(var(--accent-r),var(--accent-g),var(--accent-b),0.5)',
      }}
    >
      <div>
        <div className="badge mb-3">Oferta de lanzamiento</div>
        <div className="font-bold text-xl md:text-2xl tracking-tight">
          Primeros 3 clientes: <span className="text-accent">30% de descuento</span> + 1 mes de mantenimiento gratis.
        </div>
        <div className="text-muted text-sm mt-2">Aplica a Pro y Elite. Cupo limitado este trimestre.</div>
      </div>
      <a href={waLink('Hola Cristian, quiero aprovechar el descuento del 30% de los primeros 3 clientes.')} target="_blank" rel="noreferrer" className="btn-primary whitespace-nowrap">
        Quiero mi descuento <Icon.arrow width="16" height="16"/>
      </a>
    </div>
  );
}

function BrowserFrame({ url = 'https://manumoreno.mx', children, height = 460 }) {
  return (
    <div className="browser">
      <div className="browser-bar">
        <div className="flex gap-1.5">
          <span className="browser-dot"></span>
          <span className="browser-dot"></span>
          <span className="browser-dot"></span>
        </div>
        <div className="url-pill">
          <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="5" y="11" width="14" height="9" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>
          {url}
        </div>
        <div className="text-muted hidden sm:block"><Icon.external width="14" height="14"/></div>
      </div>
      <div style={{ height }}>{children}</div>
    </div>
  );
}

// Placeholder for the manumoreno.mx mockup (no iframe; original composition matching the brief feel)
function ManuMorenoMockup({ compact = false }) {
  const gold = '#C9A84C';
  const goldSoft = 'rgba(201,168,76,0.12)';
  return (
    <div className="w-full h-full relative overflow-hidden" style={{ background: '#080608' }}>
      {/* Fondo dorado atmosférico */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(900px 500px at 15% -10%, rgba(201,168,76,0.13) 0%, transparent 55%), radial-gradient(600px 400px at 90% 110%, rgba(201,168,76,0.07) 0%, transparent 60%)',
      }}/>
      {/* Grid sutil */}
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: `linear-gradient(rgba(201,168,76,0.04) 1px, transparent 1px), linear-gradient(90deg, rgba(201,168,76,0.04) 1px, transparent 1px)`,
        backgroundSize: '48px 48px',
      }}/>

      {/* Nav */}
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, padding: '14px 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '0.5px solid rgba(201,168,76,0.15)' }}>
        <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: gold, letterSpacing: '0.15em', fontWeight: 600 }}>MANU MORENO</span>
        <div style={{ display: 'flex', gap: 16 }}>
          {['Obra','Taller','Prensa'].map(l => (
            <span key={l} style={{ fontSize: 10, color: 'rgba(255,255,255,0.4)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>{l}</span>
          ))}
        </div>
      </div>

      {/* Hero content */}
      <div style={{ position: 'absolute', left: compact ? 16 : 28, right: compact ? 16 : 140, top: compact ? 50 : 70, display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: goldSoft, border: `0.5px solid rgba(201,168,76,0.3)`, borderRadius: 999, padding: '4px 10px', width: 'fit-content' }}>
          <span style={{ width: 5, height: 5, borderRadius: '50%', background: gold, display: 'inline-block' }}/>
          <span style={{ fontSize: 9, color: gold, fontWeight: 600, letterSpacing: '0.12em', textTransform: 'uppercase' }}>Latin Grammy Winner · 2016</span>
        </div>
        <div style={{ fontWeight: 800, lineHeight: 0.88, letterSpacing: '-0.03em', color: '#fff', fontSize: compact ? 32 : 52 }}>
          Compositor<br/>
          <span style={{ color: gold }}>Mexicano.</span>
        </div>
        <p style={{ fontSize: compact ? 10 : 12, color: 'rgba(255,255,255,0.5)', lineHeight: 1.6, maxWidth: 280 }}>
          Música original para cine, televisión y escena. Más de 20 años creando desde el centro del mundo.
        </p>
        <div style={{ display: 'flex', gap: 8, marginTop: 6 }}>
          <span style={{ fontSize: 10, background: gold, color: '#000', borderRadius: 6, padding: '5px 12px', fontWeight: 700 }}>Inscribirme</span>
          <span style={{ fontSize: 10, border: `0.5px solid rgba(201,168,76,0.4)`, color: gold, borderRadius: 6, padding: '5px 12px' }}>Ver catálogo</span>
        </div>
      </div>

      {/* Foto placeholder dorado */}
      {!compact && (
        <div style={{
          position: 'absolute', right: 20, top: 60, bottom: 30,
          width: 110,
          background: 'linear-gradient(180deg, rgba(201,168,76,0.15) 0%, rgba(201,168,76,0.05) 100%)',
          border: '0.5px solid rgba(201,168,76,0.2)',
          borderRadius: 12,
          display: 'flex', alignItems: 'flex-end', justifyContent: 'center', paddingBottom: 10,
        }}>
          <span style={{ fontSize: 8, color: 'rgba(201,168,76,0.4)', fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.08em' }}>FOTO</span>
        </div>
      )}

      {/* Footer stat */}
      <div style={{ position: 'absolute', bottom: 10, left: compact ? 16 : 28, display: 'flex', gap: 16 }}>
        {[['20+', 'Años'], ['Grammy', '2016'], ['MX/EN', 'Bilingüe']].map(([v, l]) => (
          <div key={l} style={{ textAlign: 'center' }}>
            <div style={{ fontSize: compact ? 10 : 12, fontWeight: 700, color: gold }}>{v}</div>
            <div style={{ fontSize: 8, color: 'rgba(255,255,255,0.3)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>{l}</div>
          </div>
        ))}
      </div>
      <div style={{ position: 'absolute', bottom: 10, right: 14, fontSize: 8, color: 'rgba(255,255,255,0.15)', fontFamily: 'JetBrains Mono, monospace' }}>manumoreno.mx</div>
    </div>
  );
}

function OrdenMockup({ compact = false }) {
  const blue = '#3B82F6';
  const blueSoft = 'rgba(59,130,246,0.12)';
  return (
    <div className="w-full h-full relative overflow-hidden" style={{ background: '#07090F' }}>
      {/* Fondo azul atmosférico */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(1000px 500px at 50% -20%, rgba(59,130,246,0.12) 0%, transparent 60%), radial-gradient(600px 400px at 90% 110%, rgba(59,130,246,0.06) 0%, transparent 60%)',
      }}/>
      {/* Grid tipo radar */}
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: `linear-gradient(rgba(59,130,246,0.05) 1px, transparent 1px), linear-gradient(90deg, rgba(59,130,246,0.05) 1px, transparent 1px)`,
        backgroundSize: '40px 40px',
      }}/>
      {/* Partículas simuladas */}
      {[{x:'15%',y:'25%'},{x:'75%',y:'18%'},{x:'45%',y:'65%'},{x:'88%',y:'55%'},{x:'30%',y:'78%'},{x:'60%',y:'40%'}].map((p,i) => (
        <div key={i} style={{ position:'absolute', left:p.x, top:p.y, width:2, height:2, borderRadius:'50%', background:blue, opacity:0.4 }}/>
      ))}

      {/* Nav */}
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, padding: '14px 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '0.5px solid rgba(59,130,246,0.2)', backdropFilter: 'blur(8px)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{ width: 22, height: 22, borderRadius: 4, background: blue, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <span style={{ fontSize: 10, fontWeight: 800, color: '#fff' }}>O</span>
          </div>
          <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: '#fff', letterSpacing: '0.12em', fontWeight: 600 }}>ORDEN SP</span>
        </div>
        <div style={{ display: 'flex', gap: 14 }}>
          {['Servicios','Nosotros','Contacto'].map(l => (
            <span key={l} style={{ fontSize: 9, color: 'rgba(255,255,255,0.4)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>{l}</span>
          ))}
        </div>
      </div>

      {/* Badge */}
      <div style={{ position: 'absolute', left: compact ? 16 : 28, top: compact ? 50 : 65, display: 'flex', flexDirection: 'column', gap: 10, right: compact ? 16 : 28 }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: blueSoft, border: `0.5px solid rgba(59,130,246,0.35)`, borderRadius: 999, padding: '4px 10px', width: 'fit-content' }}>
          <span style={{ width: 5, height: 5, borderRadius: '50%', background: blue, display: 'inline-block', boxShadow: `0 0 6px ${blue}` }}/>
          <span style={{ fontSize: 9, color: blue, fontWeight: 600, letterSpacing: '0.12em', textTransform: 'uppercase' }}>Seguridad con ORDEN</span>
        </div>
        <div style={{ fontWeight: 800, lineHeight: 0.9, letterSpacing: '-0.03em', color: '#fff', fontSize: compact ? 28 : 44 }}>
          Blindamos tu<br/>
          <span style={{ color: blue }}>actividad</span> y tu<br/>
          <span style={{ color: blue }}>vida.</span>
        </div>
        <p style={{ fontSize: compact ? 9 : 11, color: 'rgba(255,255,255,0.5)', lineHeight: 1.6, maxWidth: 300 }}>
          Servicios tácticos de protección con atención personalizada y capacidad de respuesta efectiva.
        </p>
        <div style={{ display: 'flex', gap: 8, marginTop: 4 }}>
          <span style={{ fontSize: 9, background: blue, color: '#fff', borderRadius: 6, padding: '5px 12px', fontWeight: 700, letterSpacing: '0.08em' }}>Ver servicios</span>
          <span style={{ fontSize: 9, border: `0.5px solid rgba(255,255,255,0.25)`, color: 'rgba(255,255,255,0.7)', borderRadius: 6, padding: '5px 12px' }}>Contactar</span>
        </div>
      </div>

      {/* Stats */}
      <div style={{ position: 'absolute', bottom: 14, left: compact ? 16 : 28, display: 'flex', gap: compact ? 14 : 22 }}>
        {[['+10', 'Años'], ['24/7', 'Operación'], ['3C', 'Certificación']].map(([v, l]) => (
          <div key={l}>
            <div style={{ fontSize: compact ? 11 : 14, fontWeight: 700, color: blue }}>{v}</div>
            <div style={{ fontSize: 8, color: 'rgba(255,255,255,0.3)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>{l}</div>
          </div>
        ))}
      </div>
      <div style={{ position: 'absolute', bottom: 10, right: 14, fontSize: 8, color: 'rgba(255,255,255,0.15)', fontFamily: 'JetBrains Mono, monospace' }}>ordenseguridadprivada.com</div>
    </div>
  );
}

// Export everything to window so other files can use it
Object.assign(window, {
  RouterProvider, useRouter, Link, Navbar, Footer,
  Section, SectionHeader, Card, PromoBanner, BrowserFrame, ManuMorenoMockup, OrdenMockup,
  Icon, WA_NUMBER, WA_BASE, waLink,
});
