// enhancements.jsx — Futuristic web features for Codexa
// CustomCursor · ScrollProgress · TiltCard · Typewriter · Aurora · AI Chat

const { useState: _useState, useEffect: _useEffect, useRef: _useRef, useLayoutEffect: _useLayoutEffect } = React;

/* ─────────────────────────────────────────────
   CUSTOM CURSOR — magnetic purple halo
   ───────────────────────────────────────────── */
function CustomCursor({ enabled }) {
  const dot = _useRef(null);
  const ring = _useRef(null);

  _useEffect(() => {
    if (!enabled) return;
    // Hide on touch devices
    if (matchMedia('(hover: none)').matches) return;

    let mx = window.innerWidth / 2, my = window.innerHeight / 2;
    let rx = mx, ry = my;
    let raf;
    const isHover = { current: false };

    const move = (e) => { mx = e.clientX; my = e.clientY; };
    const over = (e) => {
      const t = e.target;
      const interactive = t.closest && t.closest('a, button, input, textarea, select, [role=button], .cdx-project, .cdx-service');
      isHover.current = !!interactive;
      if (ring.current) {
        ring.current.classList.toggle('hover', !!interactive);
      }
    };

    const tick = () => {
      rx += (mx - rx) * 0.18;
      ry += (my - ry) * 0.18;
      if (dot.current) {
        dot.current.style.transform = `translate3d(${mx}px, ${my}px, 0) translate(-50%, -50%)`;
      }
      if (ring.current) {
        ring.current.style.transform = `translate3d(${rx}px, ${ry}px, 0) translate(-50%, -50%)`;
      }
      raf = requestAnimationFrame(tick);
    };

    window.addEventListener('mousemove', move, { passive: true });
    window.addEventListener('mouseover', over, { passive: true });
    document.body.classList.add('cdx-custom-cursor-on');
    raf = requestAnimationFrame(tick);

    return () => {
      window.removeEventListener('mousemove', move);
      window.removeEventListener('mouseover', over);
      document.body.classList.remove('cdx-custom-cursor-on');
      cancelAnimationFrame(raf);
    };
  }, [enabled]);

  if (!enabled) return null;
  return (
    <>
      <div ref={ring} className="cdx-cursor-ring" />
      <div ref={dot} className="cdx-cursor-dot" />
    </>
  );
}

/* ─────────────────────────────────────────────
   SCROLL PROGRESS — thin bar at top
   ───────────────────────────────────────────── */
function ScrollProgress() {
  const ref = _useRef(null);
  _useEffect(() => {
    let raf;
    const update = () => {
      const h = document.documentElement;
      const total = h.scrollHeight - window.innerHeight;
      const pct = total > 0 ? (window.scrollY / total) * 100 : 0;
      if (ref.current) ref.current.style.width = pct + '%';
    };
    const onScroll = () => { cancelAnimationFrame(raf); raf = requestAnimationFrame(update); };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', update);
    update();
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', update);
      cancelAnimationFrame(raf);
    };
  }, []);
  return (
    <div className="cdx-scroll-progress-bar-top">
      <div className="cdx-scroll-progress-bar-fill-top" ref={ref} />
    </div>
  );
}

/* ─────────────────────────────────────────────
   TILT — 3D tilt on hover (hook)
   ───────────────────────────────────────────── */
function useTilt(enabled = true, max = 8) {
  const ref = _useRef(null);
  _useEffect(() => {
    if (!enabled) return;
    if (matchMedia('(hover: none)').matches) return;
    const el = ref.current;
    if (!el) return;

    let raf;
    let rx = 0, ry = 0, tx = 0, ty = 0;
    const onMove = (e) => {
      const r = el.getBoundingClientRect();
      const px = (e.clientX - r.left) / r.width - 0.5;
      const py = (e.clientY - r.top) / r.height - 0.5;
      tx = py * -max;
      ty = px * max;
    };
    const onLeave = () => { tx = 0; ty = 0; };
    const tick = () => {
      rx += (tx - rx) * 0.12;
      ry += (ty - ry) * 0.12;
      el.style.transform = `perspective(1000px) rotateX(${rx}deg) rotateY(${ry}deg) translateZ(0)`;
      raf = requestAnimationFrame(tick);
    };
    el.addEventListener('mousemove', onMove);
    el.addEventListener('mouseleave', onLeave);
    raf = requestAnimationFrame(tick);
    return () => {
      el.removeEventListener('mousemove', onMove);
      el.removeEventListener('mouseleave', onLeave);
      cancelAnimationFrame(raf);
      if (el) el.style.transform = '';
    };
  }, [enabled, max]);
  return ref;
}

/* ─────────────────────────────────────────────
   TYPEWRITER — types out text, with caret
   ───────────────────────────────────────────── */
function Typewriter({ text, speed = 55, startDelay = 600, onDone }) {
  const [shown, setShown] = _useState('');
  _useEffect(() => {
    let i = 0;
    let t;
    const start = setTimeout(() => {
      const tick = () => {
        i++;
        setShown(text.slice(0, i));
        if (i < text.length) t = setTimeout(tick, speed);
        else onDone && onDone();
      };
      tick();
    }, startDelay);
    return () => { clearTimeout(start); clearTimeout(t); };
  }, [text, speed, startDelay]);
  return (
    <span className="cdx-typewriter">
      {shown}
      <span className="cdx-typewriter-caret" />
    </span>
  );
}

/* ─────────────────────────────────────────────
   AURORA — animated mesh gradient (CSS only)
   ───────────────────────────────────────────── */
function AuroraBackground() {
  return (
    <div className="cdx-aurora">
      <div className="cdx-aurora-blob b1" />
      <div className="cdx-aurora-blob b2" />
      <div className="cdx-aurora-blob b3" />
      <div className="cdx-aurora-blob b4" />
      <div className="cdx-aurora-grain" />
    </div>
  );
}

/* ─────────────────────────────────────────────
   AI CHAT — Claude-powered assistant
   ───────────────────────────────────────────── */
const CODEXA_SYSTEM_PROMPT = `Eres el asistente virtual de Codexa, un estudio de desarrollo de software de Uruguay.

INFORMACIÓN DE CODEXA:
- Eslogan: "Software. Solutions. Impact."
- Ubicación: Uruguay, 100% remoto
- Email: codexa.studiouy@gmail.com
- WhatsApp: +598 91 086 359
- Instagram: @codexa.group

SERVICIOS:
1. Sitios web a medida (landings, portfolios, corporativos) — stacks: Next.js, Astro, WordPress
2. Aplicaciones web (SaaS, dashboards, herramientas internas) — stacks: React, Node, Postgres
3. Software a medida (sistemas de gestión, integraciones) — APIs, MercadoPago, Stripe

PROYECTOS EN PRODUCCIÓN:
- Laborix (laborix.online): control de horarios y pagos para empresas, gestión de empleados y liquidaciones
- OneTicket (oneticket.world): venta y gestión de tickets para eventos, con QR de acceso
- Las Cañas Expo Car (laexpocar.com): sitio oficial del evento de expo de autos en Las Cañas

INSTRUCCIONES:
- Responde en español, conversacional y breve (1-3 oraciones máx).
- Si preguntan precios, di que dependen del proyecto y pide que llenen el formulario o escriban por WhatsApp.
- Si preguntan plazos, di que armamos una propuesta en 2-3 días.
- Si la pregunta es completamente off-topic, redirige amablemente.
- Nunca inventes información que no esté arriba.`;

function AIChat({ enabled }) {
  const [open, setOpen] = _useState(false);
  const [messages, setMessages] = _useState([
    { role: 'assistant', content: '¡Hola! Soy el asistente de Codexa. Preguntame lo que quieras sobre nuestros servicios, proyectos o cómo trabajamos. 👋' }
  ]);
  const [input, setInput] = _useState('');
  const [loading, setLoading] = _useState(false);
  const scrollRef = _useRef(null);

  _useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, loading]);

  const send = async () => {
    const text = input.trim();
    if (!text || loading) return;
    const newMsgs = [...messages, { role: 'user', content: text }];
    setMessages(newMsgs);
    setInput('');
    setLoading(true);
    try {
      const convo = newMsgs.map(m => ({ role: m.role, content: m.content }));
      const res = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ messages: convo, system: CODEXA_SYSTEM_PROMPT }),
      });
      const data = await res.json();
      const reply = data.reply || 'Disculpá, tuve un problema. Escribinos por WhatsApp al +598 91 086 359.';
      setMessages([...newMsgs, { role: 'assistant', content: reply.trim() }]);
    } catch (e) {
      setMessages([...newMsgs, { role: 'assistant', content: 'Disculpá, tuve un problema. Escribinos por WhatsApp al +598 91 086 359.' }]);
    } finally {
      setLoading(false);
    }
  };

  const onKey = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      send();
    }
  };

  if (!enabled) return null;

  return (
    <>
      {!open && (
        <div className="cdx-chat-label" onClick={() => setOpen(true)}>
          ✨ Probá nuestra IA integrada
        </div>
      )}
      <button
        className={"cdx-chat-fab " + (open ? 'open' : '')}
        onClick={() => setOpen(o => !o)}
        aria-label={open ? 'Cerrar chat' : 'Abrir chat'}
      >
        {open ? (
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6l12 12M6 18L18 6"/></svg>
        ) : (
          <>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M21 11.5a8.38 8.38 0 01-.9 3.8 8.5 8.5 0 01-7.6 4.7 8.38 8.38 0 01-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 01-.9-3.8 8.5 8.5 0 014.7-7.6 8.38 8.38 0 013.8-.9h.5a8.48 8.48 0 018 8v.5z"/>
            </svg>
            <span className="cdx-chat-fab-pulse" />
          </>
        )}
      </button>

      {open && (
        <div className="cdx-chat-panel">
          <div className="cdx-chat-header">
            <div className="cdx-chat-avatar">
              <img src="assets/codexa-icon.png" alt="" />
            </div>
            <div>
              <div className="cdx-chat-title">Codexa AI</div>
              <div className="cdx-chat-status"><span className="cdx-chat-status-dot" />Online ahora</div>
            </div>
          </div>
          <div className="cdx-chat-messages" ref={scrollRef}>
            {messages.map((m, i) => (
              <div key={i} className={"cdx-chat-msg cdx-chat-msg-" + m.role}>
                {m.content}
              </div>
            ))}
            {loading && (
              <div className="cdx-chat-msg cdx-chat-msg-assistant cdx-chat-typing">
                <span /><span /><span />
              </div>
            )}
          </div>
          <div className="cdx-chat-input-row">
            <input
              type="text"
              placeholder="Preguntá algo…"
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={onKey}
              disabled={loading}
            />
            <button onClick={send} disabled={loading || !input.trim()} aria-label="Enviar">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/></svg>
            </button>
          </div>
          <div className="cdx-chat-footer">
            Powered by Groq · No es asesoramiento legal/financiero
          </div>
        </div>
      )}
    </>
  );
}

// Export to window for use in app.jsx
Object.assign(window, {
  CustomCursor, ScrollProgress, useTilt, Typewriter, AuroraBackground, AIChat
});
