// Top sections: Header, Hero, Logo strip, Pain points
const { motion: m, useScroll: useScroll_, useTransform: useTransform_, AnimatePresence: AP } = window.framerMotion || {};
const { Button, Eyebrow, Pill, Reveal, Stagger, StaggerItem, CountUp, Section, Container, AnimatedHeading, AnimatedHeadingSplit, MockupChrome, prefersReducedMotion } = window.UI;
const { AgendaMockup, ProntuarioMockup, AudiometriaMockup, RepasseMockup, CheckinMockup, PainelTVMockup } = window.Mockups;

// Brand logo (uses uploaded asset)
function CliniSetLogo({ className = '', dark = false, compact = false }) {
  return (
    <div className={`inline-flex items-center gap-2.5 ${className}`}>
      <img src="assets/logo-cliniset.png" alt="CliniSet" className="h-8 w-auto select-none" draggable="false" style={{ filter: dark ? 'brightness(0) invert(1)' : 'none' }}/>
    </div>
  );
}

// ===== HEADER =====
function Header({ dark, setDark }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [mobile, setMobile] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 30);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const links = [
    ['Funcionalidades', '#funcionalidades'],
    ['Demonstração', '#demo'],
    ['Para quem', '#personas'],
    ['Preços', '#precos'],
    ['Migração', '#migracao'],
    ['FAQ', '#faq'],
  ];
  return (
    <header className={`fixed top-0 inset-x-0 z-50 transition-all duration-300 ${scrolled ? 'backdrop-blur-md bg-white/70 dark:bg-ink-900/70 border-b border-ink-200/60 dark:border-ink-800/80' : 'border-b border-transparent'}`}>
      <Container className="flex items-center justify-between h-16">
        <a href="#" className="flex items-center gap-2.5">
          <img src="assets/logo-cliniset-alpha.png" alt="CliniSet" className="h-8 w-auto block dark:hidden" draggable="false"/>
          <img src="assets/logo-cliniset-dark.png" alt="CliniSet" className="h-8 w-auto hidden dark:block" draggable="false"/>
        </a>
        <nav className="hidden lg:flex items-center gap-1 text-[13px]">
          {links.map(([l, h]) => (
            <a key={l} href={h} className="px-3 h-9 inline-flex items-center rounded-lg text-ink-600 dark:text-ink-300 hover:text-ink-900 dark:hover:text-white hover:bg-ink-100 dark:hover:bg-ink-800/60 transition-colors">{l}</a>
          ))}
        </nav>
        <div className="flex items-center gap-1.5">
          <button onClick={() => setDark(!dark)} aria-label="Alternar tema" className="w-9 h-9 inline-flex items-center justify-center rounded-lg text-ink-600 dark:text-ink-300 hover:bg-ink-100 dark:hover:bg-ink-800/60">
            {dark ? <I.Sun className="w-4 h-4"/> : <I.Moon className="w-4 h-4"/>}
          </button>
          <a href="#" className="hidden sm:inline-flex h-9 px-3.5 items-center text-[13px] font-medium rounded-lg text-ink-700 dark:text-ink-200 hover:bg-ink-100 dark:hover:bg-ink-800/60">Entrar</a>
          <Button size="sm" magnetic className="ml-1">Ver demonstração <I.ArrowRight className="w-3.5 h-3.5"/></Button>
          <button onClick={() => setMobile(!mobile)} aria-label="Menu" className="lg:hidden w-9 h-9 inline-flex items-center justify-center rounded-lg text-ink-700 dark:text-ink-200 hover:bg-ink-100 dark:hover:bg-ink-800/60 ml-1">
            {mobile ? <I.X className="w-4 h-4"/> : <I.Menu className="w-4 h-4"/>}
          </button>
        </div>
      </Container>
      {AP && (
        <AP>
          {mobile && (
            <m.div initial={{ height: 0, opacity: 0 }} animate={{ height: 'auto', opacity: 1 }} exit={{ height: 0, opacity: 0 }} className="lg:hidden overflow-hidden border-t border-ink-200/60 dark:border-ink-800 bg-white dark:bg-ink-900">
              <div className="px-5 py-3 space-y-1">
                {links.map(([l, h]) => (
                  <a key={l} href={h} onClick={() => setMobile(false)} className="block px-3 py-2.5 rounded-lg text-[14px] text-ink-700 dark:text-ink-200 hover:bg-ink-100 dark:hover:bg-ink-800/60">{l}</a>
                ))}
              </div>
            </m.div>
          )}
        </AP>
      )}
    </header>
  );
}

// ===== HERO =====
function Hero() {
  const ref = React.useRef(null);
  const { scrollY, scrollYProgress } = useScroll_ ? useScroll_({ target: ref, offset: ['start start', 'end start'] }) : { scrollY: null, scrollYProgress: null };
  const sceneRotY = scrollYProgress && useTransform_ ? useTransform_(scrollYProgress, [0, 1], [0, 90]) : 0;
  const sceneRotX = scrollYProgress && useTransform_ ? useTransform_(scrollYProgress, [0, 1], [0, 30]) : 0;
  const sceneScale = scrollYProgress && useTransform_ ? useTransform_(scrollYProgress, [0, 1], [1, 0.65]) : 1;
  const sceneOpacity = scrollYProgress && useTransform_ ? useTransform_(scrollYProgress, [0, 0.85], [1, 0]) : 1;
  const textY = scrollY && useTransform_ ? useTransform_(scrollY, [0, 600], [0, -120]) : 0;
  const textOp = scrollY && useTransform_ ? useTransform_(scrollY, [0, 500], [1, 0]) : 1;

  // Mouse-driven scene tilt (parallax)
  const [tilt, setTilt] = React.useState({ x: 0, y: 0 });
  React.useEffect(() => {
    if (prefersReducedMotion) return;
    const onMove = (e) => {
      const cx = window.innerWidth / 2;
      const cy = window.innerHeight / 2;
      setTilt({
        x: ((e.clientY - cy) / cy) * -8,
        y: ((e.clientX - cx) / cx) * 10,
      });
    };
    window.addEventListener('mousemove', onMove);
    return () => window.removeEventListener('mousemove', onMove);
  }, []);

  return (
    <Section id="hero" ref={ref} className="relative pt-24 lg:pt-32 pb-20 lg:pb-32 overflow-hidden min-h-[100vh]">
      {/* Layered background */}
      <div className="absolute inset-0 bg-grid bg-radial-fade pointer-events-none"/>
      <div className="absolute inset-0 pointer-events-none">
        <div className="absolute top-1/3 left-1/2 -translate-x-1/2 w-[1400px] h-[700px] conic-glow blur-3xl opacity-40 animate-spin-slow"/>
        <div className="absolute bottom-0 left-0 w-[600px] h-[400px] bg-cyan-500/10 blur-3xl rounded-full"/>
        <div className="absolute top-1/4 right-0 w-[500px] h-[500px] bg-brand-500/15 blur-3xl rounded-full"/>
      </div>
      {/* Decorative noise grain */}
      <div className="absolute inset-0 opacity-[0.04] pointer-events-none mix-blend-overlay" style={{ backgroundImage: 'url("data:image/svg+xml,%3Csvg viewBox=\'0 0 200 200\' xmlns=\'http://www.w3.org/2000/svg\'%3E%3Cfilter id=\'n\'%3E%3CfeTurbulence type=\'fractalNoise\' baseFrequency=\'0.9\'/%3E%3C/filter%3E%3Crect width=\'100%25\' height=\'100%25\' filter=\'url(%23n)\'/%3E%3C/svg%3E")'}}/>

      <Container className="relative">
        <div className="grid lg:grid-cols-[1.05fr_1.1fr] gap-10 lg:gap-12 items-center">
          {/* Left — copy */}
          {m ? (
            <m.div style={{ y: textY, opacity: textOp }}>
              {/* Eyebrow removed at request */}
              <AnimatedHeadingSplit
                pre={"Menos retrabalho da Recepção ao Prontuário. Mais resultado no fim do mês."}
                highlight={"Um sistema feito pra hoje."}
                className="font-display font-bold leading-[1.0]"
              />
              <style>{`#hero h1 { font-size: clamp(1.4rem, 2.8vw, 2.3rem); letter-spacing: -0.035em; line-height: 1.1; } #hero h1 .hl { background: linear-gradient(135deg, #0EA5E9 0%, #3DD0FF 50%, #15324D 100%); -webkit-background-clip: text; background-clip: text; color: transparent; }`}</style>
              <Reveal delay={0.4}>
                <p className="mt-7 text-[17px] sm:text-[18px] leading-relaxed text-ink-600 dark:text-ink-300 max-w-xl text-pretty">
                  O sistema feito só pra clínicas de <span className="text-ink-900 dark:text-white font-medium">Otorrinolaringologia e Fonoaudiologia</span>. <span className="text-ink-900 dark:text-white font-medium">IA Clínica</span> que sugere o diagnóstico, <span className="text-ink-900 dark:text-white font-medium">faturamento</span> e <span className="text-ink-900 dark:text-white font-medium">assinatura digital ICP-Brasil</span> no automático, e <span className="text-ink-900 dark:text-white font-medium">campanhas que reagendam</span> o paciente a cada ciclo. Com migração assistida do sistema atual da sua clínica.
                </p>
              </Reveal>
              <Reveal delay={0.55}>
                <div className="mt-8 flex flex-wrap items-center gap-3">
                  <Button size="lg" magnetic>Agendar demonstração <I.ArrowRight className="w-4 h-4"/></Button>
                  <Button size="lg" variant="ghost" magnetic><I.Play className="w-3.5 h-3.5"/> Ver tour de 2 min</Button>
                </div>
              </Reveal>
              <Reveal delay={0.7}>
                <div className="mt-8 flex flex-wrap gap-x-5 gap-y-2 text-[12px] text-ink-500 dark:text-ink-400">
                  {['LGPD', 'CFM/CFFa', 'ICP-Brasil', 'ISO 27001'].map(t => (
                    <span key={t} className="inline-flex items-center gap-1.5"><I.Check className="w-3.5 h-3.5 text-emerald-500"/>{t}</span>
                  ))}
                </div>
              </Reveal>
            </m.div>
          ) : null}

          {/* Right — 3D orbital scene */}
          <div className="relative h-[560px] lg:h-[640px] [perspective:1800px]">
            {m && (
              <m.div
                style={{
                  rotateY: sceneRotY,
                  rotateX: sceneRotX,
                  scale: sceneScale,
                  opacity: sceneOpacity,
                  transformStyle: 'preserve-3d',
                }}
                className="absolute inset-0"
              >
                <m.div
                  style={{ rotateX: tilt.x, rotateY: tilt.y, transformStyle: 'preserve-3d' }}
                  transition={{ type: 'spring', stiffness: 60, damping: 20 }}
                  className="absolute inset-0"
                >
                  <OrbitalScene/>
                </m.div>
              </m.div>
            )}
          </div>
        </div>
      </Container>

      {/* Scroll cue */}
      {m && (
        <m.div
          initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 1.6, duration: 0.8 }}
          className="absolute left-1/2 -translate-x-1/2 bottom-6 lg:bottom-10 flex flex-col items-center gap-2 text-ink-500 dark:text-ink-400 pointer-events-none"
        >
          <span className="text-[10px] uppercase tracking-[0.2em] font-mono">Role para explorar</span>
          <m.div
            animate={{ y: [0, 8, 0] }} transition={{ duration: 1.8, repeat: Infinity, ease: 'easeInOut' }}
            className="w-5 h-8 rounded-full border border-current flex items-start justify-center pt-1.5"
          >
            <span className="w-0.5 h-1.5 rounded-full bg-current"/>
          </m.div>
        </m.div>
      )}
    </Section>
  );
}

// ===== ORBITAL SCENE =====
// Logo at the center of a slowly-rotating 3D ring; product cards float on
// independent orbits at different radii and tilts. Built entirely with
// CSS 3D transforms — no WebGL.
function OrbitalScene() {
  // Continuous rotation of the inner stack
  const [t, setT] = React.useState(0);
  React.useEffect(() => {
    if (prefersReducedMotion) return;
    let raf, start;
    const loop = (ts) => {
      if (!start) start = ts;
      setT((ts - start) / 1000);
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);

  const innerRot = t * 6; // deg/s

  // Floating product cards — placed on a virtual sphere
  const cards = [
    { kind: 'agenda',     orbitR: 360, ang: 0,    yOff: -110, scale: 0.46, tiltY: -18, tiltX: 6 },
    { kind: 'prontuario', orbitR: 380, ang: 110,  yOff: 70,   scale: 0.44, tiltY: 14,  tiltX: -4 },
    { kind: 'audio',      orbitR: 300, ang: 215,  yOff: 160,  scale: 0.85, tiltY: -10, tiltX: -8 },
    { kind: 'checkin',    orbitR: 320, ang: 305,  yOff: -80,  scale: 0.92, tiltY: 16,  tiltX: 6 },
  ];

  // tiny floating chips
  const chips = [
    { ang: 60,  r: 250, txt: 'CID-10 H93.1 · 92%',     icon: 'Sparkles', tone: 'cyan',    yOff: -180 },
    { ang: 165, r: 230, txt: 'NFS-e emitida',          icon: 'CheckCircle', tone: 'emerald', yOff: 130 },
    { ang: 270, r: 260, txt: 'Assinatura ICP-Brasil',  icon: 'Stamp',    tone: 'amber',   yOff: -160 },
    { ang: 350, r: 220, txt: 'Repasse R$ 51.890,40',   icon: 'Wallet',   tone: 'cyan',    yOff: 180 },
  ];

  const renderMock = (kind) => {
    if (kind === 'agenda')     return <div style={{ transform: 'scale(1)', transformOrigin: 'top left' }}><AgendaMockup/></div>;
    if (kind === 'prontuario') return <div><ProntuarioMockup/></div>;
    if (kind === 'audio')      return <AudiometriaMockup/>;
    if (kind === 'checkin')    return <CheckinMockup/>;
  };

  return (
    <div className="absolute inset-0 flex items-center justify-center" style={{ transformStyle: 'preserve-3d' }}>
      {/* Orbital rings — purely decorative */}
      <div className="absolute" style={{ transformStyle: 'preserve-3d' }}>
        {[
          { r: 240, tilt: 65, color: 'rgba(14,165,233,0.25)' },
          { r: 320, tilt: 70, color: 'rgba(14,165,233,0.18)' },
          { r: 400, tilt: 75, color: 'rgba(14,165,233,0.12)' },
        ].map((ring, i) => (
          <div key={i}
            className="absolute rounded-full border"
            style={{
              width: ring.r * 2, height: ring.r * 2,
              top: -ring.r, left: -ring.r,
              borderColor: ring.color,
              transform: `rotateX(${ring.tilt}deg) rotateZ(${innerRot * (i + 1) * 0.3}deg)`,
              transformStyle: 'preserve-3d',
            }}
          >
            {/* Tracer dots on each ring */}
            {[0, 90, 180, 270].map((deg) => (
              <span key={deg}
                className="absolute w-1.5 h-1.5 rounded-full bg-cyan-400"
                style={{
                  top: '50%', left: '50%',
                  transform: `rotate(${deg}deg) translateX(${ring.r}px) translateY(-3px)`,
                  boxShadow: '0 0 12px rgba(14,165,233,0.7)',
                  opacity: 0.8 - i * 0.2,
                }}
              />
            ))}
          </div>
        ))}
      </div>

      {/* Center: logo cube — 6 faces */}
      <div className="absolute" style={{ transformStyle: 'preserve-3d', transform: `rotateY(${innerRot}deg) rotateX(${innerRot * 0.3}deg)` }}>
        <LogoCube size={170}/>
        {/* Halo behind the cube */}
        <div className="absolute -inset-12 rounded-full bg-gradient-to-br from-cyan-500/30 via-cyan-400/20 to-brand-500/30 blur-3xl pointer-events-none"/>
      </div>

      {/* Floating product cards */}
      {cards.map((c, i) => {
        const ang = (c.ang + innerRot * 0.4) * Math.PI / 180;
        const x = Math.cos(ang) * c.orbitR;
        const z = Math.sin(ang) * c.orbitR * 0.4; // shallow Z to keep readable
        const wobble = Math.sin(t * 0.6 + i) * 12;
        return (
          <m.div
            key={i}
            initial={{ opacity: 0, scale: 0.6 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ delay: 0.6 + i * 0.15, duration: 0.8, ease: [0.16, 1, 0.3, 1] }}
            className="absolute pointer-events-none"
            style={{
              transform: `translate3d(${x}px, ${c.yOff + wobble}px, ${z}px) rotateY(${c.tiltY}deg) rotateX(${c.tiltX}deg)`,
              transformStyle: 'preserve-3d',
            }}
          >
            <div
              className="rounded-2xl shadow-float-dark overflow-hidden bg-ink-900 border border-ink-700/60"
              style={{
                transform: `scale(${c.scale})`,
                transformOrigin: 'center',
              }}
            >
              {renderMock(c.kind)}
            </div>
          </m.div>
        );
      })}

      {/* Floating chip badges */}
      {chips.map((c, i) => {
        const ang = (c.ang + innerRot * 0.7) * Math.PI / 180;
        const x = Math.cos(ang) * c.r;
        const z = Math.sin(ang) * c.r * 0.5;
        const Ic = I[c.icon];
        const tones = {
          cyan: 'bg-cyan-500/15 text-cyan-200 border-cyan-400/30',
          emerald: 'bg-emerald-500/15 text-emerald-200 border-emerald-400/30',
          amber: 'bg-amber-500/15 text-amber-200 border-amber-400/30',
        };
        return (
          <m.div
            key={i}
            initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 1 + i * 0.2 }}
            className={`absolute pointer-events-none px-3 py-1.5 rounded-full backdrop-blur-md border text-[11px] font-medium inline-flex items-center gap-1.5 whitespace-nowrap ${tones[c.tone]}`}
            style={{
              transform: `translate3d(${x}px, ${c.yOff}px, ${z}px)`,
              boxShadow: '0 8px 32px rgba(0,0,0,0.4)',
            }}
          >
            <Ic className="w-3 h-3"/> {c.txt}
          </m.div>
        );
      })}

      {/* Particles / sparkles */}
      {Array.from({ length: 16 }).map((_, i) => {
        const angle = (i / 16) * Math.PI * 2;
        const r = 180 + ((i * 53) % 240);
        const x = Math.cos(angle + t * 0.2) * r;
        const y = Math.sin(angle + t * 0.2) * r * 0.65;
        return (
          <span
            key={i}
            className="absolute w-1 h-1 rounded-full bg-cyan-300 pointer-events-none"
            style={{
              transform: `translate3d(${x}px, ${y}px, ${(i % 3 - 1) * 80}px)`,
              boxShadow: '0 0 8px rgba(61,208,255,0.8)',
              opacity: 0.4 + ((i * 7) % 5) / 10,
            }}
          />
        );
      })}
    </div>
  );
}

// ===== LOGO CUBE — 6 capability faces =====
// Each face shows one CliniSet superpower: glyph + label + accent color.
// The cube rotates so the user absorbs all 6 capabilities passively.
function LogoCube({ size = 170 }) {
  const half = size / 2;
  // 6 capabilities — each with a custom inline SVG glyph (NOT generic Lucide).
  // Each glyph is purpose-built for the use case: audiogram curves, signature
  // strokes, invoice with QR, weekly grid with appointments, etc.
  const capabilities = [
    {
      label: 'IA Clínica',
      sub: 'Sugestão de CID-10',
      stat: '14s',
      tone: { bg: 'rgba(14,165,233,0.18)', border: 'rgba(14,165,233,0.5)', glow: 'rgba(14,165,233,0.45)', text: '#67E8F9' },
      // Custom glyph: prescription pad with AI sparkle indicator + suggestion lines
      glyph: (color) => (
        <svg viewBox="0 0 64 64" fill="none" stroke={color} strokeLinecap="round" strokeLinejoin="round">
          <rect x="12" y="8" width="34" height="44" rx="3" strokeWidth="2"/>
          <path d="M19 19h12M19 26h20M19 33h16M19 40h10" strokeWidth="2" opacity="0.55"/>
          <circle cx="46" cy="46" r="10" fill={color} stroke="none" opacity="0.18"/>
          <path d="M46 38v6l4 2M40 46h12" strokeWidth="2.5"/>
          <path d="M52 14l1.5 3 3 1.5-3 1.5L52 23l-1.5-3-3-1.5 3-1.5z" fill={color} stroke="none"/>
          <path d="M58 22l0.7 1.4 1.4 0.7-1.4 0.7L58 26l-0.7-1.2-1.4-0.7 1.4-0.7z" fill={color} stroke="none" opacity="0.7"/>
        </svg>
      ),
    },
    {
      label: 'Assinatura ICP',
      sub: 'Receita digital',
      stat: 'A1·A3',
      tone: { bg: 'rgba(245,158,11,0.16)', border: 'rgba(245,158,11,0.45)', glow: 'rgba(245,158,11,0.4)', text: '#FCD34D' },
      // Custom glyph: handwritten signature stroke + ICP seal badge
      glyph: (color) => (
        <svg viewBox="0 0 64 64" fill="none" stroke={color} strokeLinecap="round" strokeLinejoin="round">
          <path d="M8 36c4-6 7-9 10-7s2 8-3 11 6-8 12-7 4 8-1 10 8-5 14-3" strokeWidth="2.5"/>
          <path d="M10 46h36" strokeWidth="1.5" opacity="0.4"/>
          <g transform="translate(44 12)">
            <circle r="11" stroke={color} strokeWidth="2" fill={color} fillOpacity="0.15"/>
            <circle r="7" stroke={color} strokeWidth="1" opacity="0.5"/>
            <path d="M-3.5 0l2.5 2.5L4 -3" strokeWidth="2.5"/>
            <text y="-13" textAnchor="middle" fontSize="5" fill={color} fontFamily="ui-monospace, monospace" fontWeight="700" letterSpacing="0.5">ICP</text>
          </g>
        </svg>
      ),
    },
    {
      label: 'NFS-e auto',
      sub: '20+ municípios',
      stat: '<2s',
      tone: { bg: 'rgba(16,185,129,0.18)', border: 'rgba(16,185,129,0.5)', glow: 'rgba(16,185,129,0.4)', text: '#6EE7B7' },
      // Custom glyph: invoice document with QR code grid
      glyph: (color) => (
        <svg viewBox="0 0 64 64" fill="none" stroke={color} strokeLinecap="round" strokeLinejoin="round">
          <path d="M14 6h26l8 8v40a2 2 0 0 1-2 2H14a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z" strokeWidth="2"/>
          <path d="M40 6v8h8" strokeWidth="2"/>
          <text x="18" y="28" fontSize="8" fontWeight="700" fontFamily="ui-monospace, monospace" fill={color} letterSpacing="1">NFS-e</text>
          <path d="M18 35h28M18 40h22" strokeWidth="1.5" opacity="0.4"/>
          {/* QR code mini */}
          <g transform="translate(20 44)">
            <rect width="3" height="3" fill={color}/>
            <rect x="5" width="3" height="3" fill={color}/>
            <rect x="10" width="3" height="3" fill={color}/>
            <rect x="15" width="3" height="3" fill={color}/>
            <rect x="20" width="3" height="3" fill={color} opacity="0.5"/>
            <rect y="5" width="3" height="3" fill={color}/>
            <rect x="10" y="5" width="3" height="3" fill={color}/>
            <rect x="20" y="5" width="3" height="3" fill={color}/>
            <rect y="10" width="3" height="3" fill={color}/>
            <rect x="5" y="10" width="3" height="3" fill={color}/>
            <rect x="15" y="10" width="3" height="3" fill={color}/>
          </g>
        </svg>
      ),
    },
    {
      label: 'Agenda',
      sub: 'Sem conflito',
      stat: 'Realtime',
      tone: { bg: 'rgba(99,102,241,0.18)', border: 'rgba(129,140,248,0.5)', glow: 'rgba(99,102,241,0.4)', text: '#A5B4FC' },
      // Custom glyph: weekly grid view with filled appointment blocks (not generic calendar)
      glyph: (color) => (
        <svg viewBox="0 0 64 64" fill="none" stroke={color} strokeLinecap="round" strokeLinejoin="round">
          <rect x="8" y="12" width="48" height="44" rx="3" strokeWidth="2"/>
          <path d="M8 22h48" strokeWidth="2"/>
          <path d="M20 8v8M44 8v8" strokeWidth="2"/>
          {/* Time grid lines */}
          <path d="M8 32h48M8 42h48M8 52h48" strokeWidth="0.8" opacity="0.3"/>
          <path d="M20 22v34M32 22v34M44 22v34" strokeWidth="0.8" opacity="0.3"/>
          {/* Filled appointment blocks */}
          <rect x="10" y="24" width="9" height="6" rx="1" fill={color} opacity="0.85"/>
          <rect x="22" y="24" width="9" height="10" rx="1" fill={color} opacity="0.55"/>
          <rect x="34" y="34" width="9" height="8" rx="1" fill={color} opacity="0.7"/>
          <rect x="46" y="44" width="8" height="6" rx="1" fill={color} opacity="0.5"/>
          <rect x="22" y="44" width="9" height="9" rx="1" fill={color} opacity="0.85"/>
        </svg>
      ),
    },
    {
      label: 'Audiometria',
      sub: 'Laudo automático',
      stat: 'PTA·SDR',
      tone: { bg: 'rgba(236,72,153,0.18)', border: 'rgba(236,72,153,0.45)', glow: 'rgba(236,72,153,0.4)', text: '#F9A8D4' },
      // Custom glyph: real audiogram — frequency on X, dB on Y, with O markers
      glyph: (color) => (
        <svg viewBox="0 0 64 64" fill="none" stroke={color} strokeLinecap="round" strokeLinejoin="round">
          <path d="M8 8v48h48" strokeWidth="2"/>
          {/* Grid */}
          <path d="M8 18h48M8 28h48M8 38h48M8 48h48" strokeWidth="0.5" opacity="0.3"/>
          <path d="M18 8v48M28 8v48M38 8v48M48 8v48" strokeWidth="0.5" opacity="0.3"/>
          {/* Right ear curve (O) — descending */}
          <path d="M14 18 L24 20 L34 24 L44 32 L54 42" strokeWidth="2"/>
          <circle cx="14" cy="18" r="2.5" fill="none" strokeWidth="1.5"/>
          <circle cx="24" cy="20" r="2.5" fill="none" strokeWidth="1.5"/>
          <circle cx="34" cy="24" r="2.5" fill="none" strokeWidth="1.5"/>
          <circle cx="44" cy="32" r="2.5" fill="none" strokeWidth="1.5"/>
          <circle cx="54" cy="42" r="2.5" fill="none" strokeWidth="1.5"/>
          {/* Left ear curve (X) — opacity */}
          <path d="M14 22 L24 24 L34 28 L44 36 L54 46" strokeWidth="1.5" opacity="0.5"/>
          {/* Axis labels */}
          <text x="4" y="14" fontSize="4" fill={color} opacity="0.6" fontFamily="ui-monospace, monospace">dB</text>
          <text x="56" y="60" fontSize="4" fill={color} opacity="0.6" fontFamily="ui-monospace, monospace">Hz</text>
        </svg>
      ),
    },
    {
      label: 'Repasse',
      sub: 'Fechamento mensal',
      stat: 'R$',
      tone: { bg: 'rgba(20,184,166,0.18)', border: 'rgba(20,184,166,0.5)', glow: 'rgba(20,184,166,0.4)', text: '#5EEAD4' },
      // Custom glyph: stacked bar chart + R$ symbol — financial data
      glyph: (color) => (
        <svg viewBox="0 0 64 64" fill="none" stroke={color} strokeLinecap="round" strokeLinejoin="round">
          {/* Baseline */}
          <path d="M8 52h48" strokeWidth="2"/>
          {/* Stacked bars */}
          <g>
            <rect x="12" y="36" width="8" height="16" rx="1" fill={color} opacity="0.4"/>
            <rect x="12" y="28" width="8" height="8" rx="1" fill={color} opacity="0.7"/>
            <rect x="22" y="32" width="8" height="20" rx="1" fill={color} opacity="0.4"/>
            <rect x="22" y="22" width="8" height="10" rx="1" fill={color} opacity="0.7"/>
            <rect x="22" y="16" width="8" height="6" rx="1" fill={color}/>
            <rect x="32" y="40" width="8" height="12" rx="1" fill={color} opacity="0.4"/>
            <rect x="32" y="34" width="8" height="6" rx="1" fill={color} opacity="0.7"/>
            <rect x="42" y="24" width="8" height="28" rx="1" fill={color} opacity="0.4"/>
            <rect x="42" y="14" width="8" height="10" rx="1" fill={color} opacity="0.7"/>
            <rect x="42" y="8" width="8" height="6" rx="1" fill={color}/>
          </g>
          {/* R$ symbol top-right */}
          <g transform="translate(50 8)">
            <text fontSize="10" fontWeight="800" fill={color} fontFamily="ui-sans-serif, system-ui">R$</text>
          </g>
        </svg>
      ),
    },
  ];

  const faces = [
    { transform: `translateZ(${half}px)` },
    { transform: `rotateY(180deg) translateZ(${half}px)` },
    { transform: `rotateY(90deg) translateZ(${half}px)` },
    { transform: `rotateY(-90deg) translateZ(${half}px)` },
    { transform: `rotateX(90deg) translateZ(${half}px)` },
    { transform: `rotateX(-90deg) translateZ(${half}px)` },
  ];

  return (
    <div className="relative" style={{ width: size, height: size, transformStyle: 'preserve-3d' }}>
      {faces.map((f, i) => {
        const cap = capabilities[i];
        return (
          <div
            key={i}
            className="absolute inset-0 rounded-2xl border backdrop-blur-md flex flex-col items-center justify-center overflow-hidden"
            style={{
              transform: f.transform,
              background: `linear-gradient(140deg, ${cap.tone.bg} 0%, rgba(15,23,42,0.65) 100%)`,
              borderColor: cap.tone.border,
              boxShadow: `inset 0 1px 0 rgba(255,255,255,0.12), 0 0 36px ${cap.tone.glow}`,
            }}
          >
            {/* Stat chip — top right */}
            <div className="absolute top-2.5 right-2.5 px-1.5 py-0.5 rounded text-[8px] font-mono font-semibold tracking-wide uppercase" style={{ background: 'rgba(0,0,0,0.35)', color: cap.tone.text, border: `1px solid ${cap.tone.border}` }}>
              {cap.stat}
            </div>
            {/* Brand mark — top left */}
            <div className="absolute top-2.5 left-2.5">
              <span className="block w-1.5 h-1.5 rounded-full" style={{ background: cap.tone.text, boxShadow: `0 0 8px ${cap.tone.glow}` }}/>
            </div>
            {/* Hero glyph — custom inline SVG */}
            <div
              className="flex items-center justify-center rounded-2xl mb-2"
              style={{
                width: size * 0.46, height: size * 0.46,
                background: `radial-gradient(circle at 30% 30%, ${cap.tone.bg}, transparent 70%)`,
              }}
            >
              <div style={{ width: size * 0.40, height: size * 0.40 }}>
                {cap.glyph(cap.tone.text)}
              </div>
            </div>
            {/* Label */}
            <div className="text-white font-display font-semibold text-center px-2 leading-tight" style={{ fontSize: size * 0.10, letterSpacing: '-0.02em' }}>{cap.label}</div>
            <div className="text-white/55 font-mono uppercase tracking-wider text-center mt-1" style={{ fontSize: size * 0.055 }}>{cap.sub}</div>

            {/* Edge highlight */}
            <div className="absolute inset-0 rounded-2xl pointer-events-none" style={{ background: 'radial-gradient(circle at 25% 15%, rgba(255,255,255,0.18), transparent 55%)' }}/>
            {/* Bottom CliniSet wordmark micro */}
            <div className="absolute bottom-2 left-1/2 -translate-x-1/2 text-white/25 font-mono uppercase tracking-[0.25em]" style={{ fontSize: size * 0.045 }}>CliniSet</div>
          </div>
        );
      })}
    </div>
  );
}

// ===== LOGO STRIP =====
function LogoStrip() {
  // Custom-drawn wordmark logos
  const logos = [
    { name: 'Clínica Dr Emerson Monteiro', el: (<g><circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="1.5" fill="none"/><path d="M8 14c1.5-2 3-3 4-3s2.5 1 4 3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" fill="none"/><text x="32" y="16" fontSize="13" fontWeight="700" fill="currentColor" letterSpacing="-0.02em">Dr Emerson</text></g>) },
    { name: 'OtoMed', el: (<g><path d="M4 12h16M4 8h12M4 16h10" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/><text x="28" y="16" fontSize="14" fontWeight="800" fill="currentColor" letterSpacing="-0.04em">OtoMed</text></g>) },
    { name: 'Audiophono', el: (<g><circle cx="11" cy="12" r="7" stroke="currentColor" strokeWidth="1.5" fill="none"/><circle cx="11" cy="12" r="3" fill="currentColor"/><text x="24" y="16" fontSize="13" fontWeight="700" fill="currentColor" letterSpacing="-0.03em" fontStyle="italic">audiophono</text></g>) },
    { name: 'Otorrino+', el: (<g><path d="M7 6v12M3 12h12" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"/><text x="20" y="16" fontSize="13" fontWeight="800" fill="currentColor">OTORRINO+</text></g>) },
    { name: 'Voz & Vida', el: (<g><path d="M5 14c2-6 6-6 8 0s6 6 8 0" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round"/><text x="6" y="22" fontSize="11" fontWeight="600" fill="currentColor" letterSpacing="0.04em">VOZ &amp; VIDA</text></g>) },
    { name: 'Audire', el: (<g><path d="M14 5a7 7 0 0 0-7 7v3a3 3 0 0 0 3 3v-6" stroke="currentColor" strokeWidth="1.8" fill="none" strokeLinecap="round"/><text x="22" y="16" fontSize="14" fontWeight="700" fill="currentColor" fontStyle="italic">Audire</text></g>) },
    { name: 'Vida Clara', el: (<g><circle cx="10" cy="12" r="6" stroke="currentColor" strokeWidth="1.5" fill="none"/><path d="M10 8v8M6 12h8" stroke="currentColor" strokeWidth="1.5"/><text x="20" y="16" fontSize="13" fontWeight="600" fill="currentColor" letterSpacing="0.02em">vida clara</text></g>) },
    { name: 'Núcleo Fono', el: (<g><circle cx="11" cy="12" r="3" fill="currentColor"/><circle cx="11" cy="12" r="7" stroke="currentColor" strokeWidth="1" fill="none" opacity="0.5"/><text x="22" y="16" fontSize="12" fontWeight="700" fill="currentColor">NÚCLEO FONO</text></g>) },
  ];

  return (
    <Section className="py-14 border-y border-ink-200/60 dark:border-ink-800/80">
      <Container>
        <Reveal>
          <div className="text-center text-[12px] text-ink-500 dark:text-ink-400 mb-7">Já é o sistema de gestão de</div>
        </Reveal>
        <div className="mask-fade-x overflow-hidden">
          <div className="flex animate-marquee gap-12" style={{ width: 'max-content' }}>
            {[...logos, ...logos].map((l, i) => (
              <div key={i} className="flex items-center justify-center text-ink-400 dark:text-ink-500 hover:text-ink-700 dark:hover:text-ink-200 transition-colors" style={{ minWidth: 200, height: 36 }}>
                <svg viewBox="0 0 180 24" className="h-6 w-auto" aria-label={l.name}>{l.el}</svg>
              </div>
            ))}
          </div>
        </div>
      </Container>
    </Section>
  );
}

// ===== PAIN POINTS =====
function PainPoints() {
  const cards = [
    {
      bad: 'Sua secretária ainda anota agendamento em caderno',
      good: 'Agenda em tempo real com check-in, fila visual e atrasados automáticos.',
      tag: 'Recepção',
      icon: <I.Calendar className="w-4 h-4"/>,
      tone: 'cyan',
    },
    {
      bad: 'Sua planilha de repasse falha em conciliar particular + convênio + SUS',
      good: 'Repasses por grupo de procedimento, fechamento mensal automático, contas a pagar integrado.',
      tag: 'Financeiro',
      icon: <I.Wallet className="w-4 h-4"/>,
      tone: 'emerald',
    },
    {
      bad: 'Você ainda imprime laudos em PDF e assina caneta',
      good: 'Assinatura digital ICP-Brasil em 1 clique, válida juridicamente.',
      tag: 'Legal',
      icon: <I.Stamp className="w-4 h-4"/>,
      tone: 'amber',
    },
  ];
  return (
    <Section id="pain" className="py-24 lg:py-32">
      <Container>
        <Reveal>
          <div className="max-w-2xl">
            <Eyebrow>Diagnóstico</Eyebrow>
            <h2 className="font-display font-bold text-[clamp(2rem,4vw,3.2rem)] tracking-tight leading-[1.05] mt-3 text-pretty">Três coisas que estão custando dinheiro pra sua clínica agora.</h2>
            <p className="mt-4 text-[16px] text-ink-600 dark:text-ink-300">Você sabe onde dói. Cliniset cuida de cada um deles, sem virar mais uma planilha pra preencher.</p>
          </div>
        </Reveal>
        <Stagger className="grid md:grid-cols-3 gap-5 mt-12" staggerChildren={0.1}>
          {cards.map((c, i) => (
            <StaggerItem key={i}>
              <div className="group relative h-full rounded-2xl border border-ink-200/70 dark:border-ink-800 bg-white dark:bg-ink-900/60 p-7 shadow-card hover:shadow-float dark:hover:shadow-float-dark hover:-translate-y-1 transition-all duration-300 overflow-hidden">
                <div className="absolute -top-12 -right-12 w-40 h-40 rounded-full bg-cyan-500/0 group-hover:bg-cyan-500/10 transition-colors blur-2xl"/>
                <Pill tone={c.tone}>{c.icon} {c.tag}</Pill>
                <div className="mt-6 flex gap-3">
                  <div className="w-7 h-7 rounded-lg bg-rose-500/10 flex items-center justify-center flex-shrink-0"><I.X className="w-3.5 h-3.5 text-rose-500"/></div>
                  <p className="text-[15px] text-ink-700 dark:text-ink-200 line-through decoration-rose-500/40 decoration-2 leading-snug">{c.bad}</p>
                </div>
                <div className="mt-3 flex gap-3">
                  <div className="w-7 h-7 rounded-lg bg-emerald-500/15 flex items-center justify-center flex-shrink-0"><I.Check className="w-3.5 h-3.5 text-emerald-500"/></div>
                  <p className="text-[15px] text-ink-900 dark:text-white font-medium leading-snug text-pretty">{c.good}</p>
                </div>
              </div>
            </StaggerItem>
          ))}
        </Stagger>
      </Container>
    </Section>
  );
}

window.SectionsTop = { Header, Hero, LogoStrip, PainPoints };
