// ===== PATIENT CYCLE — the thesis section =====
// "Ninguém te contou que sua clínica precisa disso."
// 6-stage circular ring showing how campaigns turn one-off appointments into
// a self-feeding patient lifecycle: each appointment auto-triggers the next.
// Auto-rotates every 4s, click any node to focus, central panel shows the
// real WhatsApp/SMS message that fires at each stage.

const { motion: mc_, AnimatePresence: APc_ } = window.framerMotion || {};

function Sec_c({ id, className = '', children }) {
  return <section id={id} className={className}>{children}</section>;
}
function C_c({ className = '', children }) {
  return <div className={`max-w-7xl mx-auto px-6 lg:px-8 ${className}`}>{children}</div>;
}

// ----- The 6 stages of the cycle (mapped from your mind map) -----
const STAGES = [
  {
    id: 'capture',
    n: 1,
    label: 'Captação',
    sub: 'Pré-agendamento',
    title: 'Campanha trouxe o paciente sozinha',
    desc: 'A base manda mensagem em quem fez ultrassom há 6 meses, ginecológico há 12 meses, ou cuja esposa engravidou. O agendamento entra sem você fazer nada.',
    color: '#06B6D4', // cyan
    icon: 'Sparkles',
    timeLabel: 'D−14',
    triggers: ['Checkup ginecológico · 12 meses', 'Bebê nasceu · indica pediatra', 'Fez ultrassom · indica consulta'],
    msg: { from: 'CliniSet · Dra. Helena', body: 'Oi, Marina! Faz 12 meses do seu checkup ginecológico. Quer agendar? Tenho horário quinta às 14h.', cta: 'Agendar' },
  },
  {
    id: 'confirm',
    n: 2,
    label: 'Confirmação',
    sub: 'D−1',
    title: 'Confirmou, remarcou ou cancelou — automático',
    desc: 'No dia anterior, sai a confirmação. Confirmou → manda preparo do exame. Remarcou → pergunta nova data. Cancelou → notifica e libera vaga.',
    color: '#F59E0B', // amber
    icon: 'Phone',
    timeLabel: 'D−1',
    triggers: ['Confirmou → envia preparo do exame', 'Remarcou → pergunta nova data', 'Cancelou → libera vaga + notifica'],
    msg: { from: 'CliniSet · Lembrete', body: 'Marina, confirma sua consulta amanhã 14h com a Dra. Helena? Responde 1 (sim), 2 (remarcar), 3 (cancelar).', cta: 'Confirmar' },
  },
  {
    id: 'arrival',
    n: 3,
    label: 'Chegada',
    sub: 'No dia',
    title: 'Orientação automática 30min antes',
    desc: 'Manhã do atendimento: chegue 5–10min antes, traga RG/CPF, confira o endereço, suba pelo elevador social. Reduz no-show e atraso em 38%.',
    color: '#10B981', // emerald
    icon: 'Calendar',
    timeLabel: 'D · 07:30',
    triggers: ['Endereço + ponto de referência', 'Documentos necessários', 'Janela de tolerância (5–10min)'],
    msg: { from: 'CliniSet · Hoje', body: '☕ Bom dia, Marina! Sua consulta é hoje 14h. Chegue 8min antes. Av. Paulista 1106, 12º andar. Traga RG.', cta: 'Ver no mapa' },
  },
  {
    id: 'thanks',
    n: 4,
    label: 'Agradecimento',
    sub: 'D+1',
    title: 'Pede review no Google sem você lembrar',
    desc: 'Um dia depois do atendimento, agradece e dispara link direto para review no Google. Clínicas CliniSet ganham em média 18 reviews 5★ por mês — sem secretária pedindo.',
    color: '#EC4899', // pink
    icon: 'Stamp',
    timeLabel: 'D+1',
    triggers: ['Agradecimento personalizado', 'Botão "Avaliar no Google"', 'Pesquisa de NPS embutida'],
    msg: { from: 'CliniSet · Obrigada', body: 'Marina, obrigada pela visita ontem! 💙 Se puder, deixa um review pra gente — leva 30s e ajuda muito.', cta: 'Avaliar no Google ★' },
  },
  {
    id: 'nps',
    n: 5,
    label: 'Satisfação',
    sub: 'D+3',
    title: 'NPS automático que retroalimenta o produto',
    desc: 'Pesquisa de satisfação 3 dias depois. Promotores entram numa lista de embaixadores. Detratores caem no funil de recuperação com follow-up humano em 24h.',
    color: '#8B5CF6', // violet
    icon: 'Activity',
    timeLabel: 'D+3',
    triggers: ['Score de 0 a 10', 'Promotor (9–10) → indicação', 'Detrator (0–6) → follow-up em 24h'],
    msg: { from: 'CliniSet · Pesquisa', body: 'De 0 a 10, qual a chance de você indicar a Dra. Helena pra um amigo? Leva 10 segundos.', cta: 'Avaliar' },
  },
  {
    id: 'rebook',
    n: 6,
    label: 'Próximo Ciclo',
    sub: 'Loop',
    title: 'Volta pra captação. Ciclo se fecha.',
    desc: 'O sistema agenda sozinho a próxima campanha de captação para esse paciente — pode ser 6 meses, 1 ano, ou no próximo evento de vida (gravidez, mudança de plano, aniversário).',
    color: '#14B8A6', // teal
    icon: 'ArrowRight',
    timeLabel: '+6 meses',
    triggers: ['Recorrência por procedimento', 'Eventos de vida disparam novo ciclo', 'CliniSet aprende e otimiza'],
    msg: { from: 'CliniSet · Daqui 6 meses', body: 'Marina, faz 6 meses do seu checkup. Tudo bem? Quer manter o ritmo? Tenho horário…', cta: 'Reagendar' },
  },
];

// ===== Patient Cycle ring =====
function PatientCycle() {
  const [active, setActive] = React.useState(0);
  const [paused, setPaused] = React.useState(false);

  // Auto-rotate
  React.useEffect(() => {
    if (paused) return;
    const id = setInterval(() => {
      setActive((a) => (a + 1) % STAGES.length);
    }, 4500);
    return () => clearInterval(id);
  }, [paused]);

  // Geometry — 6 nodes around a circle
  const SIZE = 560;
  const RADIUS = 215;
  const center = SIZE / 2;
  const positions = STAGES.map((_, i) => {
    // Start at top (-90°), go clockwise
    const angle = (-90 + (360 / STAGES.length) * i) * (Math.PI / 180);
    return {
      x: center + Math.cos(angle) * RADIUS,
      y: center + Math.sin(angle) * RADIUS,
      angle,
    };
  });

  const stage = STAGES[active];
  const Icon = (window.UI && window.UI.I && window.UI.I[stage.icon]) || (() => null);
  // Fallback to global I
  const IconC = (typeof I !== 'undefined' && I[stage.icon]) || IconFallback;

  return (
    <Sec_c id="ciclo" className="relative py-24 lg:py-36 overflow-hidden">
      {/* Forced dark backdrop — even in light mode this section is dark for drama */}
      <div className="absolute inset-0 -z-10" style={{
        background: 'radial-gradient(ellipse at 50% 0%, #0B2540 0%, #050B17 55%, #020611 100%)',
      }}/>

      {/* Decorative grid + radial vignette */}
      <div className="absolute inset-0 -z-10 opacity-[0.18]" style={{
        backgroundImage: 'radial-gradient(circle at 1px 1px, rgba(125,211,252,0.45) 1px, transparent 0)',
        backgroundSize: '32px 32px',
        maskImage: 'radial-gradient(ellipse at center, black 30%, transparent 75%)',
        WebkitMaskImage: 'radial-gradient(ellipse at center, black 30%, transparent 75%)',
      }}/>

      {/* Top reveal — kicker line with eyebrow + tag */}
      <C_c>
        <div className="grid lg:grid-cols-[1fr_auto] gap-6 items-end mb-10 lg:mb-14">
          <div>
            <div className="flex items-center gap-3 mb-5">
              <span className="w-2 h-2 rounded-full bg-cyan-400 animate-pulse-soft"/>
              <span className="text-[11px] font-mono uppercase tracking-[0.28em] text-cyan-300/90">Tese · O Ciclo do Paciente</span>
            </div>
            <h2 className="font-display font-bold text-white text-[clamp(2.2rem,5vw,4.4rem)] leading-[1.02] tracking-[-0.04em] text-pretty max-w-[18ch]">
              Ninguém te contou<br/>
              que sua clínica precisa <span className="italic" style={{
                background: 'linear-gradient(120deg, #67E8F9 0%, #38BDF8 50%, #818CF8 100%)',
                WebkitBackgroundClip: 'text', backgroundClip: 'text', color: 'transparent',
              }}>disso</span>.
            </h2>
            <p className="mt-6 text-[16px] lg:text-[17px] text-cyan-100/70 max-w-[60ch] leading-relaxed">
              Seu paciente não é um evento. É um <span className="text-white font-semibold">ciclo</span> que se realimenta a cada 6 meses, 1 ano, ou no próximo evento de vida — se você tiver as campanhas certas rodando no automático. CliniSet roda.
            </p>
          </div>
          <div className="flex items-center gap-2 lg:flex-col lg:items-end">
            <button
              onClick={() => setPaused((p) => !p)}
              className="px-3 h-9 rounded-lg bg-white/5 border border-white/10 hover:bg-white/10 text-cyan-100 text-[12px] font-medium inline-flex items-center gap-2 transition"
            >
              {paused ? <>▶ Retomar</> : <>⏸ Pausar ciclo</>}
            </button>
            <span className="text-[10.5px] font-mono uppercase tracking-[0.2em] text-cyan-200/40">{paused ? 'Pausado' : 'Auto · 4.5s/etapa'}</span>
          </div>
        </div>
      </C_c>

      {/* The ring */}
      <C_c>
        <div className="grid lg:grid-cols-[auto_1fr] gap-12 lg:gap-16 items-center">
          {/* SVG ring — left/center on desktop */}
          <div className="relative mx-auto" style={{ width: SIZE, maxWidth: '100%' }}>
            <svg viewBox={`0 0 ${SIZE} ${SIZE}`} className="w-full h-auto" style={{ filter: 'drop-shadow(0 0 60px rgba(14,165,233,0.15))' }}>
              <defs>
                <linearGradient id="ring-grad" x1="0" y1="0" x2="1" y2="1">
                  <stop offset="0%" stopColor="#06B6D4"/>
                  <stop offset="20%" stopColor="#F59E0B"/>
                  <stop offset="40%" stopColor="#10B981"/>
                  <stop offset="60%" stopColor="#EC4899"/>
                  <stop offset="80%" stopColor="#8B5CF6"/>
                  <stop offset="100%" stopColor="#14B8A6"/>
                </linearGradient>
                <linearGradient id="ring-grad-soft" x1="0" y1="0" x2="1" y2="1">
                  <stop offset="0%" stopColor="rgba(6,182,212,0.5)"/>
                  <stop offset="100%" stopColor="rgba(20,184,166,0.5)"/>
                </linearGradient>
                <radialGradient id="ring-glow">
                  <stop offset="0%" stopColor="rgba(14,165,233,0.4)"/>
                  <stop offset="100%" stopColor="rgba(14,165,233,0)"/>
                </radialGradient>
                <filter id="ring-glow-filter">
                  <feGaussianBlur stdDeviation="3"/>
                </filter>
              </defs>

              {/* Outer faint ring */}
              <circle cx={center} cy={center} r={RADIUS + 38} fill="none" stroke="rgba(125,211,252,0.08)" strokeWidth="1" strokeDasharray="2 6"/>

              {/* Main ring with gradient */}
              <circle cx={center} cy={center} r={RADIUS} fill="none" stroke="url(#ring-grad)" strokeWidth="1.5" opacity="0.6"/>

              {/* Animated rotating arc — "energy flowing" */}
              <circle
                cx={center} cy={center} r={RADIUS}
                fill="none" stroke="url(#ring-grad)" strokeWidth="3" strokeLinecap="round"
                strokeDasharray={`${RADIUS * 2 * Math.PI * 0.18} ${RADIUS * 2 * Math.PI * 0.82}`}
                style={{
                  transformOrigin: `${center}px ${center}px`,
                  animation: paused ? 'none' : 'cycle-spin 14s linear infinite',
                  filter: 'drop-shadow(0 0 8px currentColor)',
                  color: stage.color,
                }}
              />

              {/* Inner ring */}
              <circle cx={center} cy={center} r={RADIUS - 60} fill="none" stroke="rgba(125,211,252,0.12)" strokeWidth="1" strokeDasharray="1 8"/>

              {/* Center hub */}
              <circle cx={center} cy={center} r="80" fill="rgba(8,15,30,0.85)" stroke="rgba(125,211,252,0.25)" strokeWidth="1"/>
              <circle cx={center} cy={center} r="80" fill="url(#ring-glow)" opacity="0.6"/>

              {/* Center: "PACIENTE" + active stage glyph */}
              <text x={center} y={center - 6} textAnchor="middle" fontSize="11" fontWeight="700" fontFamily="ui-monospace, monospace" letterSpacing="3" fill="rgba(186,230,253,0.7)">PACIENTE</text>
              <text x={center} y={center + 14} textAnchor="middle" fontSize="14" fontWeight="700" fill={stage.color} style={{ transition: 'fill 0.5s' }}>● {String(active + 1).padStart(2, '0')}/06</text>

              {/* Connecting lines from active node to center — pulse */}
              <line
                x1={center} y1={center}
                x2={positions[active].x} y2={positions[active].y}
                stroke={stage.color} strokeWidth="1.5" opacity="0.5"
                strokeDasharray="4 4"
                style={{ transition: 'all 0.6s cubic-bezier(0.65, 0, 0.35, 1)' }}
              />

              {/* Nodes */}
              {STAGES.map((s, i) => {
                const isActive = i === active;
                const p = positions[i];
                const r = isActive ? 38 : 28;
                return (
                  <g
                    key={s.id}
                    onClick={() => { setActive(i); setPaused(true); }}
                    style={{ cursor: 'pointer' }}
                  >
                    {/* Outer halo when active */}
                    {isActive && (
                      <circle cx={p.x} cy={p.y} r="58" fill={s.color} opacity="0.18">
                        <animate attributeName="r" values="48;62;48" dur="2.4s" repeatCount="indefinite"/>
                        <animate attributeName="opacity" values="0.25;0.05;0.25" dur="2.4s" repeatCount="indefinite"/>
                      </circle>
                    )}
                    {/* Node bg */}
                    <circle
                      cx={p.x} cy={p.y} r={r}
                      fill={isActive ? s.color : 'rgba(15,30,55,0.9)'}
                      stroke={s.color}
                      strokeWidth={isActive ? 2 : 1.5}
                      style={{ transition: 'all 0.5s cubic-bezier(0.65, 0, 0.35, 1)' }}
                    />
                    {/* Number */}
                    <text
                      x={p.x} y={p.y + 1.5}
                      textAnchor="middle" dominantBaseline="middle"
                      fontFamily="ui-monospace, monospace"
                      fontSize={isActive ? 17 : 14}
                      fontWeight="700"
                      fill={isActive ? '#0B2540' : s.color}
                      style={{ transition: 'all 0.5s', pointerEvents: 'none' }}
                    >
                      {String(s.n).padStart(2, '0')}
                    </text>
                  </g>
                );
              })}

              {/* Labels around the nodes */}
              {STAGES.map((s, i) => {
                const isActive = i === active;
                const p = positions[i];
                // Push label outward
                const dx = p.x - center;
                const dy = p.y - center;
                const len = Math.sqrt(dx * dx + dy * dy);
                const ext = 56;
                const lx = center + (dx / len) * (RADIUS + ext);
                const ly = center + (dy / len) * (RADIUS + ext);
                // Anchor based on side
                let anchor = 'middle';
                if (lx > center + 30) anchor = 'start';
                else if (lx < center - 30) anchor = 'end';
                return (
                  <g key={s.id + '-label'} style={{ pointerEvents: 'none' }}>
                    <text
                      x={lx} y={ly - 4}
                      textAnchor={anchor}
                      fontFamily="ui-monospace, monospace"
                      fontSize="9.5"
                      fontWeight="600"
                      letterSpacing="2.4"
                      fill="rgba(186,230,253,0.45)"
                    >
                      {s.sub.toUpperCase()}
                    </text>
                    <text
                      x={lx} y={ly + 11}
                      textAnchor={anchor}
                      fontSize="14"
                      fontWeight="700"
                      fill={isActive ? '#fff' : 'rgba(226,232,240,0.85)'}
                      style={{ transition: 'fill 0.5s', letterSpacing: '-0.01em' }}
                    >
                      {s.label}
                    </text>
                  </g>
                );
              })}

              {/* Orbiting dots */}
              {!paused && [0, 1, 2].map((d) => (
                <circle key={d} r="2.5" fill={stage.color} opacity="0.7">
                  <animateMotion
                    dur={`${10 + d * 1.5}s`}
                    repeatCount="indefinite"
                    path={`M ${center} ${center - RADIUS} A ${RADIUS} ${RADIUS} 0 1 1 ${center - 0.001} ${center - RADIUS}`}
                    begin={`-${d * 2.5}s`}
                  />
                </circle>
              ))}
            </svg>
          </div>

          {/* Right column — active stage detail */}
          <div className="lg:pl-4">
            {APc_ ? (
              <APc_ mode="wait">
                <mc_.div
                  key={stage.id}
                  initial={{ opacity: 0, y: 16 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -10 }}
                  transition={{ duration: 0.45, ease: [0.65, 0, 0.35, 1] }}
                >
                  <StageDetail stage={stage} />
                </mc_.div>
              </APc_>
            ) : (
              <StageDetail stage={stage} />
            )}
          </div>
        </div>

        {/* Bottom: progress dots / steppers */}
        <div className="mt-12 flex items-center justify-center gap-2 flex-wrap">
          {STAGES.map((s, i) => {
            const isActive = i === active;
            return (
              <button
                key={s.id}
                onClick={() => { setActive(i); setPaused(true); }}
                className="group relative flex items-center gap-2.5 px-3 h-9 rounded-full transition-all"
                style={{
                  background: isActive ? `${s.color}1f` : 'rgba(255,255,255,0.03)',
                  border: `1px solid ${isActive ? s.color + '60' : 'rgba(255,255,255,0.08)'}`,
                }}
              >
                <span className="w-1.5 h-1.5 rounded-full" style={{ background: s.color, boxShadow: isActive ? `0 0 8px ${s.color}` : 'none' }}/>
                <span className="text-[11px] font-mono uppercase tracking-wider" style={{ color: isActive ? s.color : 'rgba(186,230,253,0.5)' }}>
                  {String(s.n).padStart(2, '0')} {s.label}
                </span>
              </button>
            );
          })}
        </div>

        {/* Closing punchline */}
        <div className="mt-16 lg:mt-20 max-w-3xl mx-auto text-center">
          <div className="text-[11px] font-mono uppercase tracking-[0.3em] text-cyan-300/70 mb-3">O Resultado</div>
          <p className="font-display text-white text-[clamp(1.4rem,2.6vw,2.2rem)] tracking-tight leading-[1.15] text-pretty">
            Sua clínica para de depender de captação nova. <span className="text-cyan-300">Cada paciente que entra volta sozinho</span> — e traz outros 2.
          </p>
          <div className="mt-7 flex items-center justify-center gap-3 flex-wrap">
            {[
              { k: '+38%', v: 'redução de no-show' },
              { k: '×2.4', v: 'pacientes recorrentes' },
              { k: '18/mês', v: 'reviews 5★ no Google' },
            ].map((m) => (
              <div key={m.k} className="px-4 py-2 rounded-lg border border-cyan-400/15 bg-white/[0.02] text-left">
                <div className="font-display font-bold text-cyan-300 text-[18px] tabular leading-none">{m.k}</div>
                <div className="text-[11px] text-cyan-100/55 mt-1">{m.v}</div>
              </div>
            ))}
          </div>
        </div>
      </C_c>

      {/* CSS keyframes for the rotating arc */}
      <style>{`
        @keyframes cycle-spin {
          0%   { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
      `}</style>
    </Sec_c>
  );
}

function IconFallback() { return null; }

// ===== Stage detail card =====
function StageDetail({ stage }) {
  const IconC = (typeof I !== 'undefined' && I[stage.icon]) || IconFallback;

  return (
    <div className="relative">
      {/* Step indicator */}
      <div className="flex items-center gap-3 mb-4">
        <div
          className="w-11 h-11 rounded-xl flex items-center justify-center"
          style={{
            background: `${stage.color}22`,
            border: `1px solid ${stage.color}55`,
            color: stage.color,
            boxShadow: `0 0 20px ${stage.color}33`,
          }}
        >
          <IconC className="w-5 h-5"/>
        </div>
        <div>
          <div className="text-[10.5px] font-mono uppercase tracking-[0.25em]" style={{ color: stage.color }}>
            Etapa {String(stage.n).padStart(2, '0')} · {stage.timeLabel}
          </div>
          <div className="text-white font-display font-semibold text-[18px] tracking-tight leading-tight mt-0.5">{stage.label}</div>
        </div>
      </div>

      {/* Headline */}
      <h3 className="font-display font-bold text-white text-[clamp(1.4rem,2.4vw,2rem)] leading-[1.1] tracking-[-0.025em] text-pretty mt-2 mb-3">
        {stage.title}
      </h3>
      <p className="text-[14.5px] text-cyan-100/65 leading-relaxed mb-6 max-w-[55ch]">{stage.desc}</p>

      {/* Triggers list */}
      <div className="mb-6">
        <div className="text-[10.5px] font-mono uppercase tracking-[0.2em] text-cyan-200/45 mb-2.5">O que dispara</div>
        <div className="space-y-1.5">
          {stage.triggers.map((t, i) => (
            <div key={i} className="flex items-start gap-2.5 text-[13.5px] text-cyan-50/85">
              <span className="w-1 h-1 rounded-full mt-2 flex-shrink-0" style={{ background: stage.color }}/>
              <span>{t}</span>
            </div>
          ))}
        </div>
      </div>

      {/* WhatsApp-style message preview */}
      <div className="rounded-2xl border p-4 backdrop-blur-md max-w-md" style={{
        borderColor: `${stage.color}33`,
        background: 'linear-gradient(180deg, rgba(255,255,255,0.04), rgba(255,255,255,0.01))',
      }}>
        <div className="flex items-center gap-2 mb-2.5 pb-2.5 border-b border-white/[0.06]">
          <div className="w-8 h-8 rounded-full flex items-center justify-center" style={{ background: stage.color, color: '#fff' }}>
            <svg viewBox="0 0 24 24" className="w-4 h-4" fill="currentColor"><path d="M20.52 3.48A12 12 0 0 0 3.48 20.52L2 22l1.48-1.48A12 12 0 0 0 20.52 3.48zM12 20a8 8 0 1 1 8-8 8 8 0 0 1-8 8z" opacity="0.3"/><path d="M16.5 13.6c-.3-.1-1.7-.8-1.9-.9-.3-.1-.4-.1-.6.1-.2.3-.7.9-.9 1-.2.2-.3.2-.6.1-1.7-.9-2.9-1.6-4-3.5-.3-.5.3-.5.8-1.5.1-.2 0-.3 0-.5l-.9-2c-.2-.5-.4-.4-.6-.4h-.5c-.2 0-.5.1-.7.3-1 1-1.5 2.4-1.5 3.7 0 .8.2 1.6.5 2.3 1.5 3.4 4 5.3 7.6 6.3.6.2 1.1.2 1.6.1.6-.1 1.7-.7 2-1.4.3-.7.3-1.3.2-1.4-.1-.1-.3-.2-.5-.2z"/></svg>
          </div>
          <div className="flex-1 min-w-0">
            <div className="text-[12.5px] font-semibold text-white truncate">{stage.msg.from}</div>
            <div className="text-[10.5px] text-cyan-200/40 font-mono uppercase tracking-wider">Enviada · agora</div>
          </div>
        </div>
        <div className="text-[13.5px] text-white/90 leading-relaxed mb-3">{stage.msg.body}</div>
        <button
          className="w-full h-9 rounded-lg text-[12.5px] font-semibold transition"
          style={{ background: stage.color, color: '#0B2540' }}
        >
          {stage.msg.cta}
        </button>
      </div>
    </div>
  );
}

// Export
window.SectionsCycle = { PatientCycle };
