// scenes.jsx — Yuan Packaging homepage build animation (compact 880×660).
// Sized for a small portfolio-card slot: chips and type are large enough to read.

const BLUE = '#1F4FCE';
const BLUE_LITE = '#4A78E8';
const BLUE_DARK = '#0E2E8A';
const BLUE_BTN = 'linear-gradient(180deg, #4A78E8 0%, #1F4FCE 100%)';
const INK = '#0B1F4A';
const INK_2 = '#3B4A6B';
const INK_3 = '#7A8497';
const PAGE = '#FFFFFF';
const LINE = '#E6E8EE';
const BAND = '#F5F7FB';

// Page stays static — no camera moves. Cleaner read at small sizes.

// ─────────────────────────────────────────────────────────────────
function BrowserChrome({ width, height }) {
  const t = useTime();
  const chromeProg = Easing.easeOutCubic(clamp(t / 0.8, 0, 1));

  return (
    <div style={{
      position: 'absolute',
      left: 0, top: 0,
      width, height,
      background: PAGE,
      opacity: chromeProg,
      transform: `scale(${0.985 + 0.015 * chromeProg})`,
      transformOrigin: 'center',
    }}>
      <div style={{
        height: 34,
        background: '#F0F2F6',
        borderBottom: `1px solid ${LINE}`,
        display: 'flex', alignItems: 'center',
        padding: '0 12px',
        gap: 10,
      }}>
        <div style={{ display: 'flex', gap: 6 }}>
          {['#FF5F57', '#FEBC2E', '#28C840'].map((c, i) => {
            const op = clamp((t - 0.1 - i * 0.06) / 0.3, 0, 1);
            return (
              <div key={i} style={{
                width: 10, height: 10, borderRadius: '50%',
                background: c,
                opacity: op,
                transform: `scale(${0.5 + 0.5 * op})`,
              }}/>
            );
          })}
        </div>
        <div style={{
          marginLeft: 8,
          background: '#fff',
          border: `1px solid ${LINE}`,
          borderRadius: 5,
          padding: '3px 12px',
          fontSize: 11,
          color: INK_3,
          fontFamily: 'ui-monospace, "SF Mono", Menlo, monospace',
          minWidth: 220,
          opacity: clamp((t - 0.4) / 0.5, 0, 1),
        }}>
          {(() => {
            const url = 'yuanpackaging.com';
            const chars = Math.floor(clamp((t - 0.4) / 0.9, 0, 1) * url.length);
            return url.slice(0, chars) + (chars < url.length ? '|' : '');
          })()}
        </div>
      </div>
      <CameraPage width={width} height={height - 34}/>
    </div>
  );
}

function CameraPage({ width, height }) {
  const t = useTime();
  const pageProg = Easing.easeOutCubic(clamp((t - 0.6) / 0.6, 0, 1));

  return (
    <div style={{
      position: 'absolute',
      left: 0, top: 34,
      width: '100%', height: 'calc(100% - 34px)',
      background: PAGE,
      opacity: pageProg,
      overflow: 'hidden',
    }}>
      <div style={{ position: 'absolute', left: 0, right: 0, top: 0, zIndex: 2 }}>
        <NavBar />
      </div>
      <div style={{
        position: 'absolute',
        left: 0, right: 0, top: 52, bottom: 0,
      }}>
        <Hero />
      </div>
      <TrustChips />
      <LoopFade />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
function NavBar() {
  const t = useTime();
  // Compact: trim to 4 links + 中文
  const links = ['Home', 'Products', 'About', 'Contact'];
  const logoOp = Easing.easeOutCubic(clamp((t - 0.9) / 0.4, 0, 1));

  return (
    <div style={{
      height: 52,
      borderBottom: `1px solid ${LINE}`,
      display: 'flex', alignItems: 'center',
      padding: '0 28px',
      justifyContent: 'space-between',
      background: PAGE,
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 9,
        opacity: logoOp,
        transform: `translateX(${(1 - logoOp) * -10}px)`,
      }}>
        <img src="yuan-logo.png" alt="" style={{
          width: 28, height: 28, objectFit: 'contain', display: 'block',
          transform: `rotate(${(1 - logoOp) * -25}deg) scale(${0.6 + 0.4 * logoOp})`,
          transformOrigin: 'center',
        }}/>
        <span style={{
          fontSize: 14, fontWeight: 600, color: INK,
          letterSpacing: '-0.01em',
        }}>Yuan Packaging</span>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 22 }}>
        {links.map((label, i) => {
          const start = 1.0 + i * 0.07;
          const op = Easing.easeOutCubic(clamp((t - start) / 0.3, 0, 1));
          const isHome = label === 'Home';
          return (
            <span key={label} style={{
              fontSize: 13, color: isHome ? INK : INK_2,
              fontWeight: isHome ? 600 : 500,
              opacity: op,
              transform: `translateY(${(1 - op) * -6}px)`,
              borderBottom: isHome ? `1.5px solid ${INK}` : 'none',
              paddingBottom: isHome ? 2 : 0,
            }}>{label}</span>
          );
        })}
        {(() => {
          const op = Easing.easeOutCubic(clamp((t - 1.4) / 0.4, 0, 1));
          return (
            <span style={{
              fontSize: 13, color: INK_2, fontWeight: 500,
              opacity: op,
              transform: `translateY(${(1 - op) * -6}px)`,
            }}>中文</span>
          );
        })()}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
function Hero() {
  const t = useTime();
  // Slide hero left to make room for the chip column when chips appear
  const slideOut = Easing.easeInOutCubic(clamp((t - 4.6) / 0.8, 0, 1));
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: '1.05fr 1fr',
      gap: 20,
      padding: '36px 32px 0',
      alignItems: 'center',
      height: 'calc(100% - 52px)',
      transform: `translateX(${-slideOut * 90}px)`,
      opacity: 1 - slideOut * 0.35,
    }}>
      <HeroCopy />
      <HeroBottle />
    </div>
  );
}

function HeroCopy() {
  const t = useTime();

  const words = [
    { text: 'Premium ',  t: 1.5,  blue: false },
    { text: 'Packaging', t: 1.85, blue: true  },
  ];
  const w3 = { text: 'Solutions', t: 2.25, blue: false };

  const subOp = Easing.easeOutCubic(clamp((t - 2.7) / 0.6, 0, 1));
  const ctaA  = Easing.easeOutBack(clamp((t - 3.1) / 0.6, 0, 1));
  const ctaB  = Easing.easeOutBack(clamp((t - 3.3) / 0.6, 0, 1));

  return (
    <div style={{ paddingLeft: 16 }}>
      <div style={{
        fontFamily: 'Inter, system-ui, sans-serif',
        fontSize: 42, fontWeight: 800,
        lineHeight: 1.05,
        letterSpacing: '-0.02em',
        color: INK,
      }}>
        <div>
          {words.map((w, i) => {
            const op = Easing.easeOutCubic(clamp((t - w.t) / 0.45, 0, 1));
            return (
              <span key={i} style={{
                display: 'inline-block',
                opacity: op,
                transform: `translateY(${(1 - op) * 14}px)`,
                color: w.blue ? BLUE : INK,
              }}>{w.text}</span>
            );
          })}
        </div>
        <div style={{ marginTop: 2 }}>
          {(() => {
            const op = Easing.easeOutCubic(clamp((t - w3.t) / 0.45, 0, 1));
            return (
              <span style={{
                display: 'inline-block',
                opacity: op,
                transform: `translateY(${(1 - op) * 14}px)`,
              }}>{w3.text}</span>
            );
          })()}
        </div>
      </div>

      <div style={{
        marginTop: 16,
        fontSize: 14, lineHeight: 1.5, color: INK_2,
        maxWidth: 320,
        opacity: subOp,
        transform: `translateY(${(1 - subOp) * 8}px)`,
      }}>
        Elevating your products with innovative,
        sustainable packaging solutions.
      </div>

      <div style={{ marginTop: 20, display: 'flex', gap: 10 }}>
        <button style={{
          background: BLUE_BTN,
          color: '#fff',
          border: 'none',
          padding: '10px 18px',
          borderRadius: 5,
          fontSize: 13, fontWeight: 600,
          boxShadow: `0 6px 16px rgba(31,79,206,${0.32 * clamp(ctaA,0,1)})`,
          opacity: clamp(ctaA, 0, 1),
          transform: `translateY(${(1 - clamp(ctaA,0,1)) * 10}px) scale(${0.85 + 0.15 * clamp(ctaA,0,1)})`,
          cursor: 'pointer',
        }}>Explore Products</button>
        <button style={{
          background: 'transparent',
          color: BLUE,
          border: `1.5px solid ${BLUE}`,
          padding: '10px 18px',
          borderRadius: 5,
          fontSize: 13, fontWeight: 600,
          opacity: clamp(ctaB, 0, 1),
          transform: `translateY(${(1 - clamp(ctaB,0,1)) * 10}px) scale(${0.85 + 0.15 * clamp(ctaB,0,1)})`,
          cursor: 'pointer',
        }}>Get a Quote</button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
function HeroBottle() {
  const t = useTime();
  const start = 1.8;
  const prog = Easing.easeOutCubic(clamp((t - start) / 1.2, 0, 1));
  const swayY = Math.sin((t - start) * 0.55) * 5;
  const swayR = Math.sin((t - start) * 0.4) * 0.5;
  const glowBoost = Easing.easeInOutCubic(clamp((t - 5.0) / 1.2, 0, 1));
  const glowOpacity = 0.18 + 0.12 * glowBoost + 0.04 * Math.sin(t * 1.4);

  return (
    <div style={{
      position: 'relative',
      width: '100%', height: '100%',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      opacity: prog,
      transform: `scale(${0.84 + 0.16 * prog}) translateY(${(1 - prog) * 22 + swayY}px) rotate(${swayR}deg)`,
      transformOrigin: '60% 55%',
    }}>
      <div style={{
        position: 'absolute',
        width: 440, height: 440,
        background: `radial-gradient(circle, rgba(31,79,206,${glowOpacity}) 0%, rgba(31,79,206,0) 65%)`,
        borderRadius: '50%',
        filter: 'blur(10px)',
      }}/>
      <div style={{
        position: 'absolute',
        width: 280, height: 280,
        background: `radial-gradient(circle, rgba(74,120,232,${0.18 + glowBoost*0.18}) 0%, rgba(74,120,232,0) 60%)`,
        borderRadius: '50%',
      }}/>
      <img src="yuan-bottle.png" alt="" style={{
        position: 'relative',
        height: '100%',
        maxHeight: 460,
        width: 'auto',
        objectFit: 'contain',
        filter: 'drop-shadow(0 24px 36px rgba(14,46,138,0.32))',
      }}/>
      <Sparkles t={t} active={glowBoost}/>
    </div>
  );
}

function Sparkles({ t, active }) {
  if (active < 0.05) return null;
  const stars = [
    { x: -130, y: -110, phase: 0.0,  size: 7 },
    { x:  100, y: -150, phase: 1.2,  size: 6 },
    { x:  140, y:   30, phase: 2.4,  size: 6 },
    { x: -150, y:   60, phase: 0.7,  size: 5 },
  ];
  return (
    <React.Fragment>
      {stars.map((s, i) => {
        const blink = (Math.sin(t * 2.4 + s.phase) + 1) / 2;
        const op = active * (0.4 + 0.6 * blink);
        return (
          <div key={i} style={{
            position: 'absolute',
            left: '50%', top: '50%',
            width: s.size, height: s.size,
            transform: `translate(${s.x}px, ${s.y}px) rotate(45deg) scale(${0.7 + 0.5 * blink})`,
            opacity: op,
            pointerEvents: 'none',
          }}>
            <div style={{
              position: 'absolute', inset: 0,
              background: '#fff',
              boxShadow: '0 0 8px rgba(255,255,255,0.9), 0 0 16px rgba(122,166,255,0.7)',
              borderRadius: 1,
            }}/>
          </div>
        );
      })}
    </React.Fragment>
  );
}

// ─────────────────────────────────────────────────────────────────
// Trust chips — stacked vertically on the right, easy to scan.
// Bottle slides left to make room; chips enter top→bottom in sequence.
const CHIPS = [
  { label: 'ISO 9001 certified',          icon: 'shield',   t: 5.2 },
  { label: '40 years in operation',       icon: 'building', t: 5.55 },
  { label: 'FDA food-grade materials',    icon: 'check',    t: 5.9 },
  { label: '14-day lead time',            icon: 'clock',    t: 6.25 },
  { label: 'Trade partners · 12 markets', icon: 'globe',    t: 6.6 },
];

function TrustChips() {
  const t = useTime();
  const veilProg = clamp((t - 4.6) / 0.6, 0, 1);
  const exitFade = clamp((t - 9.5) / 0.6, 0, 1);

  return (
    <div style={{
      position: 'absolute', inset: 0,
      pointerEvents: 'none',
      opacity: 1 - exitFade,
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        background: 'rgba(255,255,255,0.55)',
        backdropFilter: 'blur(2px)',
        opacity: veilProg * 0.85,
      }}/>

      {(() => {
        const op = Easing.easeOutCubic(clamp((t - 4.6) / 0.5, 0, 1));
        return (
          <div style={{
            position: 'absolute',
            top: 72, left: 0, right: 0,
            textAlign: 'center',
            opacity: op,
            transform: `translateY(${(1 - op) * -12}px)`,
          }}>
            <div style={{
              display: 'inline-flex',
              alignItems: 'center',
              gap: 8,
              padding: '8px 18px',
              borderRadius: 999,
              background: '#fff',
              border: `1px solid ${LINE}`,
              boxShadow: '0 6px 18px rgba(11,31,74,0.10)',
              fontSize: 13,
              fontWeight: 700,
              color: INK,
              letterSpacing: '0.04em',
              textTransform: 'uppercase',
              whiteSpace: 'nowrap',
            }}>
              <span style={{
                width: 8, height: 8, borderRadius: '50%',
                background: '#22C55E',
                boxShadow: `0 0 0 ${4 + 4 * Math.sin(t*3)}px rgba(34,197,94,${0.18 - 0.12 * Math.sin(t*3)})`,
              }}/>
              Trust signals · for overseas buyers
            </div>
          </div>
        );
      })()}

      {/* Stacked chip column on the right */}
      <div style={{
        position: 'absolute',
        right: 40,
        top: 150,
        display: 'flex',
        flexDirection: 'column',
        gap: 14,
        alignItems: 'flex-end',
      }}>
        {CHIPS.map((chip, i) => (
          <Chip key={chip.label} {...chip} now={t} index={i}/>
        ))}
      </div>
    </div>
  );
}

function Chip({ label, icon, t: tIn, now, index }) {
  const prog = Easing.easeOutBack(clamp((now - tIn) / 0.6, 0, 1));
  const op   = Easing.easeOutCubic(clamp((now - tIn) / 0.4, 0, 1));
  const floatT = Math.max(0, now - tIn - 0.6);
  const float  = Math.sin(floatT * 1.1 + index * 0.7) * 1.5;

  const landAge = now - tIn - 0.4;
  const pulse = landAge >= 0 && landAge < 0.7 ? landAge / 0.7 : -1;

  return (
    <div style={{
      position: 'relative',
      display: 'inline-flex',
      alignItems: 'center',
      gap: 12,
      padding: '13px 20px 13px 15px',
      borderRadius: 999,
      background: '#FFFFFF',
      border: `1px solid ${LINE}`,
      boxShadow: '0 12px 32px rgba(11,31,74,0.14), 0 1px 3px rgba(11,31,74,0.06)',
      opacity: op,
      transform: `translate(${(1 - prog) * 32}px, ${float}px) scale(${0.85 + 0.15 * prog})`,
      transformOrigin: 'right center',
      whiteSpace: 'nowrap',
    }}>
      {pulse >= 0 && (
        <span style={{
          position: 'absolute',
          inset: -2,
          borderRadius: 999,
          border: `2px solid ${BLUE}`,
          opacity: 0.5 * (1 - pulse),
          transform: `scale(${1 + pulse * 0.18})`,
          pointerEvents: 'none',
        }}/>
      )}
      <ChipIcon kind={icon}/>
      <span style={{
        fontSize: 16,
        fontWeight: 700,
        color: INK,
        letterSpacing: '-0.01em',
      }}>{label}</span>
    </div>
  );
}

function ChipIcon({ kind }) {
  const wrap = (svg) => (
    <span style={{
      width: 30, height: 30, borderRadius: 8,
      background: `linear-gradient(135deg, ${BLUE_LITE} 0%, ${BLUE_DARK} 100%)`,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      flexShrink: 0,
      boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.25)',
    }}>{svg}</span>
  );
  const stroke = { stroke: '#fff', strokeWidth: 1.6, fill: 'none', strokeLinecap: 'round', strokeLinejoin: 'round' };

  switch (kind) {
    case 'shield':
      return wrap(<svg width="17" height="17" viewBox="0 0 16 16"><path d="M8 1.5l5 2v4c0 3-2.2 5.5-5 6.5-2.8-1-5-3.5-5-6.5v-4l5-2z" {...stroke}/><path d="M5.5 8l2 2 3-3.5" {...stroke}/></svg>);
    case 'building':
      return wrap(<svg width="17" height="17" viewBox="0 0 16 16"><rect x="3" y="3" width="10" height="11" {...stroke}/><path d="M5.5 6h1M9.5 6h1M5.5 8.5h1M9.5 8.5h1M5.5 11h1M9.5 11h1" {...stroke}/></svg>);
    case 'clock':
      return wrap(<svg width="17" height="17" viewBox="0 0 16 16"><circle cx="8" cy="8" r="5.5" {...stroke}/><path d="M8 5v3l2 1.5" {...stroke}/></svg>);
    case 'check':
      return wrap(<svg width="17" height="17" viewBox="0 0 16 16"><circle cx="8" cy="8" r="5.5" {...stroke}/><path d="M5.5 8l2 2 3-3.5" {...stroke}/></svg>);
    case 'globe':
      return wrap(<svg width="17" height="17" viewBox="0 0 16 16"><circle cx="8" cy="8" r="5.5" {...stroke}/><path d="M2.5 8h11M8 2.5c1.8 2 1.8 9 0 11M8 2.5c-1.8 2-1.8 9 0 11" {...stroke}/></svg>);
    default:
      return wrap(<span/>);
  }
}

// ─────────────────────────────────────────────────────────────────
function LoopFade() {
  const t = useTime();
  const fadeOut = clamp((t - 9.8) / 0.7, 0, 1);
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: '#FFFFFF',
      opacity: fadeOut * 0.95,
      pointerEvents: 'none',
    }}/>
  );
}

function TimestampLabel() {
  const t = useTime();
  React.useEffect(() => {
    const root = document.querySelector('[data-anim-root]');
    if (root) root.setAttribute('data-screen-label', `t=${t.toFixed(1)}s`);
  }, [Math.floor(t)]);
  return null;
}

function YuanScene({ width, height }) {
  return (
    <div data-anim-root style={{ position: 'absolute', inset: 0 }}>
      <div style={{ position: 'absolute', inset: 0, background: BAND }}/>
      <BrowserChrome width={width} height={height}/>
      <TimestampLabel/>
    </div>
  );
}

Object.assign(window, {
  YuanScene, BLUE, BLUE_DARK, INK, INK_2, PAGE, LINE, BAND,
});
