/* Animated visuals for feature cards
   Three pure-CSS+React micro-animations replacing static screenshots.
   Exported: <ChatAnim/>, <FunnelAnim/>, <DashAnim/> */

/* ═══════════════════════════════════════════
   Shared look tokens for feature-animations
   ═══════════════════════════════════════════ */
const FA_STYLES = `
.fa-wrap {
  position: relative;
  width: 100%;
  height: 260px;
  background: linear-gradient(180deg, #ffffff 0%, #f6f6fb 100%);
  border: 1px solid rgba(10, 12, 26, 0.08);
  border-radius: 12px;
  overflow: hidden;
}
.fa-wrap.tall { height: 340px; }
.fa-wrap .fa-glow {
  position: absolute; inset: 0;
  background: radial-gradient(ellipse 60% 50% at 50% 110%, rgba(150,44,244,0.10), transparent 70%);
  pointer-events: none;
}
.fa-wrap .fa-dots {
  position: absolute; inset: 0;
  background-image: radial-gradient(circle at 1px 1px, rgba(150,44,244,0.10) 1px, transparent 0);
  background-size: 18px 18px;
  mask-image: linear-gradient(180deg, black, transparent 90%);
  -webkit-mask-image: linear-gradient(180deg, black, transparent 90%);
}

/* ─── CHAT ─── */
.fa-wrap .fa-chat { position: absolute; inset: 20px; display: flex; flex-direction: column; gap: 10px; justify-content: flex-end; }
.fa-wrap .fa-msg {
  display: flex; align-items: flex-start; gap: 10px;
  opacity: 1;
}
.fa-wrap .fa-msg.fa-fresh {
  animation: fa-msg-in 400ms var(--ease-standard) both;
}
.fa-wrap .fa-msg .av {
  flex-shrink: 0;
  width: 28px; height: 28px;
  border-radius: 50%;
  display: inline-flex; align-items: center; justify-content: center;
  font-size: 11px; font-weight: 700; font-family: var(--font-display);
}
.fa-wrap .fa-msg .av.ai { background: linear-gradient(135deg, #962cf4, #4e0f83); color: #fff; }
.fa-wrap .fa-msg .av.user { background: #25d366; color: #fff; }
.fa-wrap .fa-msg .bubble {
  max-width: 78%;
  padding: 9px 13px;
  border-radius: 14px;
  font-size: 13px;
  line-height: 1.4;
  color: #1a1a2e;
  background: rgba(150,44,244,0.08);
  border: 1px solid rgba(150,44,244,0.22);
  box-shadow: 0 4px 16px rgba(150,44,244,0.08);
}
.fa-wrap .fa-msg.user { flex-direction: row-reverse; }
.fa-wrap .fa-msg.user .bubble {
  background: rgba(37, 211, 102, 0.12);
  border-color: rgba(37, 211, 102, 0.32);
  box-shadow: 0 4px 16px rgba(37,211,102,0.08);
}
.fa-wrap .fa-msg .bubble .time {
  display: block; font-size: 10px;
  color: rgba(10,10,30,0.4);
  margin-top: 4px;
  font-family: var(--font-mono);
}
.fa-wrap .fa-typing { display: inline-flex; gap: 4px; padding: 12px 14px; }
.fa-wrap .fa-typing span {
  width: 5px; height: 5px; border-radius: 50%;
  background: #962cf4;
  animation: fa-bounce 1.2s ease-in-out infinite;
}
.fa-wrap .fa-typing span:nth-child(2) { animation-delay: 0.15s; }
.fa-wrap .fa-typing span:nth-child(3) { animation-delay: 0.3s; }

@keyframes fa-msg-in {
  from { opacity: 0; transform: translateY(10px) scale(0.96); filter: blur(4px); }
  to   { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }
}
@keyframes fa-bounce {
  0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }
  30% { transform: translateY(-5px); opacity: 1; }
}

/* ─── FUNNEL ─── */
.fa-wrap .fa-funnel { position: absolute; inset: 24px; display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; }
.fa-wrap .fa-col {
  background: rgba(150,44,244,0.04);
  border: 1px solid rgba(10, 12, 26, 0.08);
  border-radius: 10px;
  padding: 14px 12px;
  display: flex; flex-direction: column;
  position: relative;
  overflow: hidden;
}
.fa-wrap .fa-col .lbl {
  font-family: var(--font-mono);
  font-size: 10px;
  letter-spacing: 0.08em;
  color: rgba(10,10,30,0.5);
  margin-bottom: 4px;
}
.fa-wrap .fa-col .cnt {
  font-family: var(--font-display);
  font-size: 22px;
  font-weight: 700;
  color: #0a0a1a;
  margin-bottom: 12px;
}
.fa-wrap .fa-col .leads { flex: 1; display: flex; flex-direction: column; gap: 6px; }
.fa-wrap .fa-lead {
  display: flex; align-items: center; gap: 8px;
  padding: 6px 8px;
  background: rgba(10,12,26,0.035);
  border: 1px solid rgba(10,12,26,0.06);
  border-radius: 6px;
  font-size: 11px;
  color: #2a2a3a;
  animation: fa-lead-in 600ms var(--ease-standard);
}
.fa-wrap .fa-lead .pulse {
  width: 6px; height: 6px; border-radius: 50%;
  background: #a855f7;
  box-shadow: 0 0 8px #962cf4;
  animation: fa-pulse 1.6s ease-in-out infinite;
}
.fa-wrap .fa-lead.hot .pulse { background: #ff5b72; box-shadow: 0 0 8px #ff5b72; }
.fa-wrap .fa-lead.won .pulse { background: #25d366; box-shadow: 0 0 8px #25d366; }
@keyframes fa-lead-in {
  from { opacity: 0; transform: translateY(-14px); }
  to { opacity: 1; transform: translateY(0); }
}
@keyframes fa-pulse {
  0%, 100% { opacity: 0.7; transform: scale(1); }
  50% { opacity: 1; transform: scale(1.3); }
}

/* connector arrows between columns */
.fa-wrap .fa-col::after {
  content: '';
  position: absolute;
  right: -11px; top: 50%;
  width: 10px; height: 2px;
  background: linear-gradient(90deg, #962cf4, transparent);
  transform: translateY(-50%);
  opacity: 0.5;
}
.fa-wrap .fa-col:last-child::after { display: none; }

/* ─── DASHBOARD ─── */
.fa-wrap .fa-dash { position: absolute; inset: 20px; display: grid; gap: 12px; grid-template-rows: auto 1fr auto; }
.fa-wrap .fa-dash-head { display: flex; gap: 10px; }
.fa-wrap .fa-stat {
  flex: 1;
  padding: 10px 12px;
  background: rgba(150,44,244,0.05);
  border: 1px solid rgba(10,12,26,0.08);
  border-radius: 8px;
}
.fa-wrap .fa-stat .lbl {
  font-size: 10px; color: rgba(10,10,30,0.5);
  letter-spacing: 0.04em;
  margin-bottom: 4px;
}
.fa-wrap .fa-stat .val {
  font-family: var(--font-display);
  font-size: 18px; font-weight: 700;
  color: #0a0a1a;
}
.fa-wrap .fa-stat .chg { font-size: 10px; color: #8e2ff0; font-family: var(--font-mono); }

.fa-wrap .fa-chart {
  position: relative;
  background: rgba(150,44,244,0.035);
  border: 1px solid rgba(10,12,26,0.08);
  border-radius: 8px;
  padding: 12px;
  overflow: hidden;
}
.fa-wrap .fa-bars { display: flex; align-items: flex-end; gap: 4px; height: 100%; }
.fa-wrap .fa-bar {
  flex: 1;
  background: linear-gradient(180deg, #c88cff 0%, #8e2ff0 50%, #5a0fa8 100%);
  border-radius: 3px 3px 0 0;
  box-shadow: 0 0 10px rgba(150,44,244,0.25), inset 0 1px 0 rgba(255,255,255,0.25);
  transition: height 700ms cubic-bezier(.2,.8,.2,1);
  min-height: 8px;
}
@keyframes fa-bar-grow {
  from { transform: scaleY(0); transform-origin: bottom; }
  to { transform: scaleY(1); transform-origin: bottom; }
}

.fa-wrap .fa-cards-row { display: flex; gap: 8px; }
.fa-wrap .fa-mini-card {
  flex: 1;
  padding: 10px;
  background: rgba(10,12,26,0.035);
  border: 1px solid rgba(10,12,26,0.06);
  border-radius: 8px;
  font-size: 11px;
  color: #2a2a3a;
  display: flex; align-items: center; gap: 8px;
}
.fa-wrap .fa-mini-card .ic {
  width: 24px; height: 24px; border-radius: 6px;
  background: linear-gradient(135deg, rgba(150,44,244,0.25), rgba(150,44,244,0.08));
  display: inline-flex; align-items: center; justify-content: center;
  color: #8e2ff0;
}
.fa-wrap .fa-mini-card .txt strong { color: #0a0a1a; display: block; font-weight: 600; }
.fa-wrap .fa-mini-card .status {
  margin-left: auto;
  font-size: 9px;
  padding: 2px 6px;
  border-radius: 999px;
  background: rgba(150,44,244,0.12);
  color: #6919c2;
  font-family: var(--font-mono);
}
.fa-wrap .fa-mini-card .status.ok { background: rgba(37,211,102,0.15); color: #16a34a; }
`;

/* Inject styles once */
if (typeof document !== 'undefined' && !document.getElementById('fa-styles')) {
  const s = document.createElement('style');
  s.id = 'fa-styles';
  s.textContent = FA_STYLES;
  document.head.appendChild(s);
}

/* ═══════════════════════════════════════════
   CHAT. Jarvis responding on WhatsApp
   Loops through a conversation.
   ═══════════════════════════════════════════ */
const CHAT_SCRIPT = [
  { who: 'user', text: 'Oi, vi o anúncio no Instagram. Qto custa o tratamento de pele a laser?', t: '14:23' },
  { who: 'ai',   text: 'Oi! Aqui é a Bia, assistente da BioAge. Nosso laser co2 fracionado sai por R$ 480 a sessão 🙌', t: '14:23', delay: 800 },
  { who: 'ai',   text: 'Posso ver um horário essa semana pra você? Tenho quinta 15h ou sexta 10h.', t: '14:23', delay: 900 },
  { who: 'user', text: 'Quinta 15h serve!', t: '14:24', delay: 1100 },
  { who: 'ai',   text: 'Agendado ✨ Enviei a confirmação no seu email. Até quinta!', t: '14:24', delay: 900 },
];

const ChatAnim = () => {
  const [step, setStep] = React.useState(0);
  // Precompute timeline: list of (label, durationMs)
  const timeline = React.useMemo(() => {
    const tl = [];
    CHAT_SCRIPT.forEach((m, i) => {
      if (i === 0) {
        tl.push({ shown: 1, typing: false, dur: 900 });
      } else if (m.who === 'ai') {
        tl.push({ shown: i, typing: true, dur: m.delay || 800 });
        tl.push({ shown: i + 1, typing: false, dur: 700 });
      } else {
        tl.push({ shown: i + 1, typing: false, dur: m.delay || 900 });
      }
    });
    tl.push({ shown: 0, typing: false, dur: 3500 }); // pause + reset
    return tl;
  }, []);

  React.useEffect(() => {
    const id = setTimeout(() => {
      setStep(s => (s + 1) % timeline.length);
    }, timeline[step].dur);
    return () => clearTimeout(id);
  }, [step, timeline]);

  const state = timeline[step];
  const shown = state.shown;
  const typing = state.typing;

  return (
    <div className="fa-wrap">
      <div className="fa-dots" />
      <div className="fa-glow" />
      <div className="fa-chat">
        {CHAT_SCRIPT.slice(0, shown).map((m, i) => (
          <div key={i} className={'fa-msg ' + m.who}>
            <div className={'av ' + (m.who === 'ai' ? 'ai' : 'user')}>
              {m.who === 'ai' ? 'J' : 'V'}
            </div>
            <div className="bubble">
              {m.text}
              <span className="time">{m.time || m.t} · {m.who === 'ai' ? '✓✓' : ''}</span>
            </div>
          </div>
        ))}
        {typing && (
          <div className="fa-msg ai">
            <div className="av ai">J</div>
            <div className="bubble fa-typing"><span/><span/><span/></div>
          </div>
        )}
      </div>
    </div>
  );
};

/* ═══════════════════════════════════════════
   FUNNEL. Leads flowing through ToFu/MoFu/BoFu
   ═══════════════════════════════════════════ */
const FUNNEL_LEADS = [
  ['Carla M.',  'Ana P.',   'Ricardo S.', 'Julia F.', 'Pedro L.', 'Bia T.'],
  ['Lucas R.',  'Renata K.', 'Otávio N.', 'Sofia A.', 'Diego M.'],
  ['Marina G.', 'Thiago B.', 'Paula V.', 'Nina C.'],
];
const FUNNEL_COLS = [
  { lbl: 'Novo lead',   total: 247, cls: '' },
  { lbl: 'Qualificado', total:  68, cls: 'hot' },
  { lbl: 'Agendado',    total:  19, cls: 'won' },
];

const FunnelAnim = () => {
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const int = setInterval(() => setTick(t => t + 1), 1800);
    return () => clearInterval(int);
  }, []);

  return (
    <div className="fa-wrap">
      <div className="fa-dots" />
      <div className="fa-glow" />
      <div className="fa-funnel">
        {FUNNEL_COLS.map((col, ci) => {
          const leads = FUNNEL_LEADS[ci];
          const offset = tick % leads.length;
          const visible = [0, 1, 2].map(i => leads[(offset + i) % leads.length]);
          return (
            <div className="fa-col" key={col.lbl}>
              <div className="lbl">{col.lbl}</div>
              <div className="cnt">{col.total + tick}</div>
              <div className="leads">
                {visible.map((name, li) => (
                  <div key={name + ci + tick + li} className={'fa-lead ' + col.cls}
                       style={{ animationDelay: (li * 0.08) + 's' }}>
                    <div className="pulse" />
                    <span>{name}</span>
                  </div>
                ))}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

/* ═══════════════════════════════════════════
   DASHBOARD. stats + animated chart bars + posts
   ═══════════════════════════════════════════ */
const DashAnim = () => {
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const int = setInterval(() => setTick(t => t + 1), 1400);
    return () => clearInterval(int);
  }, []);

  // generate bar heights each tick
  const bars = React.useMemo(() => {
    const base = [28, 45, 38, 62, 54, 70, 58, 82, 75, 90, 68, 95];
    const jitter = (i) => Math.min(100, Math.max(15, base[i] + ((tick * 11 + i * 17) % 32) - 16));
    return base.map((_, i) => jitter(i));
  }, [tick]);

  // rotate stat values
  const stats = React.useMemo(() => [
    { lbl: 'CONVERSÕES',   val: 324 + tick * 3, chg: '+12%' },
    { lbl: 'TEMPO MÉDIO',  val: '0:42', chg: '-08%', raw: true },
    { lbl: 'ROI',          val: '4.7×', chg: '+22%', raw: true },
  ], [tick]);

  const POSTS = ['Carrossel: Black Friday', 'Reel: Antes/Depois', 'Post: Depoimento Ana'];
  const curPost = POSTS[tick % POSTS.length];

  return (
    <div className="fa-wrap">
      <div className="fa-dots" />
      <div className="fa-glow" />
      <div className="fa-dash">
        <div className="fa-dash-head">
          {stats.map(s => (
            <div className="fa-stat" key={s.lbl}>
              <div className="lbl">{s.lbl}</div>
              <div className="val">{s.raw ? s.val : s.val.toLocaleString('pt-BR')}</div>
              <div className="chg">{s.chg} vs semana passada</div>
            </div>
          ))}
        </div>
        <div className="fa-chart">
          <div className="fa-bars">
            {bars.map((h, i) => (
              <div className="fa-bar"
                   key={i}
                   style={{ height: h + '%' }} />
            ))}
          </div>
        </div>
        <div className="fa-cards-row">
          <div className="fa-mini-card">
            <div className="ic">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <rect x="3" y="3" width="18" height="18" rx="4"/><circle cx="12" cy="12" r="4"/>
              </svg>
            </div>
            <div className="txt">
              <strong>IA gerou post</strong>
              <span>{curPost}</span>
            </div>
            <span className="status ok">PRONTO</span>
          </div>
          <div className="fa-mini-card">
            <div className="ic">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0zM12 7v5l3 2"/>
              </svg>
            </div>
            <div className="txt">
              <strong>Disparo agendado</strong>
              <span>Amanhã 09:00 · 1.240 leads</span>
            </div>
            <span className="status">FILA</span>
          </div>
        </div>
      </div>
    </div>
  );
};

window.ChatAnim = ChatAnim;
window.FunnelAnim = FunnelAnim;
window.DashAnim = DashAnim;
