/* ============================================================
   CentralAR.jsx — "Central Inteligente de Atendimento AR"
   Cena em camadas: Cliente (WhatsApp) → Agente IA AR → CRM/Agenda/
   Planilha/Equipe. Linhas curvas luminosas, partículas, dados em
   trânsito, tilt 3D no mouse, destaque do bloco mais próximo.
   ============================================================ */
const CentralAR = ({ tilt = { x: 0, y: 0 } }) => {
  const wrapRef = React.useRef(null);
  const waRef = React.useRef(null);
  const agentRef = React.useRef(null);
  const cardRefs = React.useRef([]);
  const [geo, setGeo] = React.useState(null);
  const [near, setNear] = React.useState(null);   // 'wa' | 'agent' | 0..3
  const [hovering, setHovering] = React.useState(false);
  const rafRef = React.useRef(0);

  const dests = [
    { id: 'crm',    icon: 'user-check',     label: 'Lead qualificado',     sub: 'CRM · score 88',  tone: '#1FD17B' },
    { id: 'agenda', icon: 'calendar-check', label: 'Reunião sugerida',     sub: 'Agenda · ter 14h', tone: '#00D4FF' },
    { id: 'follow', icon: 'bell-ring',      label: 'Follow-up programado', sub: 'em 2 dias',        tone: '#7CB0FF' },
    { id: 'sheet',  icon: 'table-2',        label: 'Planilha atualizada',  sub: 'linha +1',         tone: '#3D8BFF' },
  ];

  // ---- measurement (responsive line geometry) ----
  React.useLayoutEffect(() => {
    const measure = () => {
      const wrap = wrapRef.current;
      if (!wrap || !waRef.current || !agentRef.current) return;
      const cr = wrap.getBoundingClientRect();
      const rect = (el) => {
        const r = el.getBoundingClientRect();
        return {
          x: r.left - cr.left + r.width / 2, y: r.top - cr.top + r.height / 2,
          left: r.left - cr.left, right: r.right - cr.left,
          top: r.top - cr.top, bottom: r.bottom - cr.top,
        };
      };
      const isCol = cr.width < 560;
      setGeo({
        w: cr.width, h: cr.height, isCol,
        wa: rect(waRef.current),
        agent: rect(agentRef.current),
        cards: cardRefs.current.filter(Boolean).map(rect),
      });
    };
    measure();
    const ro = new ResizeObserver(measure);
    if (wrapRef.current) ro.observe(wrapRef.current);
    window.addEventListener('resize', measure);
    const t = setTimeout(measure, 350); // após fontes/imagens
    return () => { ro.disconnect(); window.removeEventListener('resize', measure); clearTimeout(t); };
  }, []);

  React.useEffect(() => { window.lucide && window.lucide.createIcons(); }, [geo]);

  // ---- nearest-block detection (throttled w/ rAF) ----
  const onSceneMove = (e) => {
    if (!geo || !wrapRef.current) return;
    if (rafRef.current) return;
    rafRef.current = requestAnimationFrame(() => {
      rafRef.current = 0;
      const cr = wrapRef.current.getBoundingClientRect();
      const mx = e.clientX - cr.left, my = e.clientY - cr.top;
      const pts = [['wa', geo.wa], ['agent', geo.agent], ...geo.cards.map((c, i) => [i, c])];
      let best = null, bd = Infinity;
      for (const [id, p] of pts) {
        const d = (p.x - mx) ** 2 + (p.y - my) ** 2;
        if (d < bd) { bd = d; best = id; }
      }
      setNear(bd < 200 * 200 ? best : null);
    });
  };

  // ---- path helpers ----
  const anchorOut = (r) => geo.isCol ? { x: r.x, y: r.bottom } : { x: r.right, y: r.y };
  const anchorIn  = (r) => geo.isCol ? { x: r.x, y: r.top }    : { x: r.left,  y: r.y };
  const curve = (a, b, towardA) => {
    const cx = (a.x + b.x) / 2, cy = (a.y + b.y) / 2;
    const ctrl = towardA ? { x: cx, y: a.y } : { x: cx, y: b.y };
    if (geo.isCol) { ctrl.x = a.x; ctrl.y = cy; }
    return `M ${a.x} ${a.y} Q ${ctrl.x} ${ctrl.y} ${b.x} ${b.y}`;
  };

  const particles = React.useMemo(() => Array.from({ length: 16 }, (_, i) => ({
    left: Math.random() * 100, top: Math.random() * 100,
    size: 1.5 + Math.random() * 2.5, delay: Math.random() * 6,
    dur: 7 + Math.random() * 7,
  })), []);

  const tx = tilt.x * 12, ty = tilt.y * 12;

  // build line set
  let lines = [];
  if (geo) {
    const aIn = anchorIn(geo.agent), aOut = anchorOut(geo.agent);
    lines.push({ key: 'in', d: curve(anchorOut(geo.wa), aIn, false), active: near === 'wa' || near === 'agent', dur: 2.0, color: '#25D366' });
    geo.cards.forEach((c, i) => {
      lines.push({ key: 'o' + i, d: curve(aOut, anchorIn(c), true), active: near === i || near === 'agent', dur: 1.7 + i * 0.18, begin: (i * 0.4) + 's', color: dests[i].tone });
    });
  }
  const geoKey = geo ? `${Math.round(geo.w)}x${Math.round(geo.h)}` : '0';

  return (
    <div
      ref={wrapRef}
      onMouseMove={onSceneMove}
      onMouseEnter={() => setHovering(true)}
      onMouseLeave={() => { setHovering(false); setNear(null); }}
      style={{
        position: 'relative', width: '100%', minHeight: 460,
        transform: `perspective(1200px) rotateY(${tilt.x * 4}deg) rotateX(${-tilt.y * 4}deg)`,
        transformStyle: 'preserve-3d', transition: 'transform 240ms var(--ar-ease)',
      }}
    >
      {/* ambient glow */}
      <div style={{
        position: 'absolute', inset: '-6% -4%', pointerEvents: 'none', zIndex: 0,
        background: 'radial-gradient(closest-side at 50% 46%, rgba(0,94,255,0.22), transparent 72%)',
        filter: 'blur(8px)', transform: `translate(${tx * 0.3}px, ${ty * 0.3}px)`,
      }} />

      {/* particles */}
      <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', zIndex: 0, overflow: 'hidden' }}>
        {particles.map((p, i) => (
          <span key={i} className="car-particle" style={{
            position: 'absolute', left: p.left + '%', top: p.top + '%',
            width: p.size, height: p.size, borderRadius: 999,
            background: i % 3 === 0 ? '#00D4FF' : 'rgba(124,176,255,0.9)',
            boxShadow: '0 0 6px rgba(0,212,255,0.8)',
            animationDelay: `-${p.delay}s`, animationDuration: `${p.dur}s`,
          }} />
        ))}
      </div>

      {/* connecting lines */}
      {geo && (
        <svg key={geoKey} width={geo.w} height={geo.h} viewBox={`0 0 ${geo.w} ${geo.h}`}
          style={{ position: 'absolute', inset: 0, zIndex: 1, pointerEvents: 'none', overflow: 'visible' }}>
          <defs>
            <linearGradient id="carLine" x1="0%" y1="0%" x2="100%" y2="0%">
              <stop offset="0%" stopColor="#005EFF" /><stop offset="100%" stopColor="#00D4FF" />
            </linearGradient>
          </defs>
          {lines.map(l => (
            <g key={l.key}>
              {/* soft glow underlay */}
              <path d={l.d} fill="none" stroke="url(#carLine)" strokeWidth={l.active ? 9 : 6}
                strokeLinecap="round" opacity={l.active ? 0.32 : (hovering ? 0.16 : 0.10)}
                style={{ transition: 'opacity 240ms, stroke-width 240ms' }} />
              {/* crisp line */}
              <path d={l.d} fill="none" stroke="url(#carLine)" strokeWidth="1.6"
                strokeLinecap="round" strokeDasharray="5 6"
                opacity={l.active ? 1 : (hovering ? 0.8 : 0.55)}
                style={{ transition: 'opacity 240ms' }} className="car-flow" />
              {/* travelling data dot */}
              <circle r={l.active ? 3.4 : 2.6} fill={l.color}
                style={{ filter: `drop-shadow(0 0 5px ${l.color})`, transition: 'r 240ms' }}>
                <animateMotion dur={`${l.dur}s`} begin={l.begin || '0s'} repeatCount="indefinite" path={l.d} rotate="auto" />
              </circle>
            </g>
          ))}
        </svg>
      )}

      {/* ===== layout: 3 columns (row) / stacked (col) ===== */}
      <div style={{
        position: 'relative', zIndex: 2, width: '100%', minHeight: 460,
        display: 'flex', flexDirection: (geo && geo.isCol) ? 'column' : 'row',
        alignItems: 'center', justifyContent: 'space-between',
        gap: (geo && geo.isCol) ? 30 : 8,
      }}>
        {/* --- WhatsApp client --- */}
        <CarTilt parallax={{ x: tx, y: ty }} active={near === 'wa'} style={{ width: (geo && geo.isCol) ? '100%' : 184, maxWidth: 240 }}>
          <div ref={waRef} style={carWaCardStyle(near === 'wa')}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '10px 12px', background: 'linear-gradient(135deg,#0c3b2e,#075E54)', borderBottom: '1px solid rgba(255,255,255,0.08)' }}>
              <span style={{ width: 26, height: 26, borderRadius: 999, background: '#25D366', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <i data-lucide="message-circle" style={{ width: 14, height: 14, color: '#06281f' }}></i>
              </span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: 'var(--ar-font-title)', fontWeight: 600, fontSize: 12.5, color: '#fff' }}>Cliente</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontFamily: 'var(--ar-font-body)', fontSize: 10, color: '#9ff0c4' }}>
                  <span className="ar-pulse" style={{ width: 5, height: 5, borderRadius: 999, background: '#25D366' }} />online · WhatsApp
                </div>
              </div>
            </div>
            <div style={{ padding: '14px 12px 12px', display: 'flex', flexDirection: 'column', gap: 8, background: 'rgba(5,7,13,0.55)' }}>
              <CarBubble delay={0}>Olá! Vocês atendem hoje?</CarBubble>
              <CarBubble delay={1.4}>Queria agendar uma reunião</CarBubble>
              <div className="car-typing" style={{ alignSelf: 'flex-start', display: 'inline-flex', gap: 4, padding: '9px 12px', borderRadius: '12px 12px 12px 4px', background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.07)' }}>
                {[0, 1, 2].map(d => <span key={d} className="car-dot" style={{ width: 5, height: 5, borderRadius: 999, background: '#9ff0c4', animationDelay: `${d * 0.16}s` }} />)}
              </div>
            </div>
          </div>
        </CarTilt>

        {/* --- AI Agent core --- */}
        <div style={{ position: 'relative', flexShrink: 0, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <div ref={agentRef} className={'car-core' + (near === 'agent' ? ' on' : '')} style={{
            position: 'relative', width: 118, height: 118, borderRadius: 999, flexShrink: 0,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            background: 'radial-gradient(circle at 50% 38%, #0a4fd8 0%, #06245f 64%, #08142e 100%)',
            border: '1px solid rgba(0,212,255,0.55)',
            boxShadow: '0 0 0 1px rgba(0,212,255,0.18), 0 0 48px rgba(0,94,255,0.6), inset 0 0 24px rgba(0,212,255,0.25)',
            transform: `translate(${tx * 0.25}px, ${ty * 0.25}px)`,
          }}>
            <span className="car-ring" />
            <span className="car-ring car-ring2" />
            <img src="assets/logo-white.png" alt="AR" style={{ width: 50, height: 50, filter: 'drop-shadow(0 0 10px rgba(0,212,255,0.7))', position: 'relative', zIndex: 2 }} />
          </div>
          <div style={{ marginTop: 14, textAlign: 'center', transform: `translate(${tx * 0.25}px, ${ty * 0.25}px)` }}>
            <div style={{ fontFamily: 'var(--ar-font-title)', fontWeight: 700, fontSize: 13.5, color: 'var(--ar-text-main)', letterSpacing: '-0.01em' }}>Agente IA AR</div>
            <div style={{ marginTop: 5, display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 10px', borderRadius: 999, background: 'rgba(0,212,255,0.08)', border: '1px solid rgba(0,212,255,0.28)' }}>
              <span style={{ fontFamily: 'var(--ar-font-body)', fontSize: 10.5, fontWeight: 600, letterSpacing: '0.04em', color: '#00D4FF' }}>analisando intenção</span>
              <span className="car-dot" style={{ width: 4, height: 4, borderRadius: 999, background: '#00D4FF' }} />
            </div>
            <div style={{ marginTop: 7, fontFamily: 'var(--ar-font-mono)', fontSize: 10, color: 'var(--ar-text-muted)' }}>intenção: <span style={{ color: '#7CB0FF' }}>agendamento</span></div>
          </div>
        </div>

        {/* --- CRM / destinations --- */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 9, width: (geo && geo.isCol) ? '100%' : 198, maxWidth: 260 }}>
          {dests.map((d, i) => (
            <CarTilt key={d.id} parallax={{ x: tx * 1.15, y: ty * 1.15 }} active={near === i} compact>
              <div ref={el => cardRefs.current[i] = el} style={carDestCardStyle(near === i)}>
                <span style={{ width: 30, height: 30, borderRadius: 9, flexShrink: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', background: `${d.tone}1f`, border: `1px solid ${d.tone}55`, color: d.tone }}>
                  <i data-lucide={d.icon} style={{ width: 15, height: 15 }}></i>
                </span>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ fontFamily: 'var(--ar-font-title)', fontWeight: 600, fontSize: 12.5, color: 'var(--ar-text-main)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.label}</div>
                  <div style={{ fontFamily: 'var(--ar-font-body)', fontSize: 10.5, color: 'var(--ar-text-muted)' }}>{d.sub}</div>
                </div>
                <i data-lucide="check" className="car-check" style={{ width: 14, height: 14, color: d.tone, animationDelay: `${i * 0.5}s` }}></i>
              </div>
            </CarTilt>
          ))}
        </div>
      </div>

      {/* live badge */}
      <div style={{
        position: 'absolute', bottom: -10, right: (geo && geo.isCol) ? '50%' : -6, zIndex: 3,
        transform: (geo && geo.isCol) ? `translateX(50%) translate(${tx}px,${ty}px)` : `translate(${tx * 1.4}px, ${ty * 1.4}px)`,
        background: 'linear-gradient(135deg,#005EFF,#00D4FF)', borderRadius: 12, padding: '8px 13px',
        display: 'flex', alignItems: 'center', gap: 8, boxShadow: '0 12px 30px rgba(0,94,255,0.5)',
      }}>
        <i data-lucide="zap" style={{ width: 14, height: 14, color: '#fff' }}></i>
        <span style={{ fontFamily: 'var(--ar-font-body)', fontWeight: 600, fontSize: 11.5, color: '#fff' }}>resolvido em 38s</span>
      </div>

      <style>{`
        .ar-pulse { animation: arPulse 1.6s var(--ar-ease) infinite; }
        @keyframes arPulse { 0%,100% { box-shadow: 0 0 0 0 rgba(31,209,123,0.5); } 50% { box-shadow: 0 0 0 5px rgba(31,209,123,0); } }

        .car-flow { animation: carDash 1.1s linear infinite; }
        @keyframes carDash { to { stroke-dashoffset: -22; } }

        .car-particle { animation-name: carFloat; animation-timing-function: ease-in-out; animation-iteration-count: infinite; opacity: .5; }
        @keyframes carFloat { 0%,100% { transform: translate(0,0); opacity:.25; } 50% { transform: translate(6px,-14px); opacity:.85; } }

        .car-core .car-ring, .car-core .car-ring2 { position:absolute; inset:0; border-radius:999px; border:1px solid rgba(0,212,255,0.5); animation: carRing 2.8s ease-out infinite; }
        .car-core .car-ring2 { animation-delay: 1.4s; }
        @keyframes carRing { 0% { transform: scale(1); opacity:.7; } 70%,100% { transform: scale(1.9); opacity:0; } }
        .car-core.on { box-shadow: 0 0 0 1px rgba(0,212,255,0.4), 0 0 70px rgba(0,94,255,0.85), inset 0 0 28px rgba(0,212,255,0.4) !important; }

        .car-dot { display:inline-block; animation: carBlink 1s var(--ar-ease) infinite; }
        @keyframes carBlink { 0%,60%,100% { opacity:.3; transform: translateY(0);} 30% { opacity:1; transform: translateY(-2px);} }

        .car-bubble { animation: carMsg 7s var(--ar-ease) infinite; }
        @keyframes carMsg { 0% { opacity:0; transform: translateY(8px) scale(.97);} 7% { opacity:1; transform:none;} 88% { opacity:1;} 100% { opacity:0; transform: translateY(-4px);} }

        .car-check { animation: carPop 4s ease-in-out infinite; }
        @keyframes carPop { 0%,70%,100% { opacity:.35; transform: scale(.85);} 12%,55% { opacity:1; transform: scale(1);} }

        @media (prefers-reduced-motion: reduce) {
          .car-flow, .car-particle, .car-ring, .car-ring2, .car-dot, .car-bubble, .car-check { animation: none !important; }
          .car-bubble { opacity: 1 !important; transform: none !important; }
        }
      `}</style>
    </div>
  );
};

/* ---- sub-pieces ---- */
const carWaCardStyle = (active) => ({
  borderRadius: 16, overflow: 'hidden', width: '100%',
  background: 'var(--ar-bg-card)',
  border: `1px solid ${active ? 'rgba(0,212,255,0.55)' : 'rgba(255,255,255,0.10)'}`,
  boxShadow: active
    ? '0 26px 60px -24px rgba(0,0,0,0.8), 0 0 30px -6px rgba(0,212,255,0.4)'
    : '0 22px 50px -22px rgba(0,0,0,0.72)',
  transition: 'border-color 240ms, box-shadow 240ms',
});

const carDestCardStyle = (active) => ({
  display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 13,
  background: active ? 'linear-gradient(135deg, rgba(0,94,255,0.18), rgba(16,24,43,0.96))' : 'var(--ar-bg-card)',
  border: `1px solid ${active ? 'rgba(0,212,255,0.5)' : 'rgba(255,255,255,0.10)'}`,
  boxShadow: active ? '0 18px 40px -18px rgba(0,0,0,0.8), 0 0 22px -8px rgba(0,212,255,0.45)' : '0 12px 30px -16px rgba(0,0,0,0.6)',
  transition: 'border-color 240ms, box-shadow 240ms, background 240ms',
});

const CarBubble = ({ children, delay }) => (
  <div className="car-bubble" style={{
    alignSelf: 'flex-start', maxWidth: '92%', padding: '8px 11px',
    borderRadius: '12px 12px 12px 4px', background: 'rgba(255,255,255,0.07)',
    border: '1px solid rgba(255,255,255,0.07)', fontFamily: 'var(--ar-font-body)',
    fontSize: 12, lineHeight: 1.4, color: '#e7ecf7', animationDelay: `${delay}s`,
  }}>{children}</div>
);

/* CarTilt — parallax + subtle 3D tilt on hover */
const CarTilt = ({ children, parallax = { x: 0, y: 0 }, active, compact, style }) => {
  const ref = React.useRef(null);
  const [t, setT] = React.useState({ rx: 0, ry: 0 });
  const onMove = (e) => {
    const el = ref.current; if (!el) return;
    const r = el.getBoundingClientRect();
    const px = (e.clientX - r.left) / r.width - 0.5;
    const py = (e.clientY - r.top) / r.height - 0.5;
    const m = compact ? 6 : 8;
    setT({ rx: -py * m, ry: px * m });
  };
  return (
    <div
      ref={ref}
      onMouseMove={onMove}
      onMouseLeave={() => setT({ rx: 0, ry: 0 })}
      style={{
        transform: `translate(${parallax.x}px, ${parallax.y}px) perspective(800px) rotateX(${t.rx}deg) rotateY(${t.ry}deg)`,
        transition: 'transform 180ms var(--ar-ease)', transformStyle: 'preserve-3d', willChange: 'transform',
        ...style,
      }}
    >{children}</div>
  );
};

window.CentralAR = CentralAR;
