/* eslint-disable */
const { Icon, Tool, WhinkLogo, Reveal } = window.Whink;
const { useState, useEffect, useRef } = React;

/* ============== PROCESS ============== */
function ProcessSection() {
  const steps = [
    ['01', 'Reunión inicial', 'Entendemos tu negocio en profundidad, identificamos los procesos a automatizar y definimos exactamente qué resolverá tu agente.'],
    ['02', 'Diseño y configuración', 'Diseñamos y configuramos tu agente IA junto con todo el sistema, integrándolo a tus canales, herramientas y bases de conocimiento.'],
    ['03', 'Iteración y ajustes', 'Probamos la primera versión, corregimos errores, refinamos respuestas y ponemos todo a punto antes del despliegue final.'],
    ['04', 'Implementación y seguimiento', 'Cuando todo funciona perfectamente, implementamos el agente de forma definitiva y hacemos seguimiento continuo de su rendimiento.'],
  ];
  return (
    <section id="proceso" className="section">
      <div className="container">
        <Reveal className="eyebrow">Cómo trabajamos</Reveal>
        <Reveal as="h2" className="h-section section-title" delay={80}>
          De la idea al agente funcionando, <span className="grad-text">en simples pasos</span>
        </Reveal>
        <Reveal as="p" className="lead section-sub" delay={140}>
          Nos encargamos de todo el proceso y trabajo técnico. Solo necesitamos tu conocimiento del negocio y tu validación en cada etapa.
        </Reveal>
        <div className="process-line">
          <div className="process-track" />
          {steps.map(([n, t, d], i) => (
            <Reveal key={n} className="process-step" delay={200 + i * 130}>
              <div className="process-num">{n}</div>
              <h3 className="h-card" style={{ marginTop: 16 }}>{t}</h3>
              <p className="muted" style={{ fontSize: 13.5, lineHeight: 1.55, marginTop: 8 }}>{d}</p>
            </Reveal>
          ))}
        </div>
      </div>
      <style>{`
        .process-line {
          margin-top: 64px;
          display: grid;
          grid-template-columns: repeat(4, 1fr);
          gap: 28px;
          position: relative;
        }
        .process-track {
          position: absolute;
          left: 8%; right: 8%;
          top: 24px; height: 1px;
          background: rgba(37,211,102,0.18);
          overflow: hidden;
        }
        .process-track::before {
          content: '';
          position: absolute;
          left: -25%; top: 0;
          width: 25%; height: 100%;
          background: linear-gradient(90deg, transparent, var(--green), transparent);
          animation: trackFlow 5s cubic-bezier(0.4, 0, 0.6, 1) infinite;
          filter: drop-shadow(0 0 6px rgba(37,211,102,0.45));
        }
        @keyframes trackFlow {
          0%   { left: -25%; }
          100% { left: 100%; }
        }
        .process-step { position: relative; }
        .process-num {
          width: 48px; height: 48px;
          border-radius: 50%;
          background: var(--bg);
          border: 1px solid rgba(37,211,102,0.4);
          display: flex; align-items: center; justify-content: center;
          color: var(--green);
          font-weight: 600; font-size: 15px;
          letter-spacing: -0.01em;
          position: relative; z-index: 1;
        }
        @media (max-width: 768px) {
          .process-line { grid-template-columns: 1fr; gap: 24px; }
          .process-track {
            left: 24px; top: 24px; bottom: 24px; right: auto;
            width: 1px; height: auto;
            background: linear-gradient(180deg, transparent, rgba(37,211,102,0.45), rgba(37,211,102,0.45), transparent);
          }
          .process-track::before { display: none; }
          .process-step { padding-left: 64px; }
          .process-num { position: absolute; left: 0; top: 0; }
        }
      `}</style>
    </section>
  );
}

/* ============== IN ACTION — phone with animated chat ============== */
function PhoneChat() {
  const SCRIPT = [
    { who: 'user', text: 'Hola, quería saber si tienen turno disponible para esta semana' },
    { who: 'bot', text: '¡Hola! Sí, tengo disponibilidad. ¿Preferís un día específico?' },
    { who: 'user', text: 'El jueves por la tarde estaría bien' },
    { who: 'bot', text: 'Perfecto. Para el jueves tengo 15:30 hs o 17:00 hs. ¿Cuál te queda mejor?' },
    { who: 'user', text: '17 hs esta bien' },
    { who: 'bot', text: 'Listo, te agendé el turno el jueves a las 17:00 hs. Te envío un recordatorio el día anterior.' },
  ];
  const [shown, setShown] = useState([]);
  const [typing, setTyping] = useState(false);
  const [started, setStarted] = useState(false);
  const phoneRef = useRef(null);
  const indexRef = useRef(0);
  const mountedRef = useRef(true);

  useEffect(() => {
    const el = phoneRef.current;
    if (!el) return;
    const observer = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) { setStarted(true); observer.disconnect(); } },
      { threshold: 0.3 }
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, []);

  useEffect(() => {
    if (!started) return;
    mountedRef.current = true;
    let timers = [];
    const next = () => {
      if (!mountedRef.current) return;
      const i = indexRef.current;
      if (i >= SCRIPT.length) return;
      const msg = SCRIPT[i];
      const showDelay = msg.who === 'user' ? 600 : 0;
      timers.push(setTimeout(() => {
        if (msg.who === 'bot') setTyping(true);
        timers.push(setTimeout(() => {
          if (!mountedRef.current) return;
          setTyping(false);
          setShown(s => [...s, msg]);
          indexRef.current = i + 1;
          timers.push(setTimeout(next, msg.who === 'bot' ? 1100 : 800));
        }, msg.who === 'bot' ? 1300 : 0));
      }, showDelay));
    };
    timers.push(setTimeout(next, 800));
    return () => { mountedRef.current = false; timers.forEach(clearTimeout); };
  }, [started]);

  return (
    <div className="phone" ref={phoneRef}>
      <div className="phone-glow" />
      <div className="phone-body">
        <div className="phone-island" />
        <div className="phone-screen">
          <div className="phone-status">
            <span>9:41</span>
            <span style={{ display: 'inline-flex', gap: 4, alignItems: 'center' }}>
              <svg width="14" height="10" viewBox="0 0 14 10" fill="currentColor"><rect x="0" y="6" width="2" height="4"/><rect x="4" y="4" width="2" height="6"/><rect x="8" y="2" width="2" height="8"/><rect x="12" y="0" width="2" height="10"/></svg>
              <svg width="16" height="10" viewBox="0 0 16 10" fill="none" stroke="currentColor" strokeWidth="1"><rect x="1" y="2" width="11" height="6" rx="1.5"/><rect x="13" y="4" width="1.5" height="2"/><rect x="2" y="3" width="6" height="4" fill="currentColor"/></svg>
            </span>
          </div>
          <div className="phone-chat-head">
            <div className="phone-avatar"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></svg></div>
            <div>
              <strong>Martín Díaz</strong>
            </div>
          </div>
          <div className="phone-chat-body">
            {shown.map((m, i) => (
              <div key={i} className={`pbubble ${m.who}`}>{m.text}</div>
            ))}
            {typing && (
              <div className="pbubble bot typing">
                <span /> <span /> <span />
              </div>
            )}
          </div>
          <div className="phone-input">
            <span className="dim">Escribir mensaje…</span>
            <span className="phone-send"><Icon.Arrow width="14" height="14" /></span>
          </div>
        </div>
      </div>
      <style>{`
        .phone {
          position: relative;
          width: 100%;
          max-width: min(320px, calc(100vw - 48px));
          margin: 0 auto;
          aspect-ratio: 320 / 660;
        }
        .phone-glow {
          position: absolute; inset: -30px;
          background: radial-gradient(ellipse at 30% 30%, rgba(37,211,102,0.3), transparent 60%);
          filter: blur(40px);
          z-index: 0;
        }
        .phone-body {
          position: relative; z-index: 1;
          width: 100%; height: 100%;
          background: #050505;
          border-radius: 44px;
          padding: 12px;
          border: 1px solid #1a1a1a;
          box-shadow: 0 0 0 2px #0a0a0a, 0 30px 80px -20px rgba(0,0,0,0.7), inset 0 0 1px rgba(255,255,255,0.1);
        }
        .phone-island {
          position: absolute;
          top: 18px; left: 50%; transform: translateX(-50%);
          width: 100px; height: 28px;
          background: #000;
          border-radius: 20px;
          z-index: 5;
        }
        .phone-screen {
          width: 100%; height: 100%;
          background: linear-gradient(180deg, #0a0a0a 0%, #0d0d0d 100%);
          border-radius: 32px;
          overflow: hidden;
          display: flex; flex-direction: column;
          color: #fff;
          position: relative;
        }
        .phone-status {
          display: flex; justify-content: space-between; align-items: center;
          padding: 14px 28px 6px;
          font-size: 13px; font-weight: 600;
          color: #fff;
        }
        .phone-chat-head {
          display: flex; align-items: center; gap: 10px;
          padding: 14px 16px;
          border-bottom: 1px solid rgba(255,255,255,0.06);
          background: rgba(255,255,255,0.02);
        }
        .phone-chat-head strong { font-size: 12.5px; display: block; color: #fff; }
        .phone-avatar {
          width: 34px; height: 34px;
          border-radius: 50%;
          background: #1a1a1a;
          color: var(--fg-dim);
          display: flex; align-items: center; justify-content: center;
          border: 1px solid rgba(255,255,255,0.12);
        }
        .phone-chat-body {
          flex: 1;
          padding: 14px 14px;
          display: flex; flex-direction: column;
          gap: 6px;
          overflow-y: auto;
          scrollbar-width: none;
        }
        .phone-chat-body::-webkit-scrollbar { display: none; }
        .pbubble {
          max-width: 78%;
          padding: 8px 12px;
          border-radius: 14px;
          font-size: 12.5px;
          line-height: 1.4;
          animation: bubbleIn 280ms cubic-bezier(0.22,1,0.36,1);
          color: #fff;
        }
        @keyframes bubbleIn {
          from { opacity: 0; transform: translateY(6px) scale(0.96); }
          to { opacity: 1; transform: translateY(0) scale(1); }
        }
        .pbubble.user {
          align-self: flex-start;
          background: rgba(255,255,255,0.08);
          border-bottom-left-radius: 4px;
        }
        .pbubble.bot {
          align-self: flex-end;
          background: rgba(37,211,102,0.18);
          border: 1px solid rgba(37,211,102,0.3);
          border-bottom-right-radius: 4px;
        }
        .pbubble.typing {
          display: inline-flex; gap: 4px; align-items: center; padding: 11px 14px;
        }
        .pbubble.typing span {
          width: 5px; height: 5px;
          background: var(--green);
          border-radius: 50%;
          animation: typing 1.2s infinite ease-in-out;
        }
        .pbubble.typing span:nth-child(2) { animation-delay: 0.15s; }
        .pbubble.typing span:nth-child(3) { animation-delay: 0.3s; }
        .phone-input {
          padding: 12px 14px calc(14px + env(safe-area-inset-bottom));
          border-top: 1px solid rgba(255,255,255,0.06);
          display: flex; align-items: center; justify-content: space-between;
          font-size: 12px;
        }
        .phone-send {
          width: 28px; height: 28px;
          border-radius: 50%;
          background: var(--green);
          color: #002b10;
          display: flex; align-items: center; justify-content: center;
        }
      `}</style>
    </div>
  );
}

function InActionSection() {
  const bullets = [
    ['Comprende la intención', 'Detecta que el cliente quiere reservar un turno, no solo consultar.'],
    ['Consulta tu agenda en vivo', 'Lee disponibilidad real desde Google Calendar o la agenda que utilices.'],
    ['Confirma y agenda', 'Reserva el turno y programa el recordatorio sin intervención humana.'],
  ];
  return (
    <section id="accion" className="section">
      <div className="glow" style={{ width: 600, height: 600, top: 100, right: -200 }} />
      <div className="container">
        <Reveal className="eyebrow">En acción</Reveal>
        <Reveal as="h2" className="h-section section-title" delay={80}>
          Mirá cómo trabaja un Agente IA<br />en una <span className="grad-text">conversación real</span>
        </Reveal>
        <div className="action-grid">
          <Reveal variant="scale" delay={100}><PhoneChat /></Reveal>
          <div className="action-text">
            <Reveal as="h3" delay={180} className="h-section action-h" style={{ fontSize: 'clamp(28px, 3.4vw, 38px)' }}>Razona, decide y ejecuta</Reveal>
            <Reveal as="p" delay={320} className="lead" style={{ marginTop: 16 }}>
              El agente no solo responde: conversa e interpreta, entiende la intención, consulta tu agenda y reserva el turno, todo en un mismo flujo natural.
            </Reveal>
            <ul className="check-list">
              {bullets.map(([t, d], i) => (
                <Reveal as="li" key={t} delay={460 + i * 120}>
                  <span className="check"><Icon.Check width="13" height="13" /></span>
                  <div>
                    <strong>{t}</strong>
                    <p className="muted" style={{ fontSize: 13.5, margin: '4px 0 0' }}>{d}</p>
                  </div>
                </Reveal>
              ))}
            </ul>
          </div>
        </div>
      </div>
      <style>{`
        .action-grid {
          margin-top: 56px;
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 64px;
          align-items: center;
        }
        .action-text { max-width: 520px; }
        .check-list {
          list-style: none; padding: 0; margin: 32px 0 0;
          display: flex; flex-direction: column; gap: 18px;
        }
        .check-list li { display: flex; gap: 14px; align-items: flex-start; }
        .check {
          width: 24px; height: 24px; flex-shrink: 0;
          border-radius: 50%;
          background: rgba(37,211,102,0.15);
          color: var(--green);
          display: flex; align-items: center; justify-content: center;
          border: 1px solid rgba(37,211,102,0.3);
          margin-top: 2px;
        }
        .check-list strong { font-size: 15px; font-weight: 600; }
        @media (max-width: 1024px) {
          .action-grid { grid-template-columns: 1fr; gap: 48px; }
          .action-text { margin: 0 auto; }
        }
      `}</style>
    </section>
  );
}

window.WhinkParts = Object.assign(window.WhinkParts || {}, { ProcessSection, InActionSection });
