// Animated preview for the bottom-left of the case card.
// 3 variants controlled by tweak:
//  - "screens" : auto-cycle through 3 screen variants (cross-fade)
//  - "slide"   : screens slide horizontally
//  - "tap"     : cursor animates and taps elements on a single screen

// Each case study supplies 3 "screen" components for the preview.
// We render them small inside a phone-like card.

const PreviewFrame = ({ children, accent, surface }) => (
  <div style={{
    width: 148, height: 300, borderRadius: 24, background: '#0c0c0e',
    padding: 4,
    boxShadow: '0 1px 0 rgba(255,255,255,.05) inset, 0 20px 40px -10px rgba(0,0,0,.45)',
    position: 'relative', overflow: 'hidden', flexShrink: 0,
  }}>
    <div style={{
      position: 'absolute', inset: 4, borderRadius: 22, background: surface,
      overflow: 'hidden',
    }}>
      {children}
    </div>
  </div>
);

// Tiny screen renderers — minimal, abstract, readable at 168px wide
const screensFor = (caseId, accent, surface, fg) => {
  const baseTop = (label) => (
    <div style={{ padding: '24px 14px 0', color: fg, fontFamily: 'DM Sans, sans-serif' }}>
      <div style={{ fontSize: 8, opacity: .55, letterSpacing: '.08em', textTransform: 'uppercase' }}>{label}</div>
    </div>
  );

  if (caseId === 'mvno') {
    const fullImg = (src, alt) => (
      <img src={src} alt={alt} draggable={false}
           style={{ position: 'absolute', inset: 0, width: '100%', height: '100%',
                    objectFit: 'cover', objectPosition: 'top' }} />
    );
    return [
      fullImg('case-assets/mvno/anim-signup.png', 'Create your account — number selection'),
      fullImg('case-assets/mvno/anim-dashboard.png', 'Dashboard — local data & wallet'),
      fullImg('case-assets/mvno/anim-wallet.png', 'Wallet'),
      fullImg('case-assets/mvno/anim-topup.png', 'Top up'),
      fullImg('case-assets/mvno/anim-profile.png', 'Profile'),
    ];
  }

  if (caseId === '__mvno_old') {
    return [
      // Screen 1: data ring
      <>
        {baseTop('Twoja taryfa')}
        <div style={{ display: 'flex', justifyContent: 'center', marginTop: 18 }}>
          <div style={{
            width: 110, height: 110, borderRadius: '50%',
            background: `conic-gradient(${accent} 0% 70%, rgba(255,255,255,.08) 70% 100%)`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <div style={{ width: 80, height: 80, borderRadius: '50%', background: surface, display: 'flex',
                          flexDirection: 'column', alignItems: 'center', justifyContent: 'center', color: fg }}>
              <div style={{ fontFamily: 'Libre Bodoni, serif', fontSize: 22, fontWeight: 600, color: accent }}>14.2</div>
              <div style={{ fontSize: 8, opacity: .55 }}>GB / 20 GB</div>
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 5, padding: '18px 12px 0' }}>
          {['Doładuj', 'Pakiety', 'Roam'].map(t => (
            <div key={t} style={{ flex: 1, padding: '8px 0', background: 'rgba(255,255,255,.06)',
                                    borderRadius: 8, fontSize: 8, color: fg, textAlign: 'center' }}>{t}</div>
          ))}
        </div>
      </>,
      // Screen 2: pakiety list
      <>
        {baseTop('Pakiety dodatkowe')}
        <div style={{ padding: '12px 12px 0' }}>
          {[['+10 GB UE', '15 zł'], ['Nielimitowane SMS', '9 zł'], ['Roaming pl', '0 zł']].map(([n, p], i) => (
            <div key={i} style={{ display: 'flex', justifyContent: 'space-between',
                                    padding: '10px 0', borderTop: i ? '1px solid rgba(255,255,255,.07)' : 'none',
                                    color: fg, fontSize: 9 }}>
              <span>{n}</span><span style={{ color: accent, fontWeight: 600 }}>{p}</span>
            </div>
          ))}
        </div>
      </>,
      // Screen 3: confirm doładowanie
      <>
        {baseTop('Doładowanie')}
        <div style={{ padding: '24px 14px 0', color: fg, textAlign: 'center' }}>
          <div style={{ fontFamily: 'Libre Bodoni, serif', fontSize: 34, fontWeight: 600, color: accent }}>+10 GB</div>
          <div style={{ fontSize: 9, opacity: .55, marginTop: 4 }}>aktywne natychmiast</div>
        </div>
        <div style={{ position: 'absolute', left: 12, right: 12, bottom: 14,
                       background: accent, color: '#0e1739',
                       borderRadius: 10, padding: '10px 0', fontSize: 10, fontWeight: 700,
                       textAlign: 'center' }}>Potwierdź ↗</div>
      </>,
    ];
  }

  if (caseId === 'ecom') {
    const fullImg = (src, alt) => (
      <img src={src} alt={alt} draggable={false}
           style={{ position: 'absolute', inset: 0, width: '100%', height: '100%',
                    objectFit: 'cover', objectPosition: 'top' }} />
    );
    return [
      fullImg('case-assets/cashback/anim-zalando.png', 'Shop details — Zalando'),
      fullImg('case-assets/cashback/anim-cart.png', 'Shopping cart — products'),
      fullImg('case-assets/cashback/anim-paczkomat.png', 'Parcel locker pick-up'),
      fullImg('case-assets/cashback/anim-cart-empty.png', 'Empty cart'),
      fullImg('case-assets/cashback/anim-profile.png', 'Profile — cashback summary'),
    ];
  }

  if (caseId === '__ecom_old') {
    return [
      // 1: discover grid
      <>
        {baseTop('Discover')}
        <div style={{ padding: '10px 12px 0', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
          {[['#E87055', '79'], ['#D4B896', '129'], ['#2a4d4a', '49'], ['#EFD7C2', '89']].map(([bg, p], i) => (
            <div key={i} style={{ background: bg, borderRadius: 10, aspectRatio: '0.85',
                                    display: 'flex', alignItems: 'flex-end', padding: 6,
                                    color: i === 1 || i === 3 ? '#2a1f1a' : '#fff', fontSize: 9, fontWeight: 600 }}>
              {p} zł
            </div>
          ))}
        </div>
      </>,
      // 2: product detail
      <>
        <div style={{ height: 170, background: '#E87055', position: 'relative' }}>
          <div style={{ position: 'absolute', bottom: 10, left: 10, right: 10, color: '#fff' }}>
            <div style={{ fontFamily: 'Libre Bodoni, serif', fontSize: 18, fontWeight: 600 }}>Linen tee</div>
            <div style={{ fontSize: 9, opacity: .85 }}>cotton blend · 79 zł</div>
          </div>
        </div>
        <div style={{ padding: 12 }}>
          <div style={{ display: 'flex', gap: 5 }}>
            {['XS', 'S', 'M', 'L'].map((s, i) => (
              <div key={s} style={{ flex: 1, padding: '6px 0', borderRadius: 8,
                                      background: i === 1 ? fg : 'transparent',
                                      border: i === 1 ? 'none' : `1px solid ${fg}22`,
                                      color: i === 1 ? '#fff' : fg, textAlign: 'center', fontSize: 9 }}>{s}</div>
            ))}
          </div>
        </div>
        <div style={{ position: 'absolute', left: 12, right: 12, bottom: 12, padding: '9px 0',
                       background: fg, color: '#fff', borderRadius: 999, fontSize: 9, fontWeight: 600, textAlign: 'center' }}>
          Add to bag · 79 zł
        </div>
      </>,
      // 3: checkout
      <>
        {baseTop('Checkout')}
        <div style={{ padding: '12px 12px 0', color: fg }}>
          {[['Linen tee', '79 zł'], ['Cotton pants', '129 zł'], ['Delivery', '12 zł']].map(([n, p], i) => (
            <div key={i} style={{ display: 'flex', justifyContent: 'space-between',
                                    padding: '8px 0', borderTop: i ? '1px solid rgba(0,0,0,.08)' : 'none',
                                    fontSize: 9 }}>
              <span>{n}</span><span>{p}</span>
            </div>
          ))}
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '12px 0', borderTop: '1px solid rgba(0,0,0,.08)',
                         fontWeight: 700, fontFamily: 'Libre Bodoni, serif', fontSize: 14 }}>
            <span>Total</span><span>220 zł</span>
          </div>
        </div>
        <div style={{ position: 'absolute', left: 12, right: 12, bottom: 12, padding: '9px 0',
                       background: '#E87055', color: '#fff', borderRadius: 999, fontSize: 9, fontWeight: 600, textAlign: 'center' }}>
          Pay with Apple Pay
        </div>
      </>,
    ];
  }

  if (caseId === 'delivery') {
    const fullImg = (src, alt) => (
      <img src={src} alt={alt} draggable={false}
           style={{ position: 'absolute', inset: 0, width: '100%', height: '100%',
                    objectFit: 'cover', objectPosition: 'top' }} />
    );
    return [
      fullImg('case-assets/delivery/anim-stats-dark.png', 'Statistics — dark mode'),
      fullImg('case-assets/delivery/anim-list.jpg', 'Parcel list — undelivered'),
      fullImg('case-assets/delivery/anim-confirm-dark.png', 'Confirm delivery — scan'),
      fullImg('case-assets/delivery/anim-settings.png', 'Settings — dark mode toggle'),
      fullImg('case-assets/delivery/anim-confirm-light.png', 'Confirm delivery — light mode'),
    ];
  }

  if (caseId === '__delivery_old') {
    return [
      // 1: map + card
      <>
        <div style={{ height: 150, background: 'linear-gradient(135deg, #2a2e36, #1a1d22)', position: 'relative' }}>
          <svg viewBox="0 0 200 150" style={{ width: '100%', height: '100%' }}>
            <path d="M0 100 L200 100 M70 0 L70 150 M140 0 L140 150" stroke="rgba(255,255,255,.05)" strokeWidth="1" />
            <path d="M 20 130 Q 50 70, 100 80 T 180 30" fill="none" stroke="#F5C04C" strokeWidth="2.2" />
            <circle cx="20" cy="130" r="4" fill="#F5C04C" />
            <circle cx="180" cy="30" r="6" fill="#F5C04C" stroke="#1a1d22" strokeWidth="1.5" />
          </svg>
        </div>
        <div style={{ padding: 14, color: fg }}>
          <div style={{ fontSize: 8, opacity: .55, letterSpacing: '.08em', textTransform: 'uppercase' }}>Dostawa #284</div>
          <div style={{ fontFamily: 'Libre Bodoni, serif', fontSize: 16, fontWeight: 600, marginTop: 2 }}>Anna Nowak</div>
          <div style={{ fontSize: 9, opacity: .55 }}>Marszałkowska 14/8</div>
        </div>
      </>,
      // 2: scan
      <>
        {baseTop('Skan paczki')}
        <div style={{ display: 'flex', justifyContent: 'center', marginTop: 28 }}>
          <div style={{ width: 130, height: 130, borderRadius: 14, border: `2px dashed ${accent}`,
                          display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
            {[0, 1, 2, 3].map(i => (
              <div key={i} style={{
                position: 'absolute',
                [['top', 'top', 'bottom', 'bottom'][i]]: -1.5,
                [['left', 'right', 'left', 'right'][i]]: -1.5,
                width: 18, height: 18,
                borderTop: i < 2 ? `3px solid ${accent}` : 'none',
                borderBottom: i >= 2 ? `3px solid ${accent}` : 'none',
                borderLeft: i % 2 === 0 ? `3px solid ${accent}` : 'none',
                borderRight: i % 2 === 1 ? `3px solid ${accent}` : 'none',
              }} />
            ))}
            <div style={{ fontSize: 8, color: fg, opacity: .6 }}>EAN-13</div>
          </div>
        </div>
        <div style={{ position: 'absolute', left: 12, right: 12, bottom: 14,
                       textAlign: 'center', color: fg, fontSize: 9, opacity: .65 }}>
          Wskaż kod kreskowy
        </div>
      </>,
      // 3: confirmed
      <>
        <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', color: fg }}>
          <div style={{ width: 56, height: 56, borderRadius: '50%', background: accent,
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                          color: '#1a1d22', fontSize: 28, fontWeight: 700 }}>✓</div>
          <div style={{ fontFamily: 'Libre Bodoni, serif', fontSize: 18, fontWeight: 600, marginTop: 14 }}>Dostarczono</div>
          <div style={{ fontSize: 9, opacity: .55, marginTop: 4 }}>Anna N. · 14:23</div>
        </div>
      </>,
    ];
  }

  // fitness — laptop screens (real captures)
  const fullImg = (src, alt) => (
    <img src={src} alt={alt} draggable={false}
         style={{ position: 'absolute', inset: 0, width: '100%', height: '100%',
                  objectFit: 'cover', objectPosition: 'top' }} />
  );
  return [
    fullImg('case-assets/fitness/anim-landing.jpg', 'Landing page — personalised'),
    fullImg('case-assets/fitness/anim-landing-norecom.jpg', 'Landing page — survey prompt'),
    fullImg('case-assets/fitness/anim-email.jpg', 'Send recommendations modal'),
    fullImg('case-assets/fitness/anim-history.jpg', 'Workout history'),
  ];
};

const LaptopPreviewFrame = ({ children }) => (
  <div style={{ position: 'relative', display: 'flex', flexDirection: 'column',
                 alignItems: 'center', flexShrink: 0,
                 filter: 'drop-shadow(0 20px 36px rgba(0,0,0,.45))' }}>
    <div style={{
      width: 268, height: 168, borderRadius: 10,
      background: '#0c0c0e', padding: 5,
      boxShadow: '0 1px 0 rgba(255,255,255,.05) inset',
      position: 'relative',
    }}>
      <div style={{ position: 'absolute', inset: 5, borderRadius: 6,
                     overflow: 'hidden', background: '#fff' }}>
        {children}
      </div>
      <div style={{ position: 'absolute', top: 2, left: '50%', transform: 'translateX(-50%)',
                     width: 4, height: 4, borderRadius: '50%', background: '#2a2a2c' }} />
    </div>
    {/* base */}
    <div style={{ width: 300, height: 9,
                   background: 'linear-gradient(to bottom, #c8c9cc, #9c9ea3 55%, #6e7075)',
                   borderRadius: '0 0 8px 8px', position: 'relative' }}>
      <div style={{ position: 'absolute', top: 0, left: '50%', transform: 'translateX(-50%)',
                     width: 44, height: 3, background: '#5b5d62',
                     borderRadius: '0 0 4px 4px' }} />
    </div>
  </div>
);

const AnimatedPreview = ({ caseId, animationType, accent, surface, fg, version = 0 }) => {
  const screens = React.useMemo(() => screensFor(caseId, accent, surface, fg), [caseId, accent, surface, fg]);
  const isLaptop = caseId === 'fitness';
  const [idx, setIdx] = React.useState(0);
  const [tapXY, setTapXY] = React.useState(null);

  // Cycle screens on a timer (for screens / slide variants)
  React.useEffect(() => {
    if (animationType === 'tap') return undefined;
    setIdx(0);
    const interval = setInterval(() => {
      setIdx(i => (i + 1) % screens.length);
    }, 2200);
    return () => clearInterval(interval);
  }, [animationType, version, screens.length]);

  // Cursor tap loop for tap variant
  const tapTargets = [
    { x: 25, y: 78, label: 'CTA' },
    { x: 50, y: 50, label: 'Center' },
    { x: 78, y: 30, label: 'Top right' },
  ];
  const [tapStep, setTapStep] = React.useState(0);
  React.useEffect(() => {
    if (animationType !== 'tap') return undefined;
    setTapStep(0);
    const interval = setInterval(() => {
      setTapStep(s => (s + 1) % tapTargets.length);
    }, 1600);
    return () => clearInterval(interval);
  }, [animationType, version]);

  const Frame = isLaptop ? LaptopPreviewFrame : PreviewFrame;
  return (
    <Frame accent={accent} surface={surface}>
      {/* Screen stack */}
      {animationType === 'slide' ? (
        <div style={{
          position: 'absolute', inset: 0, display: 'flex',
          transform: `translateX(-${idx * 100}%)`,
          transition: 'transform .7s cubic-bezier(.7,0,.2,1)',
        }}>
          {screens.map((s, i) => (
            <div key={i} style={{ position: 'relative', minWidth: '100%', height: '100%' }}>{s}</div>
          ))}
        </div>
      ) : animationType === 'tap' ? (
        <>
          <div style={{ position: 'absolute', inset: 0 }}>{screens[0]}</div>
          {/* Cursor */}
          <div style={{
            position: 'absolute',
            left: `${tapTargets[tapStep].x}%`, top: `${tapTargets[tapStep].y}%`,
            width: 18, height: 18, marginLeft: -9, marginTop: -9,
            transition: 'left .9s cubic-bezier(.5,0,.2,1), top .9s cubic-bezier(.5,0,.2,1)',
            pointerEvents: 'none',
          }}>
            <div style={{
              position: 'absolute', inset: 0, borderRadius: '50%',
              background: accent, opacity: .35,
              animation: 'tapPulse 1.6s ease-out infinite',
            }} />
            <div style={{
              position: 'absolute', inset: 4, borderRadius: '50%',
              background: '#fff', boxShadow: '0 1px 4px rgba(0,0,0,.4)',
            }} />
          </div>
          <style>{`
            @keyframes tapPulse {
              0%   { transform: scale(.5); opacity: .55 }
              60%  { transform: scale(2.4); opacity: 0 }
              100% { transform: scale(2.4); opacity: 0 }
            }
          `}</style>
        </>
      ) : (
        // screens / cross-fade
        screens.map((s, i) => (
          <div key={i} style={{
            position: 'absolute', inset: 0,
            opacity: i === idx ? 1 : 0,
            transition: 'opacity .6s ease',
          }}>{s}</div>
        ))
      )}

      {/* Dots */}
      {animationType !== 'tap' && (
        <div style={{
          position: 'absolute', bottom: 8, left: 0, right: 0,
          display: 'flex', justifyContent: 'center', gap: 4, zIndex: 10,
        }}>
          {screens.map((_, i) => (
            <div key={i} style={{
              width: i === idx ? 14 : 4, height: 4, borderRadius: 2,
              background: i === idx ? accent : 'rgba(255,255,255,.4)',
              mixBlendMode: 'difference',
              transition: 'width .3s ease',
            }} />
          ))}
        </div>
      )}
    </Frame>
  );
};

Object.assign(window, { AnimatedPreview, PreviewFrame });
