// Apple Bank × Liquid Data — shared components
// Exposes globals at bottom for cross-file Babel scope sharing.

const { useState, useEffect, useRef, useMemo } = React;

/* ─────────── ICONS ─────────── */

function AppleIcon({ size = 64, animate = false, style }) {
  // Hand-drawn editorial apple — red body, brown stem, single leaf
  return (
    <svg
      viewBox="0 0 100 110" width={size} height={size * 1.1}
      style={{ display: 'block', ...style }}
      aria-hidden="true"
    >
      <defs>
        <radialGradient id="ab-apple-grad" cx="38%" cy="36%" r="70%">
          <stop offset="0%" stopColor="#F25555" />
          <stop offset="60%" stopColor="#D72D2D" />
          <stop offset="100%" stopColor="#A8201F" />
        </radialGradient>
      </defs>
      {/* leaf */}
      <path
        d="M55 18 C 68 8, 82 12, 80 26 C 78 36, 66 36, 56 28 Z"
        fill="#4A8B2C"
        style={animate ? { transformOrigin: '56px 22px', animation: 'ab-sway 2.4s ease-in-out infinite' } : null}
      />
      <path d="M58 24 C 64 20, 72 20, 76 24" stroke="#3A6E22" strokeWidth="1" fill="none" />
      {/* stem */}
      <path d="M50 26 C 51 18, 53 14, 55 12" stroke="#6B3A1E" strokeWidth="3.2" strokeLinecap="round" fill="none" />
      {/* body */}
      <path
        d="M50 28 C 30 24, 14 38, 16 62 C 18 86, 36 102, 50 100 C 64 102, 82 86, 84 62 C 86 38, 70 24, 50 28 Z"
        fill="url(#ab-apple-grad)"
      />
      {/* highlight */}
      <ellipse cx="34" cy="46" rx="7" ry="11" fill="#fff" opacity="0.32" transform="rotate(-22 34 46)" />
    </svg>
  );
}

function AppleMark({ size = 20 }) {
  return <AppleIcon size={size} />;
}

function IconChevron({ size = 16, dir = 'right' }) {
  const rot = { right: 0, left: 180, up: -90, down: 90 }[dir];
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" style={{ transform: `rotate(${rot}deg)` }}>
      <path d="M9 6l6 6-6 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" fill="none" />
    </svg>
  );
}

function IconCheck({ size = 24, color = '#fff' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24">
      <path d="M5 12.5l4.5 4.5L19 7.5" stroke={color} strokeWidth="2.8" strokeLinecap="round" strokeLinejoin="round" fill="none" />
    </svg>
  );
}

function IconSearch({ size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24">
      <circle cx="11" cy="11" r="6.5" stroke="currentColor" strokeWidth="2" fill="none" />
      <path d="M16 16l4 4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
    </svg>
  );
}

function IconShare({ size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 3v13" /><path d="M7 8l5-5 5 5" /><path d="M5 13v6a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-6" />
    </svg>
  );
}

function IconPhone({ size = 16 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z" />
    </svg>
  );
}

function IconMail({ size = 16 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="2" y="4" width="20" height="16" rx="2" /><path d="M22 7l-10 6L2 7" />
    </svg>
  );
}

/* ─────────── ATOMS ─────────── */

function ProgressBar({ step, total = 8, label }) {
  const pct = Math.max(4, Math.round((step / total) * 100));
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <div style={{
        height: 4, background: 'var(--ab-line)', borderRadius: 999, overflow: 'hidden',
      }}>
        <div style={{
          width: `${pct}%`, height: '100%',
          background: 'linear-gradient(90deg, var(--ab-navy) 0%, var(--ab-navy-deep) 100%)',
          borderRadius: 999, transition: 'width 0.4s cubic-bezier(.2,.8,.2,1)',
        }} />
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
        <span className="t-eyebrow" style={{ color: 'var(--ab-ink-mute)', whiteSpace: 'nowrap' }}>{label || `Step ${step} of ${total}`}</span>
        <span className="t-eyebrow" style={{ color: 'var(--ab-navy)', whiteSpace: 'nowrap', flexShrink: 0 }}>{Math.round((step / total) * 100)}%</span>
      </div>
    </div>
  );
}

function Button({ children, variant = 'primary', size = 'lg', onClick, full = true, icon, disabled }) {
  const isPrimary = variant === 'primary';
  const isGhost   = variant === 'ghost';
  const isOutline = variant === 'outline';
  const pads = size === 'lg' ? '18px 28px' : size === 'md' ? '14px 22px' : '10px 18px';
  const fs   = size === 'lg' ? 17 : size === 'md' ? 15 : 14;

  const base = {
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
    width: full ? '100%' : 'auto',
    padding: pads, fontSize: fs, fontWeight: 600, fontFamily: 'var(--ab-sans)',
    borderRadius: 'var(--ab-r-pill)', border: 'none', cursor: 'pointer',
    transition: 'transform .15s ease, box-shadow .2s ease, background .2s ease',
    letterSpacing: '-0.005em', lineHeight: 1,
  };
  const variantStyles = isPrimary ? {
    background: 'var(--ab-navy)', color: '#fff', boxShadow: 'var(--ab-shadow-btn)',
  } : isOutline ? {
    background: 'transparent', color: 'var(--ab-navy)', border: '1.5px solid var(--ab-navy)', boxShadow: 'none',
  } : {
    background: 'transparent', color: 'var(--ab-ink)', boxShadow: 'none',
  };

  return (
    <button
      onClick={disabled ? null : onClick}
      disabled={disabled}
      style={{ ...base, ...variantStyles, opacity: disabled ? 0.5 : 1 }}
      onMouseEnter={(e) => isPrimary && !disabled && (e.currentTarget.style.boxShadow = 'var(--ab-shadow-btn-hover)', e.currentTarget.style.transform = 'translateY(-1px)')}
      onMouseLeave={(e) => isPrimary && !disabled && (e.currentTarget.style.boxShadow = 'var(--ab-shadow-btn)', e.currentTarget.style.transform = 'translateY(0)')}
    >
      {children}
      {icon && <IconChevron />}
    </button>
  );
}

function Chip({ children, selected, onClick, size = 'md', icon, disabled }) {
  const pads = size === 'lg' ? '14px 18px' : '11px 16px';
  const fs   = size === 'lg' ? 15 : 14;
  return (
    <button
      onClick={disabled ? null : onClick}
      disabled={disabled}
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 6, padding: pads, fontSize: fs,
        fontFamily: 'var(--ab-sans)', fontWeight: 500, lineHeight: 1,
        borderRadius: 'var(--ab-r-chip)', cursor: disabled ? 'not-allowed' : 'pointer',
        background: selected ? 'var(--ab-navy)' : 'var(--ab-paper)',
        color: selected ? '#fff' : 'var(--ab-ink)',
        border: selected ? '1.5px solid var(--ab-navy)' : '1.5px solid var(--ab-line)',
        boxShadow: selected ? '0 2px 0 -1px rgba(15, 38, 89, 0.28)' : 'none',
        transition: 'all .15s ease', opacity: disabled ? 0.4 : 1,
      }}
    >
      {icon}{children}
    </button>
  );
}

function StatCard({ value, label, sub, accent = 'red' }) {
  const c = accent === 'green' ? 'var(--ab-leaf)' : 'var(--ab-red)';
  return (
    <div style={{
      background: 'var(--ab-paper)', borderRadius: 'var(--ab-r-card)',
      borderLeft: `3px solid ${c}`,
      padding: '18px 18px 18px 20px',
      boxShadow: 'var(--ab-shadow-card)',
      display: 'flex', flexDirection: 'column', gap: 4,
    }}>
      <div style={{ fontFamily: 'var(--ab-serif)', fontWeight: 700, fontSize: 30, lineHeight: 1, color: c, letterSpacing: '-0.02em' }}>{value}</div>
      <div style={{ fontFamily: 'var(--ab-sans)', fontWeight: 600, fontSize: 14, color: 'var(--ab-ink)' }}>{label}</div>
      {sub && <div style={{ fontFamily: 'var(--ab-sans)', fontSize: 13, color: 'var(--ab-ink-soft)', lineHeight: 1.4 }}>{sub}</div>}
    </div>
  );
}

function GrandPrizeTile({ title, sub, label = 'Grand prize' }) {
  return (
    <div style={{
      position: 'relative', overflow: 'hidden',
      background: 'linear-gradient(155deg, #E83D3D 0%, #C7282A 50%, #8E1A1A 100%)',
      borderRadius: 'var(--ab-r-tile)', padding: '26px 22px 24px',
      color: '#fff', boxShadow: '0 30px 60px -30px rgba(168, 32, 31, 0.6), inset 0 1px 0 rgba(255,255,255,0.18)',
    }}>
      {/* apple silhouette behind */}
      <div style={{ position: 'absolute', right: -22, top: -28, opacity: 0.16, transform: 'rotate(14deg)' }}>
        <AppleIcon size={150} />
      </div>
      <div style={{ position: 'relative' }}>
        <div className="t-eyebrow" style={{ color: 'rgba(255,255,255,0.7)', marginBottom: 8 }}>{label}</div>
        <div style={{ fontFamily: 'var(--ab-serif)', fontWeight: 700, fontSize: 30, lineHeight: 1.05, letterSpacing: '-0.02em', textWrap: 'balance' }}>{title}</div>
        {sub && <div style={{ fontSize: 14, marginTop: 10, color: 'rgba(255,255,255,0.82)', lineHeight: 1.45 }}>{sub}</div>}
      </div>
    </div>
  );
}

function SecondaryPrizeTile({ title, sub, label = 'Secondary prize' }) {
  return (
    <div style={{
      background: 'var(--ab-paper)', border: '1.5px solid var(--ab-red)',
      borderRadius: 'var(--ab-r-tile)', padding: '22px 20px',
      boxShadow: 'var(--ab-shadow-card)',
    }}>
      <div className="t-eyebrow" style={{ color: 'var(--ab-red)', marginBottom: 8 }}>{label}</div>
      <div style={{ fontFamily: 'var(--ab-serif)', fontWeight: 700, fontSize: 22, lineHeight: 1.1, color: 'var(--ab-ink)', letterSpacing: '-0.01em' }}>{title}</div>
      {sub && <div style={{ fontSize: 13, marginTop: 8, color: 'var(--ab-ink-soft)', lineHeight: 1.45 }}>{sub}</div>}
    </div>
  );
}

function Input({ value, onChange, placeholder, type = 'text', icon, suffix }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10, padding: '14px 16px',
      background: 'var(--ab-paper)', border: '1.5px solid var(--ab-line)',
      borderRadius: 'var(--ab-r-chip)',
      transition: 'border-color .15s, box-shadow .15s',
    }}
    onFocus={(e) => e.currentTarget.style.borderColor = 'var(--ab-navy)'}
    >
      {icon && <span style={{ color: 'var(--ab-ink-mute)', display: 'flex' }}>{icon}</span>}
      <input
        value={value || ''}
        onChange={(e) => onChange && onChange(e.target.value)}
        placeholder={placeholder}
        type={type}
        style={{
          flex: 1, border: 'none', outline: 'none', background: 'transparent',
          fontFamily: 'var(--ab-sans)', fontSize: 15, color: 'var(--ab-ink)',
          minWidth: 0,
        }}
      />
      {suffix && <span style={{ color: 'var(--ab-ink-mute)', fontSize: 13 }}>{suffix}</span>}
    </div>
  );
}

/* ─────────── NYC SPOT ILLUSTRATIONS ─────────── *
   Simple editorial line-work — New Yorker spot style.
   Used as recurring visual anchors. */

function NYCStoop({ width = 320, height = 180, accent = false }) {
  return (
    <svg viewBox="0 0 320 180" width={width} height={height} style={{ display: 'block' }}>
      <rect width="320" height="180" fill="var(--ab-cream-2)" />
      {/* brownstone facade */}
      <rect x="40" y="20" width="240" height="160" fill="#E6D9C4" />
      {/* windows */}
      {[0,1,2].map(c => [0,1].map(r => (
        <g key={`${c}-${r}`}>
          <rect x={60 + c*70} y={36 + r*46} width="46" height="32" fill="#FAF7F2" stroke="var(--ab-stem)" strokeWidth="1.2" />
          <line x1={83 + c*70} y1={36 + r*46} x2={83 + c*70} y2={68 + r*46} stroke="var(--ab-stem)" strokeWidth="0.8" />
          <line x1={60 + c*70} y1={52 + r*46} x2={106 + c*70} y2={52 + r*46} stroke="var(--ab-stem)" strokeWidth="0.8" />
        </g>
      )))}
      {/* stoop steps */}
      <polygon points="40,140 280,140 300,180 20,180" fill="#D6C5A8" />
      <line x1="20" y1="180" x2="300" y2="180" stroke="var(--ab-stem)" strokeWidth="1.5" />
      <line x1="30" y1="160" x2="290" y2="160" stroke="var(--ab-stem)" strokeWidth="1" />
      {/* door */}
      <rect x="140" y="92" width="40" height="48" fill="var(--ab-red)" />
      <circle cx="172" cy="118" r="1.5" fill="#FFD96B" />
      {/* tree */}
      <rect x="6" y="120" width="6" height="60" fill="var(--ab-stem)" />
      <circle cx="9" cy="118" r="14" fill="var(--ab-leaf)" opacity="0.85" />
      {accent && <circle cx="160" cy="76" r="6" fill="var(--ab-red)" />}
    </svg>
  );
}

function NYCSubwayTile({ width = 320, height = 90 }) {
  // subway tile pattern with apple bank red sign
  return (
    <svg viewBox="0 0 320 90" width={width} height={height} style={{ display: 'block' }}>
      <rect width="320" height="90" fill="#F5EFE3" />
      {[...Array(4)].map((_, r) =>
        [...Array(10)].map((_, c) => {
          const x = c * 32 + (r % 2 ? 16 : 0);
          return <rect key={`${r}-${c}`} x={x} y={r*22 + 2} width="28" height="18" rx="2" fill="#fff" stroke="#E5DFD4" strokeWidth="0.8" />;
        })
      )}
      <circle cx="160" cy="45" r="22" fill="var(--ab-red)" />
      <text x="160" y="52" textAnchor="middle" fontFamily="var(--ab-serif)" fontSize="22" fontWeight="700" fill="#fff">1</text>
    </svg>
  );
}

function ConfettiBurst() {
  const bits = Array.from({ length: 18 }, (_, i) => ({
    x: (i * 37) % 280 + 20,
    y: (i * 23) % 80 + 10,
    rot: i * 23,
    color: ['var(--ab-red)', 'var(--ab-leaf)', 'var(--ab-stem)', '#E8B86A'][i % 4],
    w: 6 + (i % 3) * 2,
  }));
  return (
    <svg viewBox="0 0 320 100" width="100%" height="60" style={{ display: 'block', position: 'absolute', top: -10, left: 0 }}>
      {bits.map((b, i) => (
        <rect key={i} x={b.x} y={b.y} width={b.w} height="3" fill={b.color} transform={`rotate(${b.rot} ${b.x} ${b.y})`} opacity="0.85" />
      ))}
    </svg>
  );
}

/* ─────────── DANCING CAN HERO (mobile S1) ─────────── */

function AppleDropHero({ animated = true, canSize = 220, height = 300 }) {
  // Sparkle positions — small marks that fly outward around the dancing can
  const sparkles = [
    { x: -40, y: -10, sx: -50, sy: -60, delay: 0.0,  color: 'var(--ab-red)' },
    { x: 38,  y: 20,  sx: 60,  sy: -40, delay: 0.6,  color: 'var(--ab-leaf)' },
    { x: -32, y: 80,  sx: -70, sy: -20, delay: 1.2,  color: 'var(--ab-red)' },
    { x: 44,  y: 110, sx: 80,  sy: -30, delay: 1.8,  color: 'var(--ab-stem)' },
    { x: 0,   y: -20, sx: 10,  sy: -80, delay: 2.4,  color: 'var(--ab-red)' },
  ];
  return (
    <div style={{
      position: 'relative', height: height, width: '100%',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
      overflow: 'visible',
    }}>
      {/* sparkles */}
      {animated && sparkles.map((s, i) => (
        <div key={i} style={{
          position: 'absolute',
          left: `calc(50% + ${s.x}px)`,
          top:  `calc(20% + ${s.y}px)`,
          width: 8, height: 8, borderRadius: 999,
          background: s.color,
          '--sx': `${s.sx}px`,
          '--sy': `${s.sy}px`,
          animation: `ab-spark 2.6s ease-out ${s.delay}s infinite`,
          opacity: 0,
          pointerEvents: 'none',
        }} />
      ))}

      {/* shadow ellipse */}
      <div style={{
        position: 'absolute', bottom: 10, left: '50%',
        width: canSize * 0.7, height: 14,
        marginLeft: -(canSize * 0.35),
        background: 'radial-gradient(ellipse at center, rgba(15, 23, 42, 0.35) 0%, rgba(15,23,42,0) 70%)',
        borderRadius: '50%',
        transformOrigin: 'center center',
        animation: animated ? 'ab-can-shadow 2.4s ease-in-out infinite' : 'none',
      }} />

      {/* dancing can — single animation, no drop-in (so it renders at rest if hidden) */}
      <div style={{
        position: 'relative', zIndex: 2,
        animation: animated ? 'ab-can-dance 2.4s ease-in-out infinite' : 'none',
        transformOrigin: 'center bottom', willChange: 'transform',
      }}>
        <img
          src="assets/can-front.png"
          alt="Apple Bank Natural Spring Water can"
          draggable={false}
          style={{
            display: 'block', height: canSize, width: 'auto',
            filter: 'drop-shadow(0 18px 22px rgba(15, 23, 42, 0.22))',
            userSelect: 'none',
          }}
        />
      </div>
    </div>
  );
}

/* ─────────── PHONE FRAME ─────────── *
   Lightweight iPhone bezel with status bar — 390x844 viewport. */

function PhoneFrame({ children, scale = 1, label }) {
  return (
    <div style={{
      width: 390 * scale, height: 844 * scale,
      position: 'relative', transformOrigin: 'top left',
    }}>
      <div style={{
        position: 'absolute', inset: 0, transform: `scale(${scale})`, transformOrigin: 'top left',
        width: 390, height: 844,
        borderRadius: 54, background: '#0F0F10', padding: 8,
        boxShadow: '0 30px 80px -30px rgba(0,0,0,0.35), 0 2px 0 rgba(255,255,255,0.04) inset, 0 -2px 0 rgba(255,255,255,0.04) inset',
      }}>
        <div style={{
          position: 'relative', width: '100%', height: '100%',
          borderRadius: 46, overflow: 'hidden', background: 'var(--ab-cream)',
        }}>
          {/* status bar */}
          <div style={{
            position: 'absolute', top: 0, left: 0, right: 0, height: 48,
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '12px 28px 0', zIndex: 50, pointerEvents: 'none',
            fontFamily: '-apple-system, BlinkMacSystemFont, system-ui', fontSize: 14, fontWeight: 600, color: 'var(--ab-ink)',
          }}>
            <span>9:41</span>
            {/* dynamic island */}
            <div style={{ position: 'absolute', left: '50%', top: 11, transform: 'translateX(-50%)', width: 110, height: 32, background: '#0F0F10', borderRadius: 999 }} />
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
              {/* signal */}
              <svg width="16" height="11" viewBox="0 0 16 11"><g fill="currentColor"><rect x="0" y="7" width="3" height="4" rx="0.5"/><rect x="4" y="5" width="3" height="6" rx="0.5"/><rect x="8" y="3" width="3" height="8" rx="0.5"/><rect x="12" y="0" width="3" height="11" rx="0.5"/></g></svg>
              {/* battery */}
              <svg width="24" height="11" viewBox="0 0 24 11"><rect x="0.5" y="0.5" width="20" height="10" rx="2" fill="none" stroke="currentColor"/><rect x="21" y="3.5" width="2" height="4" rx="0.5" fill="currentColor"/><rect x="2" y="2" width="17" height="7" rx="1" fill="currentColor"/></svg>
            </span>
          </div>
          {/* content area */}
          <div className="ab" style={{ position: 'absolute', inset: 0, paddingTop: 48, overflow: 'hidden' }}>
            {children}
          </div>
        </div>
      </div>
      {label && (
        <div style={{
          position: 'absolute', top: 844 * scale + 14, left: 0, right: 0,
          textAlign: 'center', fontFamily: 'var(--ab-sans)', fontSize: 12, color: 'var(--ab-ink-mute)',
          letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 600,
        }}>{label}</div>
      )}
    </div>
  );
}

/* ─────────── SCREEN SHELL ─────────── *
   Standard padded scrollable column with optional progress + footer. */

function ScreenShell({ step, label, children, footer, bg = 'var(--ab-cream)' }) {
  return (
    <div style={{
      width: '100%', minHeight: '100%', flex: 1, background: bg, display: 'flex', flexDirection: 'column',
    }}>
      {step !== undefined && (
        <div style={{ padding: '12px 24px 8px' }}>
          <ProgressBar step={step} total={8} label={label} />
        </div>
      )}
      <div style={{ flex: 1, overflow: 'visible', padding: '8px 24px 16px', display: 'flex', flexDirection: 'column' }}>
        {children}
      </div>
      {footer && (
        <div style={{
          padding: '12px 24px 28px', background: bg,
          borderTop: '1px solid var(--ab-line-2)',
        }}>
          {footer}
        </div>
      )}
    </div>
  );
}

/* ─────────── EXPORTS ─────────── */
Object.assign(window, {
  AppleIcon, AppleMark, AppleDropHero,
  IconChevron, IconCheck, IconSearch, IconShare, IconPhone, IconMail,
  ProgressBar, Button, Chip, StatCard, GrandPrizeTile, SecondaryPrizeTile, Input,
  NYCStoop, NYCSubwayTile, ConfettiBurst,
  PhoneFrame, ScreenShell,
});
