/* ============================================================
   AppShowcase.jsx — "Apps web e mobile com IA"
   Showcase interativo: web app + tablet + celular, com abas
   por módulo (Gestão, Atendimento, Financeiro, Estoque,
   Vendas, RH). Escala responsiva via ScaleBox.
   ============================================================ */

/* ---- ScaleBox: encaixa um palco de tamanho fixo na largura do pai ----
   Usa medição no mount + resize da janela (ResizeObserver não é
   confiável neste runtime). ---- */
const ScaleBox = ({ designW, designH, maxScale = 1, children }) => {
  const wrapRef = React.useRef(null);
  const [scale, setScale] = React.useState(maxScale);
  React.useLayoutEffect(() => {
    const measure = () => {
      const el = wrapRef.current;
      if (!el) return;
      const w = el.clientWidth;
      if (w > 0) setScale(Math.min(maxScale, w / designW));
    };
    measure();
    const t1 = setTimeout(measure, 60);
    const t2 = setTimeout(measure, 400);
    window.addEventListener('resize', measure);
    return () => { clearTimeout(t1); clearTimeout(t2); window.removeEventListener('resize', measure); };
  }, [designW, maxScale]);
  return (
    <div ref={wrapRef} style={{ width: '100%', height: designH * scale }}>
      <div style={{ width: designW, height: designH, transformOrigin: 'top left', transform: `scale(${scale})` }}>
        {children}
      </div>
    </div>
  );
};

/* ---- molduras de dispositivos ---- */
const BrowserFrame = ({ children, style }) => (
  <div style={{ borderRadius: 15, overflow: 'hidden', background: '#0A0F1C', border: '1px solid rgba(255,255,255,0.11)', boxShadow: '0 50px 100px -38px rgba(0,0,0,0.82)', display: 'flex', flexDirection: 'column', ...style }}>
    <div style={{ height: 38, flexShrink: 0, background: '#0E1424', borderBottom: '1px solid rgba(255,255,255,0.07)', display: 'flex', alignItems: 'center', gap: 14, padding: '0 14px' }}>
      <div style={{ display: 'flex', gap: 7 }}>
        {['#FF5F57', '#FEBC2E', '#28C840'].map(c => <span key={c} style={{ width: 11, height: 11, borderRadius: 999, background: c, opacity: 0.9 }} />)}
      </div>
      <div style={{ flex: 1, maxWidth: 360, margin: '0 auto', display: 'flex', alignItems: 'center', gap: 8, background: '#070B16', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 8, padding: '5px 12px', color: '#6B7591', fontFamily: 'var(--ar-font-body)', fontSize: 11.5 }}>
        <i data-lucide="lock" style={{ width: 12, height: 12, color: '#1FD17B' }}></i>
        app.suaempresa.com.br
      </div>
      <div style={{ width: 56 }} />
    </div>
    <div style={{ flex: 1, minHeight: 0 }}>{children}</div>
  </div>
);

const TabletFrame = ({ children, style }) => (
  <div style={{ borderRadius: 24, padding: 10, background: 'linear-gradient(160deg, #161d30, #06090f)', border: '1px solid rgba(255,255,255,0.10)', boxShadow: '0 40px 80px -36px rgba(0,0,0,0.8)', ...style }}>
    <div style={{ width: '100%', height: '100%', borderRadius: 16, overflow: 'hidden', background: '#070B16' }}>{children}</div>
  </div>
);

const PhoneFrame = ({ children, style }) => (
  <div style={{ position: 'relative', borderRadius: 38, padding: 9, background: 'linear-gradient(160deg, #161d30, #06090f)', border: '1px solid rgba(255,255,255,0.11)', boxShadow: '0 44px 90px -34px rgba(0,0,0,0.82)', ...style }}>
    <div style={{ position: 'absolute', top: 10, left: '50%', transform: 'translateX(-50%)', width: 58, height: 15, background: '#05070d', borderRadius: 999, zIndex: 4 }} />
    <div style={{ width: '100%', height: '100%', borderRadius: 30, overflow: 'hidden', background: '#070B16' }}>{children}</div>
  </div>
);

/* ---- badges de loja (sem logos de terceiros) ---- */
const StoreBadge = ({ kind }) => {
  const apple = kind === 'apple';
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 11, padding: '9px 18px', borderRadius: 13, background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.14)', cursor: 'pointer', transition: 'border-color 220ms, background 220ms' }}
      onMouseEnter={e => { e.currentTarget.style.borderColor = 'rgba(0,94,255,0.45)'; e.currentTarget.style.background = 'rgba(0,94,255,0.08)'; }}
      onMouseLeave={e => { e.currentTarget.style.borderColor = 'rgba(255,255,255,0.14)'; e.currentTarget.style.background = 'rgba(255,255,255,0.03)'; }}>
      {apple ? (
        <svg width="20" height="22" viewBox="0 0 24 24" fill="#F5F8FF"><path d="M17.05 12.04c-.03-2.6 2.12-3.85 2.22-3.91-1.21-1.77-3.1-2.01-3.77-2.04-1.6-.16-3.13.94-3.94.94-.81 0-2.07-.92-3.4-.89-1.75.03-3.36 1.02-4.26 2.58-1.82 3.16-.47 7.83 1.3 10.39.86 1.25 1.89 2.66 3.24 2.61 1.3-.05 1.79-.84 3.36-.84 1.57 0 2.01.84 3.39.81 1.4-.03 2.28-1.28 3.14-2.54.99-1.45 1.4-2.86 1.42-2.93-.03-.01-2.72-1.04-2.75-4.13zM14.6 4.7c.72-.87 1.2-2.08 1.07-3.28-1.03.04-2.28.69-3.02 1.56-.66.77-1.24 2-1.08 3.18 1.15.09 2.32-.59 3.03-1.46z"/></svg>
      ) : (
        <svg width="19" height="22" viewBox="0 0 24 24"><defs><linearGradient id="gp" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stopColor="#00D4FF"/><stop offset="1" stopColor="#005EFF"/></linearGradient></defs><path d="M3.5 2.2c-.3.2-.5.6-.5 1.1v17.4c0 .5.2.9.5 1.1l9.3-9.8L3.5 2.2z" fill="url(#gp)"/><path d="M16.8 8.3l-3.4-1.97-2.6 2.74 2.6 2.73 3.42-1.97c.86-.5.86-1.03-.02-1.53z" fill="#F5F8FF"/><path d="M12.8 11.8l-9.3 9.8c.3.2.7.2 1.2-.07l11.1-6.4-3-3.33z" fill="#7CB0FF"/><path d="M12.8 11.8l3-3.33L4.7 2.07C4.2 1.8 3.8 1.8 3.5 2.0l9.3 9.8z" fill="#3D8BFF"/></svg>
      )}
      <div style={{ lineHeight: 1.15 }}>
        <div style={{ fontFamily: 'var(--ar-font-body)', fontSize: 10, color: '#A7B0C5', letterSpacing: '0.04em' }}>{apple ? 'Disponível na' : 'Disponível no'}</div>
        <div style={{ fontFamily: 'var(--ar-font-title)', fontSize: 15, fontWeight: 700, color: '#F5F8FF' }}>{apple ? 'App Store' : 'Google Play'}</div>
      </div>
    </div>
  );
};

/* ---- rótulo leve de dispositivo (nome + papel) ---- */
const DeviceLabel = ({ name, role, style }) => (
  <div style={{ position: 'absolute', textAlign: 'center', whiteSpace: 'nowrap', transform: 'translateX(-50%)', fontFamily: 'var(--ar-font-body)', textTransform: 'uppercase', ...style }}>
    <span style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.18em', color: 'var(--ar-text-muted)' }}>{name}</span>
    {role && <span style={{ fontSize: 10, fontWeight: 500, letterSpacing: '0.16em', color: 'var(--ar-text-dim)' }}> · {role}</span>}
  </div>
);

/* ---- a seção ---- */
const AppShowcase = () => {
  const [active, setActive] = React.useState(0);
  const [paused, setPaused] = React.useState(false);
  const [narrow, setNarrow] = React.useState(false);
  const m = AR_MODULES[active];

  React.useEffect(() => {
    const mq = window.matchMedia('(max-width: 860px)');
    const on = () => setNarrow(mq.matches);
    on(); mq.addEventListener('change', on);
    return () => mq.removeEventListener('change', on);
  }, []);

  // recriar ícones lucide a cada troca de módulo / layout
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });

  // auto-rotação (pausa ao interagir / hover)
  React.useEffect(() => {
    if (paused) return;
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduce) return;
    const t = setInterval(() => setActive(a => (a + 1) % AR_MODULES.length), 4600);
    return () => clearInterval(t);
  }, [paused]);

  const pick = (i) => { setActive(i); setPaused(true); };

  return (
    <section id="apps" style={{ position: 'relative', background: 'var(--ar-bg-main)', padding: '116px 0', overflow: 'hidden' }}>
      {/* glow de fundo */}
      <div style={{ position: 'absolute', top: '12%', left: '50%', transform: 'translateX(-50%)', width: 1100, height: 620, background: 'radial-gradient(ellipse at center, rgba(0,94,255,0.20), transparent 62%)', pointerEvents: 'none', filter: 'blur(8px)' }} />

      <Container style={{ position: 'relative' }}>
        <SectionHead
          align="center" maxWidth={820}
          eyebrow="PRODUTO · APPS COM IA"
          title={<>Apps web e mobile com <GradText>IA, sob medida</GradText> para a sua operação</>}
          sub="Construímos o sistema da sua empresa — web app, tablet e aplicativo para iOS e Android — com inteligência artificial integrada à gestão, atendimento, financeiro, estoque, vendas e RH. Tudo em um só lugar."
        />

        {/* abas de módulo */}
        <Reveal delay={100}>
          <div className="apps-tabs" style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'center', gap: 10, margin: '34px auto 8px', maxWidth: 760 }}>
            {AR_MODULES.map((mod, i) => {
              const on = i === active;
              return (
                <button key={mod.id} onClick={() => pick(i)} style={{
                  display: 'inline-flex', alignItems: 'center', gap: 8, cursor: 'pointer',
                  fontFamily: 'var(--ar-font-body)', fontSize: 13.5, fontWeight: 500,
                  padding: '9px 16px', borderRadius: 999,
                  color: on ? '#fff' : 'var(--ar-text-muted)',
                  background: on ? 'linear-gradient(135deg,#005EFF,#00D4FF)' : 'rgba(255,255,255,0.025)',
                  border: `1px solid ${on ? 'transparent' : 'rgba(255,255,255,0.10)'}`,
                  boxShadow: on ? '0 6px 18px -8px rgba(0,94,255,0.55)' : 'none',
                  transition: 'all 220ms var(--ar-ease)',
                }}>
                  <i data-lucide={mod.icon} style={{ width: 15, height: 15 }}></i>{mod.label}
                </button>
              );
            })}
          </div>
        </Reveal>

        {/* palco dos dispositivos */}
        <Reveal delay={140}>
          <div
            onMouseEnter={() => setPaused(true)}
            style={{ marginTop: 30, position: 'relative' }}
          >
            {narrow ? (
              /* ---------- mobile: pilha web app → tablet → mobile ---------- */
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 40 }}>
                <div style={{ width: '100%', maxWidth: 540, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                  <DeviceLabel name="Web app" role="Desktop" style={{ position: 'static', transform: 'none', marginBottom: 14 }} />
                  <ScaleBox designW={720} designH={468}>
                    <BrowserFrame style={{ width: 720, height: 468 }}><WebAppScreen m={m} /></BrowserFrame>
                  </ScaleBox>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                  <DeviceLabel name="Tablet" role="Visão gerencial" style={{ position: 'static', transform: 'none', marginBottom: 14 }} />
                  <TabletFrame style={{ width: 300, height: 432 }}><TabletScreen m={m} /></TabletFrame>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                  <DeviceLabel name="Mobile" role="App operacional" style={{ position: 'static', transform: 'none', marginBottom: 14 }} />
                  <PhoneFrame style={{ width: 240, height: 488 }}><PhoneAppScreen m={m} /></PhoneFrame>
                </div>
              </div>
            ) : (
              /* ---------- desktop: tríptico minimalista, web app protagonista ---------- */
              <ScaleBox designW={1200} designH={510}>
                <div style={{ position: 'relative', width: 1200, height: 510 }}>
                  {/* brilho de chão sutil sob os aparelhos */}
                  <div style={{ position: 'absolute', left: 180, right: 180, bottom: 40, height: 110, background: 'radial-gradient(ellipse at center, rgba(0,94,255,0.14), transparent 72%)', filter: 'blur(14px)', pointerEvents: 'none' }} />
                  {/* tablet (apoio esquerdo, menor, só o bezel encosta atrás) */}
                  <TabletFrame style={{ position: 'absolute', left: 52, top: 124, width: 232, height: 344, zIndex: 1 }}>
                    <TabletScreen m={m} />
                  </TabletFrame>
                  <DeviceLabel name="Tablet" role="Visão gerencial" style={{ left: 168, top: 484 }} />
                  {/* web app (protagonista, centrado) */}
                  <BrowserFrame style={{ position: 'absolute', left: 270, top: 40, width: 660, height: 428, zIndex: 2 }}>
                    <WebAppScreen m={m} />
                  </BrowserFrame>
                  <DeviceLabel name="Web app" role="Desktop" style={{ left: 600, top: 484 }} />
                  {/* celular (apoio direito, menor, só a borda encosta à frente) */}
                  <PhoneFrame style={{ position: 'absolute', left: 918, top: 64, width: 188, height: 404, zIndex: 3 }}>
                    <PhoneAppScreen m={m} />
                  </PhoneFrame>
                  <DeviceLabel name="Mobile" role="App operacional" style={{ left: 1012, top: 484 }} />
                </div>
              </ScaleBox>
            )}
          </div>
        </Reveal>

        {/* legenda + badges de loja */}
        <Reveal delay={120}>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 20, marginTop: 38 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9, fontFamily: 'var(--ar-font-body)', fontSize: 13.5, color: 'var(--ar-text-dim)', textAlign: 'center' }}>
              <i data-lucide="info" style={{ width: 15, height: 15, color: 'var(--ar-cyan)' }}></i>
              Interfaces ilustrativas — cada módulo é personalizado para a realidade do seu negócio.
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'center', gap: 14 }}>
              <StoreBadge kind="apple" />
              <StoreBadge kind="play" />
              <Button size="lg" onClick={() => { const el = document.getElementById('contato'); if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 76, behavior: 'smooth' }); }}>
                Solicitar demonstração <i data-lucide="arrow-right" style={{ width: 18, height: 18 }}></i>
              </Button>
            </div>
          </div>
        </Reveal>
      </Container>
    </section>
  );
};

window.AppShowcase = AppShowcase;
