// Typing intro + reusable wordmark logo for WithDev site.

// Wordmark logo — small, for nav. Matches the SVG: "withdev" with purple dot.
const WordmarkLogo = ({ height = 26 }) => (
  <span style={{
    fontFamily: "'Geist', sans-serif",
    fontWeight: 600,
    fontSize: height,
    color: '#f4f4f5',
    letterSpacing: '-0.04em',
    lineHeight: 1,
    display: 'inline-flex',
    alignItems: 'center',
    userSelect: 'none',
  }}>
    withdev<span style={{ color: '#6E45F7' }}>.</span>
  </span>
);

// Smooth scroll with controlled duration.
const introSmoothScrollTo = (targetY, duration = 1400) => {
  const startY = window.scrollY;
  const distance = targetY - startY;
  if (Math.abs(distance) < 4) return;
  const startTime = performance.now();
  const easeInOutCubic = (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);
  const step = (now) => {
    const elapsed = now - startTime;
    const t = Math.min(1, elapsed / duration);
    window.scrollTo(0, startY + distance * easeInOutCubic(t));
    if (t < 1) requestAnimationFrame(step);
  };
  requestAnimationFrame(step);
};

// Full-screen intro that types "withdev." with a blinking purple cursor.
// After typing completes, the cursor blinks and a "↓ role" hint appears.
// Auto-scrolls to the next section as soon as the user scrolls even a little.
const TypingIntro = () => {
  const FULL = 'withdev.';
  const [typed, setTyped] = React.useState('');
  const [done, setDone] = React.useState(false);
  const [hintDismissed, setHintDismissed] = React.useState(false);

  React.useEffect(() => {
    if (typed.length < FULL.length) {
      const t = setTimeout(() => {
        setTyped(FULL.slice(0, typed.length + 1));
      }, 200);
      return () => clearTimeout(t);
    } else {
      const t = setTimeout(() => setDone(true), 600);
      return () => clearTimeout(t);
    }
  }, [typed]);

  // Auto-snap: once typing is done, any small scroll smoothly takes the
  // user to the V23 section below.
  React.useEffect(() => {
    if (!done) return;
    let triggered = false;
    const handler = () => {
      if (window.scrollY > window.innerHeight * 0.6) setHintDismissed(true);
      if (triggered) return;
      const sy = window.scrollY;
      if (sy > 20 && sy < window.innerHeight * 0.7) {
        triggered = true;
        introSmoothScrollTo(window.innerHeight, 1400);
      }
    };
    window.addEventListener('scroll', handler, { passive: true });
    return () => window.removeEventListener('scroll', handler);
  }, [done]);

  const renderTyped = () => {
    const out = [];
    for (let i = 0; i < typed.length; i++) {
      const ch = typed[i];
      out.push(
        <span key={i} style={{ color: ch === '.' ? '#6E45F7' : '#f4f4f5' }}>
          {ch}
        </span>
      );
    }
    return out;
  };

  return (
    <section style={{
      width: '100%',
      minHeight: '100vh',
      background: '#050505',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      position: 'relative',
      overflow: 'hidden',
    }}>
      {/* Wordmark being typed */}
      <div style={{
        display: 'inline-flex',
        alignItems: 'center',
        fontFamily: "'Geist', sans-serif",
        fontWeight: 600,
        fontSize: 'clamp(72px, 12vw, 200px)',
        letterSpacing: '-0.04em',
        lineHeight: 1,
        position: 'relative',
        zIndex: 1,
      }}>
        {renderTyped()}
        {/* Cursor — solid while typing, blinks when done */}
        <span style={{
          display: 'inline-block',
          width: '0.5em',
          height: '1.05em',
          background: '#6E45F7',
          borderRadius: 3,
          marginLeft: '0.05em',
          animation: done ? 'wd-blink 1s steps(2, start) infinite' : 'none',
        }} />
      </div>

      {/* Scroll hint */}
      <div style={{
        position: 'absolute', bottom: 48, left: 0, right: 0,
        textAlign: 'center',
        fontFamily: "'JetBrains Mono', monospace",
        fontSize: 12,
        color: 'rgba(255,255,255,0.45)',
        letterSpacing: '0.2em',
        textTransform: 'uppercase',
        opacity: done && !hintDismissed ? 1 : 0,
        transform: done && !hintDismissed ? 'translateY(0)' : 'translateY(10px)',
        transition: 'opacity 1.4s ease, transform 1.4s ease',
        zIndex: 1,
        pointerEvents: hintDismissed ? 'none' : 'auto',
      }}>
        <div style={{
          display: 'inline-flex', flexDirection: 'column', alignItems: 'center', gap: 10,
        }}>
          <span>role para continuar</span>
          <span style={{ animation: 'wd-bounce 1.6s ease-in-out infinite' }}>↓</span>
        </div>
      </div>

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

// The "<WithDev/>" tag-style logo. Used in the V23 nav and footer.
const TagLogo = ({ height = 24 }) => (
  <span style={{
    fontFamily: "'Geist', sans-serif",
    fontWeight: 600,
    fontSize: height,
    color: '#f4f4f5',
    letterSpacing: '-0.02em',
    lineHeight: 1,
    display: 'inline-flex',
    alignItems: 'center',
    userSelect: 'none',
  }}>
    <span style={{ color: '#6E45F7', fontFamily: "'JetBrains Mono', monospace", fontWeight: 500 }}>{'<'}</span>
    <span style={{ padding: '0 1px' }}>WithDev</span>
    <span style={{ color: '#6E45F7', fontFamily: "'JetBrains Mono', monospace", fontWeight: 500 }}>{'/>'}</span>
  </span>
);

// Typing headline that triggers when scrolled into view.
// Pass `text` with `\n` for line breaks. Renders a blinking purple cursor at the end.
const TypingHeadline = ({ text, speed = 55, style = {}, ...rest }) => {
  const ref = React.useRef(null);
  const [started, setStarted] = React.useState(false);
  const [typed, setTyped] = React.useState('');

  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)), speed);
    return () => clearTimeout(t);
  }, [started, typed, text, speed]);

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

  return (
    <h2 ref={ref} style={style} {...rest}>
      {parts.map((p, i) => (
        <React.Fragment key={i}>
          {i > 0 && <br />}
          {p}
        </React.Fragment>
      ))}
      {/* Cursor */}
      <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,
      }} />
      <style>{`
        @keyframes wd-blink {
          to { visibility: hidden; }
        }
      `}</style>
    </h2>
  );
};

Object.assign(window, { WordmarkLogo, TagLogo, TypingIntro, TypingHeadline });
