// Apple devices animation — responsive, correct notch shapes
const { useState: useStateAD, useEffect: useEffectAD, useCallback: useCallbackAD, useRef: useRefAD } = React;
// Natural pixel width of the device row at scale=1 (iPhone + gaps + MacBook_base + gaps + iPad)
const AD_BASE_WIDTH = 680;

const PHASE = {
  REQUIREMENTS: { label: 'Requirements', desc: 'Analyzing specifications…', step: 1 },
  PLANNING: { label: 'Planning', desc: 'Defining test strategy…', step: 2 },
  DEVELOPMENT: { label: 'Development', desc: 'Building test scripts…', step: 3 },
  EXECUTION: { label: 'Execution', desc: 'Running automated suites…', step: 4 },
  VERIFICATION: { label: 'Verification', desc: 'Validating fixes…', step: 5 },
  CLOSURE: { label: 'Closure', desc: 'Quality gates passed.', step: 6 }
};

function BugIcon() {
  return (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M8 2l1.88 1.88M14.12 3.88L16 2M9 7.13v-1a3 3 0 1 1 6 0v1M12 20v-9M6.53 9a8 8 0 0 0 11 0M19 18a8 8 0 0 0-14 0" />
    </svg>);

}

function CheckIcon() {
  return (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="10" /><path d="M9 12l2 2 4-4" />
    </svg>);

}

function ScreenContent({ isFaulty, isVerified }) {
  return (
    <div style={{
      width: '100%',
      height: '100%',
      display: 'flex',
      flexDirection: 'column',
      padding: '6%',
      background: isFaulty ? '#fef2f2' : '#ffffff',
      transition: 'background-color 0.5s',
      color: '#1f2937'
    }}>
      {/* Header UI */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12, opacity: 0.5 }}>
        <div style={{ height: 6, width: '33%', background: '#cbd5e1', borderRadius: 999 }} />
        <div style={{ display: 'flex', gap: 4 }}>
          <div style={{ height: 6, width: 6, borderRadius: '50%', background: '#cbd5e1' }} />
          <div style={{ height: 6, width: 12, borderRadius: 999, background: '#cbd5e1' }} />
        </div>
      </div>

      {/* Hero Image Area */}
      <div style={{
        width: '100%',
        aspectRatio: '4/3',
        borderRadius: 8,
        marginBottom: 12,
        background: isFaulty ? '#fee2e2' : isVerified ? '#dcfce7' : '#f1f5f9',
        border: isFaulty ? '2px solid #fca5a5' : isVerified ? '2px solid #86efac' : 'none',
        transform: isFaulty ? 'rotate(1deg) scale(1.05)' : 'none',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        transition: 'all 0.5s',
        position: 'relative',
        color: isFaulty ? '#dc2626' : isVerified ? '#16a34a' : '#64748b'
      }}>
        {isFaulty && <BugIcon />}
        {isVerified && <CheckIcon />}
      </div>

      {/* Text Lines */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, opacity: 0.6, marginBottom: 12 }}>
        <div style={{ height: 6, width: '100%', borderRadius: 999, background: isFaulty ? '#fecaca' : '#cbd5e1', transition: 'all 0.5s' }} />
        <div style={{ height: 6, width: isFaulty ? '40%' : '83%', borderRadius: 999, background: isFaulty ? '#fecaca' : '#cbd5e1', transition: 'all 0.5s' }} />
        <div style={{ height: 6, width: '66%', borderRadius: 999, background: isFaulty ? '#fecaca' : '#cbd5e1', transition: 'all 0.5s' }} />
      </div>

      {/* Primary Button */}
      <div style={{
        marginTop: 'auto',
        height: 28,
        width: '100%',
        borderRadius: 8,
        background: isFaulty ? '#f87171' : isVerified ? '#22c55e' : '#1e293b',
        opacity: isFaulty ? 0.5 : 1,
        transform: isFaulty ? 'translateY(8px)' : 'none',
        transition: 'all 0.5s',
        boxShadow: '0 1px 3px rgba(0,0,0,0.1)'
      }} />
    </div>);

}

function AppleDevice({ type, isFaulty, isVerified }) {
  if (type === 'iphone') {
    return (
      <div style={{
        position: 'relative',
        width: '105px',
        height: '215px',
        borderRadius: '24px',
        background: '#1c1c1e',
        boxShadow: '0 20px 25px -5px rgba(0,0,0,0.3)',
        animation: isFaulty ? 'glitch 0.24s both infinite' : 'none'
      }}>
        {/* Outer Frame */}
        <div style={{
          position: 'absolute',
          inset: 0,
          borderRadius: '24px',
          border: '1px solid #3f3f3f',
          background: 'linear-gradient(135deg, #2a2a2a, #4a4a4a, #2a2a2a)',
          zIndex: 0
        }} />

        {/* Inner Black Bezel */}
        <div style={{
          position: 'absolute',
          inset: '3px',
          background: '#000',
          borderRadius: '21px',
          zIndex: 10
        }} />

        {/* Screen */}
        <div style={{
          position: 'absolute',
          inset: '6px',
          background: '#fff',
          borderRadius: '19px',
          overflow: 'hidden',
          zIndex: 20
        }}>
          <ScreenContent isFaulty={isFaulty} isVerified={isVerified} />
        </div>

        {/* Dynamic Island — pill, not oval */}
        <div style={{
          position: 'absolute',
          top: '9px',
          left: '50%',
          transform: 'translateX(-50%)',
          width: '36px',
          height: '12px',
          background: '#000',
          borderRadius: '999px',
          zIndex: 30
        }} />
      </div>);

  }

  if (type === 'ipad') {
    return (
      <div style={{
        position: 'relative',
        width: '180px',
        height: '240px',
        borderRadius: '18px',
        background: '#1a1a1a',
        boxShadow: '0 20px 25px -5px rgba(0,0,0,0.3)',
        animation: isFaulty ? 'glitch 0.24s both infinite' : 'none'
      }}>
        {/* Aluminum Frame */}
        <div style={{
          position: 'absolute',
          inset: 0,
          borderRadius: '18px',
          border: '1px solid #3f3f3f',
          background: 'linear-gradient(180deg, #3a3a3a, #1a1a1a)'
        }} />

        {/* Inner Bezel */}
        <div style={{
          position: 'absolute',
          inset: '6px',
          background: '#000',
          borderRadius: '14px'
        }} />

        {/* Screen */}
        <div style={{
          position: 'absolute',
          inset: '10px',
          background: '#fff',
          borderRadius: '12px',
          overflow: 'hidden'
        }}>
          <ScreenContent isFaulty={isFaulty} isVerified={isVerified} />
        </div>

        {/* Camera */}
        <div style={{
          position: 'absolute',
          top: '8px',
          left: '50%',
          transform: 'translateX(-50%)',
          width: '4px',
          height: '4px',
          background: '#1a1a1a',
          borderRadius: '50%',
          zIndex: 20
        }} />
      </div>);

  }

  if (type === 'macbook') {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', animation: isFaulty ? 'glitch 0.24s both infinite' : 'none' }}>
        {/* Lid */}
        <div style={{
          position: 'relative',
          width: '320px',
          height: '210px',
          borderRadius: '16px 16px 0 0',
          background: '#0f0f0f',
          boxShadow: '0 20px 25px -5px rgba(0,0,0,0.3)'
        }}>
          {/* Aluminum Border */}
          <div style={{
            position: 'absolute',
            inset: 0,
            borderRadius: '16px 16px 0 0',
            borderTop: '1px solid #333',
            borderLeft: '1px solid #333',
            borderRight: '1px solid #333',
            background: '#1a1a1a'
          }} />

          {/* Inner Bezel */}
          <div style={{
            position: 'absolute',
            inset: '2px',
            bottom: 0,
            background: '#000',
            borderRadius: '12px 12px 0 0'
          }} />

          {/* Screen */}
          <div style={{
            position: 'absolute',
            inset: '5px',
            bottom: 0,
            background: '#fff',
            borderRadius: '10px 10px 0 0',
            overflow: 'hidden',
            display: 'flex',
            flexDirection: 'column'
          }}>
            {/* Menu Bar */}
            <div style={{
              height: '24px',
              width: '100%',
              background: '#f3f4f6',
              borderBottom: '1px solid #e5e7eb',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              paddingLeft: '12px',
              paddingRight: '12px',
              fontSize: '10px',
              color: '#6b7280',
              fontWeight: 'bold'
            }}>
              <div style={{ display: 'flex', gap: 8 }}>
                <span></span> <span style={{ fontWeight: 600 }}>File</span> <span>Edit</span> <span>View</span>
              </div>
              <div style={{ display: 'flex', gap: 8 }}>
                <span>100%</span> <span>Fri 12:00</span>
              </div>
            </div>
            <div style={{ flex: 1, position: 'relative' }}>
              <ScreenContent isFaulty={isFaulty} isVerified={isVerified} />
            </div>
          </div>

          {/* MacBook notch — flat top, rounded bottom */}
          <div style={{
            position: 'absolute',
            top: 0,
            left: '50%',
            transform: 'translateX(-50%)',
            width: '52px',
            height: '14px',
            background: '#000',
            borderRadius: '0 0 10px 10px',
            zIndex: 20
          }} />
        </div>

        {/* Base / keyboard deck — wider than the lid for realistic proportions */}
        <div style={{
          width: '380px',
          height: '14px',
          background: 'linear-gradient(180deg, #2a2a2a, #111)',
          borderRadius: '0 0 14px 14px',
          boxShadow: '0 20px 25px -5px rgba(0,0,0,0.3)',
          position: 'relative',
          zIndex: 30,
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          borderTop: '1px solid #333'
        }}>
          <div style={{ width: '60px', height: '4px', background: '#1a1a1a', borderRadius: '0 0 8px 8px', opacity: 0.5 }} />
        </div>

        {/* Rubber Feet Shadow */}
        <div style={{
          width: '380px',
          height: '6px',
          background: 'rgba(0,0,0,0.3)',
          filter: 'blur(4px)',
          marginTop: '-4px',
          borderRadius: '50%'
        }} />
      </div>);

  }

  return null;
}

function Scanner({ active }) {
  if (!active) return null;
  return (
    <div style={{
      position: 'absolute',
      left: '-15%',
      right: '-15%',
      top: '-20%',
      bottom: '0',
      zIndex: 100,
      pointerEvents: 'none',
      overflow: 'hidden'
    }}>
      <div style={{
        position: 'absolute',
        top: '-10%',
        bottom: '-10%',
        width: '80px',
        animation: 'scan-swipe 3s cubic-bezier(0.4, 0, 0.2, 1) forwards',
        display: 'flex',
        alignItems: 'stretch',
        justifyContent: 'center',
        marginLeft: '-40px',
        left: '50%'
      }}>
        {/* Wide ambient glow trailing behind the line */}
        <div style={{
          position: 'absolute',
          top: 0,
          bottom: 0,
          width: '100%',
          background: 'linear-gradient(90deg, transparent 0%, rgba(59,59,239,0.12) 60%, rgba(59,59,239,0.22) 100%)',
          filter: 'blur(10px)',
        }} />
        {/* Thin 1px line with gradient shadow */}
        <div style={{
          position: 'absolute',
          top: 0,
          bottom: 0,
          right: 0,
          width: '1px',
          background: 'linear-gradient(180deg, transparent 0%, rgba(255,255,255,0.9) 15%, #fff 50%, rgba(255,255,255,0.9) 85%, transparent 100%)',
          boxShadow: '0 0 6px 2px rgba(59,59,239,0.7), 0 0 16px 4px rgba(59,59,239,0.35)',
        }} />
      </div>
    </div>);

}

function AppleDevicesAnimation() {
  const [phase, setPhase] = useStateAD('REQUIREMENTS');
  const [fixes, setFixes] = useStateAD({ iphone: false, macbook: false, ipad: false });
  const [scale, setScale] = useStateAD(1);
  const timer = useRefAD([]);
  const containerRef = useRefAD(null);

  // Compute scale so the device row always fits the container width
  useEffectAD(() => {
    const el = containerRef.current;
    if (!el) return;
    const update = () => {
      const s = Math.min(1, (el.offsetWidth * 0.94) / AD_BASE_WIDTH);
      setScale(s);
    };
    update();
    const ro = new ResizeObserver(update);
    ro.observe(el);
    return () => ro.disconnect();
  }, []);

  const runSimulation = useCallbackAD(() => {
    timer.current.forEach(clearTimeout);
    timer.current = [];
    setFixes({ iphone: false, macbook: false, ipad: false });

    const seq = [
    { t: 0, fn: () => setPhase('REQUIREMENTS') },
    { t: 500, fn: () => setPhase('PLANNING') },
    { t: 1000, fn: () => setPhase('DEVELOPMENT') },
    { t: 1800, fn: () => setPhase('EXECUTION') },
    { t: 4800, fn: () => setPhase('VERIFICATION') },
    { t: 5300, fn: () => setFixes((p) => ({ ...p, iphone: true })) },
    { t: 6100, fn: () => setFixes((p) => ({ ...p, macbook: true })) },
    { t: 6900, fn: () => setFixes((p) => ({ ...p, ipad: true })) },
    { t: 9500, fn: () => setPhase('CLOSURE') },
    { t: 12500, fn: runSimulation }];

    seq.forEach(({ t, fn }) => timer.current.push(window.setTimeout(fn, t)));
  }, []);

  useEffectAD(() => {
    runSimulation();
    return () => timer.current.forEach(clearTimeout);
  }, [runSimulation]);

  const isExec = phase === 'EXECUTION';
  const showDevices = phase !== 'REQUIREMENTS';
  const info = PHASE[phase];

  return (
    <div ref={containerRef} style={{
      position: 'relative',
      width: '100%',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      background: 'transparent',
    }}>
      <style>{`
        @keyframes scan-swipe {
          0% { left: -5%; opacity: 0; }
          15% { opacity: 1; }
          85% { opacity: 1; }
          100% { left: 105%; opacity: 0; }
        }
        @keyframes glitch {
          0% { transform: translate(0); }
          20% { transform: translate(-2px, 2px); }
          40% { transform: translate(-2px, -2px); }
          60% { transform: translate(2px, 2px); }
          80% { transform: translate(2px, -2px); }
          100% { transform: translate(0); }
        }
      `}</style>

      {/* Stage: height matches the visual (scaled) height of the device row so the badge never overlaps */}
      <div style={{
        position: 'relative',
        width: '100%',
        height: `${264 * scale}px`,
        overflow: 'visible',
      }}>
        <Scanner active={phase === 'VERIFICATION'} />

        {/* Device row anchored to the bottom of the stage, scaled from that bottom edge */}
        <div style={{
          position: 'absolute',
          bottom: 0,
          left: '50%',
          transform: `translateX(-50%) scale(${scale})`,
          transformOrigin: 'bottom center',
          display: 'flex',
          alignItems: 'flex-end',
          justifyContent: 'center',
          gap: '32px',
          perspective: '1000px',
        }}>
          {/* iPhone */}
          <div style={{
            zIndex: 30,
            transform: showDevices ? 'translateY(0) scaleY(1)' : 'translateY(40px) scaleY(0.9)',
            opacity: showDevices ? 1 : 0,
            transition: 'all 0.7s ease-out'
          }}>
            <AppleDevice type="iphone" isFaulty={isExec && !fixes.iphone} isVerified={fixes.iphone} />
          </div>

          {/* MacBook */}
          <div style={{
            zIndex: 20,
            marginBottom: '-8px',
            transform: showDevices ? 'none' : 'scaleY(0.95)',
            opacity: showDevices ? 1 : 0,
            transition: 'all 1s ease-out 100ms'
          }}>
            <AppleDevice type="macbook" isFaulty={isExec && !fixes.macbook} isVerified={fixes.macbook} />
          </div>

          {/* iPad */}
          <div style={{
            zIndex: 10,
            transform: showDevices ? 'translateY(0) scaleY(1)' : 'translateY(40px) scaleY(0.9)',
            opacity: showDevices ? 1 : 0,
            transition: 'all 0.7s ease-out 200ms'
          }}>
            <AppleDevice type="ipad" isFaulty={isExec && !fixes.ipad} isVerified={fixes.ipad} />
          </div>
        </div>
      </div>

      {/* Phase Badge — always flows below the stage, never overlaps devices */}
      <div style={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        gap: '4px',
        width: '100%',
        maxWidth: '320px',
        marginTop: '20px',
      }}>
        <div style={{
          background: 'var(--bg-elev, rgba(255,255,255,0.9))',
          backdropFilter: 'blur(12px)',
          padding: '12px 24px',
          borderRadius: '16px',
          border: '1px solid var(--line-strong, rgba(0,0,0,0.12))',
          boxShadow: '0 4px 6px rgba(0,0,0,0.05)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          width: '100%',
          transition: 'all 0.3s'
        }}>
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            <span style={{ fontSize: '10px', fontWeight: 'bold', color: '#9ca3af', letterSpacing: '0.1em', marginBottom: '2px' }}>
              Phase 0{info.step} / 06
            </span>
            <span style={{ fontSize: '14px', fontWeight: 'bold', color: '#1f2937', letterSpacing: '0.05em' }}>
              {info.label}
            </span>
          </div>

          <div style={{
            width: '8px',
            height: '8px',
            borderRadius: '50%',
            transition: 'all 0.3s',
            background: isExec ? '#f43f5e' : phase === 'CLOSURE' ? '#10b981' : '#3b82f6',
            boxShadow: isExec ? '0 0 8px rgba(244,63,94,0.6)' : phase === 'CLOSURE' ? '0 0 8px rgba(16,185,129,0.6)' : 'none',
            animation: isExec ? 'pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite' : 'none'
          }} />
        </div>

        <div style={{
          fontSize: '11px',
          fontWeight: '500',
          color: '#6b7280',
          letterSpacing: '0.05em',
          background: 'rgba(255,255,255,0.6)',
          backdropFilter: 'blur(8px)',
          padding: '4px 12px',
          borderRadius: '9999px',
          border: '1px solid rgba(255,255,255,0.4)',
          boxShadow: '0 1px 3px rgba(0,0,0,0.1)',
          transition: 'all 0.5s'
        }}>
          {info.desc}
        </div>
      </div>
    </div>);

}

Object.assign(window, { AppleDevicesAnimation });