// Shared primitives — Deeran Digital
const { useState, useEffect, useRef, useMemo } = React;

// The Deeran Digital lockup — DEERAN (Archivo Black) over DIGITAL (Archivo Light, 0.34em).
function Logo({ height = 38 }) {
  return (
    <img src="./assets/logo-deeran-digital-white.png" alt="Deeran Digital"
      decoding="async"
      style={{ height, width: 'auto', display: 'block', flexShrink: 0 }} />
  );
}

// Wordmark is the lockup — kept as a named export because the nav and footer call it.
function Wordmark({ height = 38 }) {
  return (
    <a href="index.html" style={{ display: 'flex', alignItems: 'center', textDecoration: 'none', flexShrink: 0 }}>
      <Logo height={height}/>
    </a>
  );
}

function Eyebrow({ children, tone = 'red' }) {
  const tones = {
    red:   { color: '#0784BE', bg: 'rgba(7,132,190,0.10)', bd: 'rgba(7,132,190,0.40)' },
    white: { color: '#fff', bg: 'rgba(255,255,255,0.06)', bd: 'rgba(255,255,255,0.22)' },
    solid: { color: '#fff', bg: '#0784BE', bd: '#0784BE' },
  };
  const t = tones[tone];
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 8,
      padding: '7px 14px',
      fontFamily: 'Archivo', fontWeight: 300, fontSize: 12, letterSpacing: '0.34em',
      color: t.color, background: t.bg, border: `1px solid ${t.bd}`,
      borderRadius: 999, textTransform: 'uppercase',
    }}>
      <span style={{
        width: 6, height: 6, borderRadius: '50%', background: t.color,
        boxShadow: tone === 'red' ? '0 0 8px rgba(7,132,190,0.8)' : 'none',
      }}/>
      {children}
    </span>
  );
}

function Button({ children, variant = 'primary', size = 'md', onClick, iconAfter = true, as, href }) {
  const [hover, setHover] = useState(false);
  const sizes = {
    sm: { p: '10px 18px',  f: 12 },
    md: { p: '14px 26px', f: 14 },
    lg: { p: '18px 32px', f: 15 },
    xl: { p: '22px 42px', f: 16 },
  }[size];
  const variants = {
    primary: {
      bg: hover ? '#1D96D4' : '#0784BE',
      color: '#fff',
      border: '1px solid rgba(255,255,255,0.08)',
      shadow: hover ? '0 14px 38px rgba(7,132,190,0.55)' : '0 10px 30px rgba(7,132,190,0.35)',
    },
    secondary: {
      bg: hover ? 'rgba(255,255,255,0.12)' : 'rgba(255,255,255,0.06)',
      color: '#fff',
      border: '1px solid rgba(255,255,255,0.18)',
      shadow: 'none',
    },
    ghost: {
      bg: hover ? 'rgba(255,255,255,0.06)' : 'transparent',
      color: '#fff',
      border: '1px solid transparent',
      shadow: 'none',
    },
    outline: {
      bg: hover ? 'rgba(7,132,190,0.12)' : 'transparent',
      color: '#fff',
      border: '2px solid #0784BE',
      shadow: 'none',
    },
  }[variant];

  const Tag = as || 'button';
  return (
    <Tag
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      onClick={onClick} href={href}
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 10,
        padding: sizes.p, fontFamily: 'Archivo', fontWeight: 700, fontSize: sizes.f,
        letterSpacing: '0.06em', textTransform: 'uppercase',
        background: variants.bg, color: variants.color,
        border: variants.border, borderRadius: 999,
        boxShadow: variants.shadow,
        cursor: 'pointer', transition: 'all 240ms cubic-bezier(0.2, 0.6, 0.2, 1)',
        textDecoration: 'none', whiteSpace: 'nowrap',
      }}>
      <span>{children}</span>
      {iconAfter && (
        <span style={{
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          width: 20, height: 20, borderRadius: '50%',
          background: variant === 'primary' ? 'rgba(255,255,255,0.18)' : 'rgba(255,255,255,0.10)',
          fontSize: 11, transform: hover ? 'translateX(3px)' : 'translateX(0)',
          transition: 'transform 220ms cubic-bezier(0.2, 0.6, 0.2, 1)',
        }}>→</span>
      )}
    </Tag>
  );
}

function Rating({ small = false }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 10,
      background: 'rgba(23, 166, 115, 0.9)', padding: small ? '6px 12px' : '8px 14px',
      borderRadius: 8, border: '1px solid rgba(23, 166, 115, 0.3)',
    }}>
      <span style={{ color: '#5FD8AC', letterSpacing: 2, fontSize: small ? 11 : 13 }}>★★★★★</span>
      <span style={{ color: '#fff', fontSize: small ? 11 : 12, fontWeight: 700 }}>
        Rated <b style={{ color: '#5FD8AC' }}>4.85/5</b> by Verified Clients
      </span>
    </div>
  );
}

function AvatarStack({ size = 50 }) {
  // Client avatar row (1203x230 PNG), carried over from the source site.
  const displayHeight = size;
  const displayWidth = Math.round((1203 / 230) * displayHeight);
  return (
    <img src="./assets/client-avatars-row.png" alt="Profile photos of service business owners who work with Deeran Digital"
      width={1203} height={230} decoding="async"
      style={{
        height: displayHeight, width: displayWidth,
        display: 'block', flexShrink: 0,
        filter: 'drop-shadow(0 2px 6px rgba(0,0,0,0.35))',
      }}/>
  );
}

function Arrow({ size = 14 }) {
  return <span style={{ display: 'inline-block', fontSize: size, lineHeight: 1 }}>→</span>;
}

// "Chapter" section heading — eyebrow + numeric marker
function SectionMark({ num, children, tone = 'red' }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
      <span style={{
        fontFamily: 'Archivo', fontWeight: 800, fontSize: 13,
        color: tone === 'red' ? '#0784BE' : '#fff',
        letterSpacing: '0.04em',
      }}>{num}</span>
      <span style={{ width: 48, height: 1, background: tone === 'red' ? 'rgba(7,132,190,0.5)' : 'rgba(255,255,255,0.2)' }}/>
      <span style={{
        fontFamily: 'Archivo', fontWeight: 300, fontSize: 12,
        color: tone === 'red' ? '#0784BE' : 'rgba(255,255,255,0.7)',
        letterSpacing: '0.34em', textTransform: 'uppercase',
      }}>{children}</span>
    </div>
  );
}

// Signal Blue go-disc — small round arrow button
function GoDisc({ size = 36, onClick }) {
  const [hover, setHover] = useState(false);
  return (
    <div onClick={onClick}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        width: size, height: size, borderRadius: '50%',
        background: hover ? '#1D96D4' : '#0784BE',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        color: '#fff', fontSize: size * 0.42, fontWeight: 700,
        cursor: 'pointer', transition: 'all 240ms cubic-bezier(0.2, 0.6, 0.2, 1)',
        boxShadow: hover ? '0 6px 18px rgba(7,132,190,0.5)' : '0 3px 10px rgba(7,132,190,0.3)',
        flexShrink: 0,
      }}>→</div>
  );
}

// Animated counter that counts up when scrolled into view
function Counter({ to, duration = 1600, prefix = '', suffix = '' }) {
  const [val, setVal] = useState(0);
  const ref = useRef(null);
  const started = useRef(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting && !started.current) {
          started.current = true;
          const start = performance.now();
          const step = (now) => {
            const t = Math.min(1, (now - start) / duration);
            const eased = 1 - Math.pow(1 - t, 3);
            setVal(Math.round(to * eased));
            if (t < 1) requestAnimationFrame(step);
          };
          requestAnimationFrame(step);
        }
      });
    }, { threshold: 0.3 });
    io.observe(el);
    return () => io.disconnect();
  }, [to, duration]);
  return <span ref={ref}>{prefix}{val.toLocaleString()}{suffix}</span>;
}

// LineWave — layered sine-wave strokes drifting horizontally.
// Each layer is one seamless 2-period path translated by exactly one period, so the
// loop is invisible. Visual rules + @keyframes live in site-styles.css (.mf-wave-layer).
function LineWave({ lines = 7, height = 720, width = 1440 }) {
  const layers = useMemo(() => (
    Array.from({ length: lines }).map((_, i) => {
      const t = i / Math.max(1, lines - 1);
      // Each line sits lower, waves a little flatter, and drifts a little slower.
      const period = width * (0.62 + t * 0.5);
      const amp = 46 - t * 20;
      const baseY = height * (0.30 + t * 0.085);
      const steps = 64;
      // Build one 2-period path so a -period translate loops seamlessly.
      let d = '';
      for (let s = 0; s <= steps * 2; s++) {
        const x = (s / steps) * period;
        const y = baseY + Math.sin((s / steps) * Math.PI * 2 + t * 2.4) * amp;
        d += (s === 0 ? 'M' : 'L') + x.toFixed(1) + ' ' + y.toFixed(1) + ' ';
      }
      return {
        d,
        period,
        duration: (16 + i * 3.5).toFixed(1),
        delay: (-i * 2.1).toFixed(1),
        opacity: 0.5 - t * 0.3,
        strokeWidth: 1.4 - t * 0.5,
        reverse: i % 2 === 1,
      };
    })
  ), [lines, height, width]);

  return (
    <svg viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="xMidYMid slice" aria-hidden
      style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none' }}>
      <defs>
        <linearGradient id="mf-wave-stroke" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%"   stopColor="#0784BE" stopOpacity="0"/>
          <stop offset="22%"  stopColor="#0784BE" stopOpacity="0.85"/>
          <stop offset="58%"  stopColor="#4FB4E4" stopOpacity="1"/>
          <stop offset="88%"  stopColor="#8CD0F0" stopOpacity="0.5"/>
          <stop offset="100%" stopColor="#8CD0F0" stopOpacity="0"/>
        </linearGradient>
      </defs>
      {layers.map((l, i) => (
        <g key={i} className="mf-wave-layer" style={{
          '--mf-wave-shift': (l.reverse ? l.period : -l.period) + 'px',
          animationDuration: l.duration + 's',
          animationDelay: l.delay + 's',
          opacity: l.opacity,
        }}>
          <path d={l.d} fill="none" stroke="url(#mf-wave-stroke)"
            strokeWidth={l.strokeWidth} strokeLinecap="round"/>
          {/* second copy, one period along, so the translate never reveals an edge */}
          <path d={l.d} fill="none" stroke="url(#mf-wave-stroke)"
            strokeWidth={l.strokeWidth} strokeLinecap="round"
            transform={`translate(${l.reverse ? -l.period : l.period} 0)`}/>
        </g>
      ))}
    </svg>
  );
}

Object.assign(window, { Logo, Wordmark, Eyebrow, Button, Rating, AvatarStack, Arrow, SectionMark, GoDisc, Counter, LineWave });
