// V23 — Etapas. Terminal mostra processo do projeto como wizard de etapas.

// Mail / envelope icon.
const MailIcon = ({ size = 18, color = 'currentColor' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <rect x="3" y="5" width="18" height="14" rx="2" />
    <path d="m3 7 9 6 9-6" />
  </svg>
);

// WhatsApp icon (official-ish glyph).
const WhatsAppIcon = ({ size = 16, color = 'currentColor' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill={color}>
    <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0 0 12.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 0 0 5.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 0 0-3.48-8.413Z" />
  </svg>
);

// Icon-only email + WhatsApp buttons, side by side.
const CTAButtons = ({ showWhatsApp }) => (
  <div style={{ display: 'inline-flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 16 }}>
    <a
      href="mailto:contato@withdev.com.br"
      aria-label="Enviar email"
      style={{
        width: 64, height: 64, borderRadius: '50%',
        background: '#7c5cff', color: '#0a0a0a',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: '0 0 40px rgba(124,92,255,0.45)',
        textDecoration: 'none',
      }}
    >
      <MailIcon size={26} />
    </a>
    {showWhatsApp && (
      <a
        href="https://wa.me/"
        target="_blank"
        rel="noopener noreferrer"
        aria-label="Abrir WhatsApp"
        style={{
          width: 64, height: 64, borderRadius: '50%',
          background: '#25D366', color: '#0a0a0a',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: '0 0 40px rgba(37,211,102,0.45)',
          textDecoration: 'none',
        }}
      >
        <WhatsAppIcon size={26} />
      </a>
    )}
  </div>
);

// Internal CTA block — types the headline on view, then shows bouncing arrow + button.
const CTABlock = ({ showWhatsApp }) => {
  const ref = React.useRef(null);
  const [started, setStarted] = React.useState(false);
  const [typed, setTyped] = React.useState('');
  const TEXT = 'Pronto pra dar o\nprimeiro passo?';

  React.useEffect(() => {
    if (!ref.current) return;
    const obs = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) { setStarted(true); obs.disconnect(); }
    }, { threshold: 0.4 });
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);

  React.useEffect(() => {
    if (!started || typed.length >= TEXT.length) return;
    const t = setTimeout(() => setTyped(TEXT.slice(0, typed.length + 1)), 60);
    return () => clearTimeout(t);
  }, [started, typed]);

  const done = typed.length >= TEXT.length;
  const parts = typed.split('\n');

  // Show the icons only after "vamos conversar" has had time to appear.
  const [showButtons, setShowButtons] = React.useState(false);
  React.useEffect(() => {
    if (!done) return;
    const t = setTimeout(() => setShowButtons(true), 500);
    return () => clearTimeout(t);
  }, [done]);

  return (
    <div ref={ref}>
      <h2 style={{ fontFamily: "'Geist', sans-serif", fontSize: 72, lineHeight: 0.95, fontWeight: 500, letterSpacing: '-0.04em', margin: '0 0 28px', minHeight: '2.1em' }}>
        {parts.map((p, i) => (
          <React.Fragment key={i}>
            {i > 0 && <br />}
            {p}
          </React.Fragment>
        ))}
        <span style={{
          display: 'inline-block',
          width: '0.07em', height: '0.85em',
          background: '#6E45F7',
          marginLeft: '0.06em',
          verticalAlign: '-0.05em',
          animation: done ? 'wd-blink 1s steps(2, start) infinite' : 'none',
          opacity: started ? 1 : 0,
        }} />
      </h2>

      {/* Bouncing scroll-style indicator */}
      <div style={{
        fontFamily: "'JetBrains Mono', monospace",
        fontSize: 12,
        color: 'rgba(255,255,255,0.45)',
        letterSpacing: '0.2em',
        textTransform: 'uppercase',
        opacity: done ? 1 : 0,
        transform: done ? 'translateY(0)' : 'translateY(10px)',
        transition: 'opacity 1.2s ease, transform 1.2s ease',
        margin: '0 0 28px',
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
      }}>
        <span>vamos conversar</span>
        <span style={{ animation: 'wd-bounce 1.6s ease-in-out infinite', fontSize: 18 }}>↓</span>
      </div>

      <div style={{
        opacity: showButtons ? 1 : 0,
        transform: showButtons ? 'translateY(0)' : 'translateY(8px)',
        transition: 'opacity 0.8s ease, transform 0.8s ease',
      }}>
        <CTAButtons showWhatsApp={showWhatsApp} />
      </div>

      <style>{`
        @keyframes wd-blink { to { visibility: hidden; } }
        @keyframes wd-bounce {
          0%, 100% { transform: translateY(0); }
          50% { transform: translateY(6px); }
        }
      `}</style>
    </div>
  );
};
window.CTABlock = CTABlock;

const V23Etapas = ({
  eyebrow = '◇ Software house brasileira',
  headline,
  sub = 'Sites, apps, sistemas, automações e IA pra empresas que precisam de algo no ar, não no PowerPoint.',
  logo,
  footerLogo,
  navLinks,
  navCta,
  showCases = true,
  showServices = true,
  showSecondaryCTA = true,
  showWhatsApp = false,
  showGrid = true,
  typingCTA = false,
  autoSnapToCTA = false,
  fullScreenCTA = false,
  showHeroScrollHint = false,
  width = 1440,
  minHeight = 2400,
} = {}) => {
  const heroRef = React.useRef(null);
  const ctaRef = React.useRef(null);
  const [showHint, setShowHint] = React.useState(false);

  // Show "role para continuar" hint 1s after hero enters view.
  React.useEffect(() => {
    if (!showHeroScrollHint) return;
    const hero = heroRef.current;
    if (!hero) return;
    let timer = null;
    const obs = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting && !timer) {
        timer = setTimeout(() => setShowHint(true), 1000);
      }
    }, { threshold: 0.5 });
    obs.observe(hero);
    return () => { obs.disconnect(); if (timer) clearTimeout(timer); };
  }, [showHeroScrollHint]);

  const scrollToCTA = (e) => {
    if (e) e.preventDefault();
    ctaRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  // Auto-snap to CTA: when the hero has been in view for 1s,
  // any further scroll of 20px+ smooth-scrolls to the contact section.
  React.useEffect(() => {
    if (!autoSnapToCTA) return;
    const hero = heroRef.current;
    if (!hero) return;

    let timer = null;
    let armed = false;
    let triggered = false;
    let baseline = 0;

    const onScroll = () => {
      if (!armed || triggered) return;
      if (window.scrollY - baseline >= 20) {
        triggered = true;
        ctaRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    };

    const obs = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting && !timer && !triggered) {
        timer = setTimeout(() => {
          armed = true;
          baseline = window.scrollY;
          window.addEventListener('scroll', onScroll, { passive: true });
        }, 1000);
      }
    }, { threshold: 0.5 });
    obs.observe(hero);

    return () => {
      obs.disconnect();
      if (timer) clearTimeout(timer);
      window.removeEventListener('scroll', onScroll);
    };
  }, [autoSnapToCTA]);

  const defaultHeadline = (
    <>
      Sem promessa<br />
      de revolução.<br />
      <span style={{ color: '#7c5cff' }}>Só software que funciona.</span>
    </>
  );
  const steps = [
    { n: 1, t: 'Conversa inicial', d: 'Conta seu desafio sem precisar de termo técnico', status: 'done' },
    { n: 2, t: 'Proposta', d: 'Escopo, prazo e investimento em até 24h', status: 'done' },
    { n: 3, t: 'Design', d: 'Você aprova antes da gente começar a construir', status: 'active' },
    { n: 4, t: 'Construção', d: 'Acompanhamento semanal, sem caixa preta', status: 'todo' },
    { n: 5, t: 'Entrega', d: 'No ar, com suporte e ajustes inclusos', status: 'todo' },
  ];

  return (
    <GridBg grid={showGrid} glow glowPosition="20% 30%" glowSize={1000} style={{ width, minHeight, color: '#e8e8e3', fontFamily: "'Inter', system-ui, sans-serif" }}>
      <MinimalNav logo={logo} links={navLinks} cta={navCta} />

      {/* Hero — split */}
      <section ref={heroRef} className="wd-hero" style={{ padding: '80px 56px 40px', display: 'flex', flexDirection: 'column', gap: 40 }}>
        <div className="wd-hero-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 600px', gap: 56, alignItems: 'center' }}>
        <div>
          <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: '#7c5cff', letterSpacing: '0.15em', textTransform: 'uppercase', marginBottom: 28 }}>
            {eyebrow}
          </div>
          <h1 style={{
            fontFamily: "'Geist', sans-serif",
            fontSize: 78, lineHeight: 0.98, fontWeight: 500,
            letterSpacing: '-0.04em', margin: '0 0 28px',
          }}>
            {headline || defaultHeadline}
          </h1>
          <p style={{ fontSize: 18, color: 'rgba(255,255,255,0.62)', maxWidth: 520, margin: '0 0 36px', fontWeight: 300, lineHeight: 1.5 }}>
            {sub}
          </p>
          <div style={{ display: 'flex', gap: 10 }}>
            <a onClick={scrollToCTA} style={{ cursor: 'pointer', padding: '14px 22px', borderRadius: 999, background: '#7c5cff', color: '#0a0a0a', fontSize: 15, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 8 }}>
              Começar projeto <ArrowIcon size={14} />
            </a>
            {showSecondaryCTA && (
              <a style={{ padding: '14px 22px', borderRadius: 999, background: 'transparent', border: '1px solid rgba(255,255,255,0.18)', color: '#fff', fontSize: 15, fontWeight: 500 }}>
                Falar com o time
              </a>
            )}
          </div>
        </div>

        {/* Terminal — etapas */}
        <TerminalChrome title="projeto · status">
          <div style={{ padding: 26 }}>
            {/* progress bar */}
            <div style={{ marginBottom: 22 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10, fontSize: 12 }}>
                <span style={{ color: 'rgba(255,255,255,0.55)' }}>Progresso</span>
                <span style={{ color: '#7c5cff', fontWeight: 600 }}>2 de 5 etapas</span>
              </div>
              <div style={{ display: 'flex', gap: 4 }}>
                {steps.map((s, i) => (
                  <span key={i} style={{
                    flex: 1, height: 4, borderRadius: 2,
                    background: s.status === 'done' ? '#a3e635' : s.status === 'active' ? '#7c5cff' : 'rgba(255,255,255,0.1)',
                  }} />
                ))}
              </div>
            </div>

            {/* steps */}
            <div>
              {steps.map((s, i) => (
                <div key={i} style={{
                  display: 'flex', gap: 14, padding: '14px 0',
                  borderBottom: i < steps.length - 1 ? '1px solid rgba(255,255,255,0.06)' : 'none',
                  alignItems: 'flex-start',
                  opacity: s.status === 'todo' ? 0.6 : 1,
                }}>
                  <span style={{
                    width: 30, height: 30, borderRadius: '50%', flexShrink: 0,
                    background: s.status === 'done' ? '#a3e635' : s.status === 'active' ? '#7c5cff' : 'rgba(255,255,255,0.08)',
                    color: s.status === 'todo' ? 'rgba(255,255,255,0.5)' : '#0a0a0a',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    fontFamily: "'JetBrains Mono', monospace", fontSize: 13, fontWeight: 700,
                  }}>
                    {s.status === 'done' ? '✓' : s.n}
                  </span>
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span style={{ fontFamily: "'Inter', sans-serif", fontSize: 15, fontWeight: 500, color: '#fff' }}>{s.t}</span>
                      {s.status === 'active' && (
                        <span style={{
                          padding: '2px 8px', borderRadius: 999,
                          background: 'rgba(124,92,255,0.18)', border: '1px solid rgba(124,92,255,0.3)',
                          color: '#c4b5ff', fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: '0.08em',
                        }}>EM ANDAMENTO</span>
                      )}
                    </div>
                    <div style={{ fontFamily: "'Inter', sans-serif", fontSize: 13, color: 'rgba(255,255,255,0.55)', marginTop: 2 }}>{s.d}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </TerminalChrome>
        </div>

        {/* Scroll hint — appears 1s after hero enters view */}
        {showHeroScrollHint && (
          <div style={{
            opacity: showHint ? 1 : 0,
            transform: showHint ? 'translateY(0)' : 'translateY(10px)',
            transition: 'opacity 1.2s ease, transform 1.2s ease',
            fontFamily: "'JetBrains Mono', monospace",
            fontSize: 12,
            color: 'rgba(255,255,255,0.45)',
            letterSpacing: '0.2em',
            textTransform: 'uppercase',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
            marginTop: 12,
          }}>
            <span>role para continuar</span>
            <span style={{ animation: 'wd-bounce 1.6s ease-in-out infinite', fontSize: 18 }}>↓</span>
          </div>
        )}
      </section>

      {/* Services */}
      {showServices && (
        <section style={{ padding: '60px 56px', borderTop: '1px solid rgba(255,255,255,0.06)', borderBottom: '1px solid rgba(255,255,255,0.06)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            {SERVICES_SHORT.map((s, i) => (
              <span key={i} style={{ fontFamily: "'Geist', sans-serif", fontSize: 20, fontWeight: 400, color: 'rgba(255,255,255,0.85)', letterSpacing: '-0.02em' }}>
                {s}
              </span>
            ))}
          </div>
        </section>
      )}

      {/* Cases */}
      {showCases && (
        <section style={{ padding: '100px 56px' }}>
          <h2 style={{ fontFamily: "'Geist', sans-serif", fontSize: 48, fontWeight: 500, letterSpacing: '-0.035em', margin: '0 0 32px' }}>Projetos no ar.</h2>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
            {CASES.map((c, i) => (
              <div key={i}>
                <Placeholder label={c.client.toLowerCase()} h={260} radius={12} />
                <div style={{ marginTop: 14, fontFamily: "'Geist', sans-serif", fontSize: 18, fontWeight: 500, letterSpacing: '-0.015em' }}>{c.client}</div>
                <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.55)', marginTop: 2 }}>{c.work}</div>
              </div>
            ))}
          </div>
        </section>
      )}

      {/* CTA — full-screen wraps contact + footer so they fit in one viewport */}
      {fullScreenCTA ? (
        <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
          <section
            ref={ctaRef}
            className="wd-cta"
            style={{
              flex: 1,
              padding: '40px 56px',
              display: 'flex', flexDirection: 'column',
              alignItems: 'center', justifyContent: 'center',
              textAlign: 'center',
            }}
          >
            {typingCTA ? (
              <CTABlock showWhatsApp={showWhatsApp} />
            ) : (
              <>
                <h2 style={{ fontFamily: "'Geist', sans-serif", fontSize: 72, lineHeight: 0.95, fontWeight: 500, letterSpacing: '-0.04em', margin: '0 0 32px' }}>
                  Pronto pra dar o<br />primeiro passo?
                </h2>
                <CTAButtons showWhatsApp={showWhatsApp} />
              </>
            )}
          </section>
          <MinimalFooter logo={footerLogo || logo} />
        </div>
      ) : (
        <>
          <section ref={ctaRef} className="wd-cta" style={{ padding: '100px 56px 120px', textAlign: 'center' }}>
            {typingCTA ? (
              <CTABlock showWhatsApp={showWhatsApp} />
            ) : (
              <>
                <h2 style={{ fontFamily: "'Geist', sans-serif", fontSize: 72, lineHeight: 0.95, fontWeight: 500, letterSpacing: '-0.04em', margin: '0 0 32px' }}>
                  Pronto pra dar o<br />primeiro passo?
                </h2>
                <CTAButtons showWhatsApp={showWhatsApp} />
              </>
            )}
          </section>
          <MinimalFooter logo={footerLogo || logo} />
        </>
      )}
    </GridBg>
  );
};

window.V23Etapas = V23Etapas;
