// bulltech_ website — shared helpers + header/hero sections
const DS = window.BulltechDesignSystem_fb9019;
const { Logo, Button, Badge, Stat, Card, Bull3D } = DS;

const CONFIG = Object.assign({
  whatsappNumber: '50256631375',
  contactEmail: 'hola@bulltechnologies.dev'
}, window.BULLTECH_CONFIG);

const wa = (msg) => `https://wa.me/${CONFIG.whatsappNumber}?text=${encodeURIComponent(msg)}`;
const WA_DEFAULT = wa('Hola Bull Technologies, quiero cotizar un proyecto digital.');

const REDUCED = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

// ---- Reveal: rise+fade on scroll, staggered ----
function Reveal({ delay = 0, children, style }) {
  const ref = React.useRef(null);
  const [shown, setShown] = React.useState(REDUCED);
  const [settled, setSettled] = React.useState(REDUCED);
  React.useEffect(() => {
    if (REDUCED) return;
    const el = ref.current;
    // Fail-open: if already in viewport on mount, or the observer never fires
    // (some embedded iframes), reveal anyway.
    const rect = el.getBoundingClientRect();
    if (rect.top < window.innerHeight && rect.bottom > 0) {
      const id = requestAnimationFrame(() => setShown(true));
      return () => cancelAnimationFrame(id);
    }
    const fallback = setTimeout(() => setShown(true), 900);
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setShown(true); clearTimeout(fallback); io.disconnect(); }
    }, { threshold: 0.15 });
    io.observe(el);
    return () => { io.disconnect(); clearTimeout(fallback); };
  }, []);
  // Once the entrance has had time to play, drop the animated properties
  // entirely so visibility never depends on a transition advancing.
  React.useEffect(() => {
    if (!shown || settled) return;
    const id = setTimeout(() => setSettled(true), delay + 560);
    return () => clearTimeout(id);
  }, [shown, settled, delay]);
  // After the settled re-render drops the styles, cancel any lingering
  // CSSTransition still applying the pre-reveal opacity/transform.
  React.useEffect(() => {
    if (!settled) return;
    const el = ref.current;
    if (el && el.getAnimations) el.getAnimations().forEach((a) => a.cancel());
  }, [settled]);
  if (settled) {
    return <div ref={ref} style={style}>{children}</div>;
  }
  return (
    <div
      ref={ref}
      style={{
        opacity: shown ? 1 : 0,
        transform: shown ? 'translateY(0)' : 'translateY(14px)',
        transition: `opacity 480ms var(--ease) ${delay}ms, transform 480ms var(--ease) ${delay}ms`,
        ...style,
      }}
    >
      {children}
    </div>
  );
}

// ---- Eyebrow ----
function Eyebrow({ children }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <span aria-hidden="true" style={{ color: 'var(--red)', fontSize: 8, lineHeight: 1 }}>◆</span>
      <span style={{ fontSize: 'var(--text-label)', fontWeight: 500, letterSpacing: 'var(--tracking-label)', textTransform: 'uppercase', color: 'var(--text-secondary)' }}>{children}</span>
    </div>
  );
}

// ---- Bull blueprint overlay (easter egg: click the header logo) ----
function BullOverlay({ onClose }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);
  return (
    <div
      onClick={onClose}
      role="dialog"
      aria-label="Toro bulltech_ en 3D"
      style={{
        position: 'fixed', inset: 0, zIndex: 200,
        background: 'var(--paper)',
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 18,
        animation: 'bt-rise var(--duration-slow) var(--ease) both',
        cursor: 'zoom-out',
      }}
    >
      <div aria-hidden="true" style={{ position: 'absolute', inset: 0, backgroundImage: 'linear-gradient(var(--ink) 1px, transparent 1px), linear-gradient(90deg, var(--ink) 1px, transparent 1px)', backgroundSize: '64px 64px', opacity: 0.05, pointerEvents: 'none' }}></div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, position: 'relative' }}>
        <span aria-hidden="true" style={{ color: 'var(--red)', fontSize: 8, lineHeight: 1 }}>◆</span>
        <span style={{ fontSize: 'var(--text-label)', fontWeight: 500, letterSpacing: 'var(--tracking-label)', textTransform: 'uppercase', color: 'var(--text-secondary)' }}>Blueprint · bulltech_</span>
      </div>
      <div onClick={(e) => e.stopPropagation()} style={{ position: 'relative', cursor: 'default' }}>
        <Bull3D size={380} hud />
      </div>
      <span style={{ position: 'relative', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-tertiary)' }}>arrastra para girar · Esc para cerrar</span>
      <button
        aria-label="Cerrar"
        onClick={onClose}
        style={{ position: 'absolute', top: 12, right: 12, width: 40, height: 40, background: 'none', border: '1px solid var(--line)', cursor: 'pointer', fontSize: 15, color: 'var(--text-secondary)', fontFamily: 'var(--font-sans)' }}
      >✕</button>
    </div>
  );
}

// ---- Header ----
function SiteHeader({ view, setView }) {
  const nav = ['Productos', 'Servicios', 'Estudio', 'Contacto'];
  const [bull, setBull] = React.useState(false);
  
  const handleLogoClick = () => {
    if (setView) setView('landing');
    else if (window.setWebsiteView) window.setWebsiteView('landing');
    setBull(true);
  };

  const handleNavClick = (e, item) => {
    e.preventDefault();
    if (setView) setView('landing');
    else if (window.setWebsiteView) window.setWebsiteView('landing');
    
    setTimeout(() => {
      if (item === 'Productos') document.getElementById('products')?.scrollIntoView({ behavior: 'smooth' });
      else if (item === 'Servicios') document.getElementById('services')?.scrollIntoView({ behavior: 'smooth' });
      else if (item === 'Estudio') document.getElementById('metrics')?.scrollIntoView({ behavior: 'smooth' });
      else if (item === 'Contacto') document.getElementById('contact')?.scrollIntoView({ behavior: 'smooth' });
    }, 100);
  };

  return (
    <header style={{ position: 'sticky', top: 0, zIndex: 50, background: 'rgba(255,255,255,0.9)', backdropFilter: 'blur(8px)', borderBottom: '1px solid var(--line)' }}>
      <div style={{ maxWidth: 'var(--container)', margin: '0 auto', padding: '0 24px', height: 64, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 24 }}>
        <button
          onClick={handleLogoClick}
          aria-label="Ver el toro en 3D"
          title="◆ blueprint"
          style={{ appearance: 'none', background: 'none', border: 'none', padding: 0, cursor: 'pointer', display: 'inline-flex' }}
        >
          <Logo variant="lockup" size={30} />
        </button>
        <nav style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <div className="bt-nav-links" style={{ gap: 28 }}>
            {nav.map((n) => (
              <a key={n} href="#" onClick={(e) => handleNavClick(e, n)} style={{ fontSize: 14, fontWeight: 500, color: 'var(--text-body)', textDecoration: 'none' }}
                onMouseEnter={(e) => { e.currentTarget.style.textDecoration = 'underline'; e.currentTarget.style.textUnderlineOffset = '4px'; }}
                onMouseLeave={(e) => { e.currentTarget.style.textDecoration = 'none'; }}
              >{n}</a>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            {view === 'generator' ? (
              <Button variant="secondary" size="sm" onClick={() => { if (setView) setView('landing'); else if (window.setWebsiteView) window.setWebsiteView('landing'); }}>← Volver</Button>
            ) : (
              <Button variant="secondary" size="sm" onClick={() => { if (setView) setView('generator'); else if (window.setWebsiteView) window.setWebsiteView('generator'); }}>Diseñar mi software ◆</Button>
            )}
            <Button variant="primary" size="sm" onClick={() => window.open(WA_DEFAULT, '_blank')}>Agendar demo</Button>
          </div>
        </nav>
      </div>
      {bull && ReactDOM.createPortal(<BullOverlay onClose={() => setBull(false)} />, document.body)}
    </header>
  );
}

// ---- Terminal panel (typed status board) ----
const TERMINAL_LINES = [
  { text: '$ bulltech --status', color: 'var(--ink)' },
  { text: '✓ alphavet      99.98% uptime', color: 'var(--ok)' },
  { text: '✓ dentos        99.97% uptime', color: 'var(--ok)' },
  { text: '✓ farmapp       99.99% uptime', color: 'var(--ok)' },
  { text: '✓ synapse-os    99.95% uptime', color: 'var(--ok)' },
  { text: '✓ lemigt        99.98% uptime', color: 'var(--ok)' },
  { text: '5 sistemas en producción', color: 'var(--ink-2)' },
];

function Terminal() {
  const [progress, setProgress] = React.useState(REDUCED ? Number.MAX_SAFE_INTEGER : 0);
  const total = TERMINAL_LINES.reduce((s, l) => s + l.text.length + 1, 0);

  React.useEffect(() => {
    if (REDUCED) return;
    let p = 0;
    const id = setInterval(() => {
      p += 3;
      setProgress(p);
      if (p >= total) clearInterval(id);
    }, 24);
    return () => clearInterval(id);
  }, []);

  let remaining = progress;
  const visible = TERMINAL_LINES.map((l) => {
    const take = Math.max(0, Math.min(l.text.length, remaining));
    remaining -= l.text.length + 1;
    return { ...l, shown: l.text.slice(0, take), done: take === l.text.length };
  });
  const doneAll = progress >= total;

  return (
    <div style={{ border: '1px solid var(--ink)', background: 'var(--paper)' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 14px', borderBottom: '1px solid var(--line)' }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-secondary)' }}>bulltech — produccion</span>
        <span aria-hidden="true" style={{ display: 'flex', gap: 5 }}>
          <span style={{ width: 7, height: 7, border: '1px solid var(--ink-3)' }}></span>
          <span style={{ width: 7, height: 7, border: '1px solid var(--ink-3)' }}></span>
          <span style={{ width: 7, height: 7, background: 'var(--red)' }}></span>
        </span>
      </div>
      <div style={{ padding: '16px 14px 18px', minHeight: 178 }}>
        {visible.map((l, i) => (
          l.shown ? (
            <div key={i} style={{ fontFamily: 'var(--font-mono)', fontSize: 13, lineHeight: 1.7, color: l.color, whiteSpace: 'pre' }}>
              {l.shown}
              {!doneAll && l.shown.length < l.text.length && <span style={{ color: 'var(--red)' }}>_</span>}
              {doneAll && i === TERMINAL_LINES.length - 1 && <span className="bt-cursor" style={{ color: 'var(--red)' }}>_</span>}
            </div>
          ) : null
        ))}
      </div>
    </div>
  );
}

// ---- Hero ----
function Hero() {
  return (
    <section style={{ borderBottom: '1px solid var(--line)', position: 'relative', overflow: 'hidden' }}>
      <div aria-hidden="true" style={{ position: 'absolute', inset: 0, backgroundImage: 'linear-gradient(var(--ink) 1px, transparent 1px), linear-gradient(90deg, var(--ink) 1px, transparent 1px)', backgroundSize: '64px 64px', opacity: 0.04, pointerEvents: 'none' }}></div>
      <div className="bt-hero-grid bt-hero-container">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
          <Reveal><Eyebrow>Digital Product Studio · Guatemala</Eyebrow></Reveal>
          <Reveal delay={80}>
            <h1 style={{ margin: 0, fontSize: 'var(--text-display)', fontWeight: 800, letterSpacing: 'var(--tracking-display)', lineHeight: 'var(--leading-display)', color: 'var(--text-body)' }}>
              Construimos los sistemas sobre los que operan los negocios<span className="bt-cursor" style={{ color: 'var(--red)' }}>_</span>
            </h1>
          </Reveal>
          <Reveal delay={160}>
            <p style={{ margin: 0, fontSize: 'var(--text-lead)', lineHeight: 1.55, color: 'var(--text-secondary)', maxWidth: 520 }}>
              Software vertical para clínicas, farmacias, laboratorios y comercio. Diseñado, construido y operado por bulltech_.
            </p>
          </Reveal>
          <Reveal delay={240}>
            <div style={{ display: 'flex', gap: 14 }}>
              <Button variant="primary" size="lg" arrow onClick={() => {
                if (window.setWebsiteView) window.setWebsiteView('generator');
              }}>Diseñar mi software ◆</Button>
              <Button variant="secondary" size="lg" onClick={() => window.open(WA_DEFAULT, '_blank')}>Agendar demo</Button>
            </div>
          </Reveal>
        </div>
        <Reveal delay={320}><Terminal /></Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { Reveal, Eyebrow, SiteHeader, Hero });
