// scenes.jsx — Al Rawdatain brand intro scenes
// Reads CSS variables from :root for themeable colors (tweakable).

const W = 1080;
const H = 1920;

const useVar = (name, fallback) => {
  if (typeof window === 'undefined') return fallback;
  const v = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
  return v || fallback;
};

// ─── Fine-grained hooks ────────────────────────────────────────────────────
const useFrame = () => {
  const [, force] = React.useReducer(x => x + 1, 0);
  React.useEffect(() => {
    let id;
    const tick = () => { force(); id = requestAnimationFrame(tick); };
    id = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(id);
  }, []);
};

// ─── Shared atoms ──────────────────────────────────────────────────────────
function CornerHUD({ time, duration, sceneName, sceneIdx, total }) {
  const mono = 'JetBrains Mono, ui-monospace, monospace';
  const ink = 'var(--ink)';
  const dim = 'var(--dim)';
  const fmt = (t) => {
    const s = Math.floor(t % 60);
    const ms = Math.floor((t * 100) % 100);
    return `00:${String(s).padStart(2, '0')}.${String(ms).padStart(2, '0')}`;
  };
  return (
    <>
      {/* Top-left: timecode */}
      <div style={{
        position: 'absolute', top: 48, left: 48,
        fontFamily: mono, fontSize: 22, color: dim, letterSpacing: '0.08em',
        display: 'flex', gap: 16, alignItems: 'center',
      }}>
        <span style={{ width: 10, height: 10, borderRadius: 5, background: 'var(--accent)', display: 'inline-block' }}/>
        <span>REC</span>
        <span style={{ color: ink, fontVariantNumeric: 'tabular-nums' }}>{fmt(time)}</span>
        <span style={{ color: dim }}>/ {fmt(duration)}</span>
      </div>
      {/* Top-right: scene label */}
      <div style={{
        position: 'absolute', top: 48, right: 48,
        fontFamily: mono, fontSize: 20, color: dim, letterSpacing: '0.1em',
        textTransform: 'uppercase',
        display: 'flex', gap: 10, alignItems: 'center',
      }}>
        <span style={{ color: ink }}>{String(sceneIdx).padStart(2,'0')}</span>
        <span>/</span>
        <span>{String(total).padStart(2,'0')}</span>
        <span style={{ marginLeft: 8 }}>{sceneName}</span>
      </div>
      {/* Bottom-left: brand mark */}
      <div style={{
        position: 'absolute', bottom: 48, left: 48,
        fontFamily: mono, fontSize: 18, color: dim, letterSpacing: '0.14em',
        textTransform: 'uppercase',
      }}>
        AL RAWDATAIN  ·  الروضتين  ·  EST. 1981
      </div>
      {/* Bottom-right: coords */}
      <div style={{
        position: 'absolute', bottom: 48, right: 48,
        fontFamily: mono, fontSize: 18, color: dim, letterSpacing: '0.08em',
        textAlign: 'right',
      }}>
        29.8°N  48.1°E<br/>
        <span style={{ color: 'var(--accent)' }}>N. KUWAIT · AL‑RAWDATAIN FIELD</span>
      </div>
    </>
  );
}

// Animated counter
function Counter({ from = 0, to, progress, suffix = '', decimals = 0, style = {} }) {
  const v = from + (to - from) * Easing.easeOutQuart(clamp(progress, 0, 1));
  const display = decimals > 0 ? v.toFixed(decimals) : Math.floor(v).toLocaleString();
  return (
    <span style={{ fontVariantNumeric: 'tabular-nums', ...style }}>
      {display}{suffix}
    </span>
  );
}

// Striped placeholder
function Placeholder({ label, style = {} }) {
  return (
    <div style={{
      background: 'repeating-linear-gradient(135deg, var(--stripe-a) 0 14px, var(--stripe-b) 14px 28px)',
      color: 'var(--dim)',
      fontFamily: 'JetBrains Mono, monospace',
      fontSize: 14,
      letterSpacing: '0.12em',
      textTransform: 'uppercase',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      border: '1px solid var(--line)',
      ...style,
    }}>
      <span style={{ background: 'var(--bg)', padding: '6px 10px', border: '1px solid var(--line)' }}>
        {label}
      </span>
    </div>
  );
}

// Animated progress line
function Ticker({ progress, style = {} }) {
  return (
    <div style={{
      position: 'relative', height: 2,
      background: 'var(--line)',
      ...style,
    }}>
      <div style={{
        position: 'absolute', left: 0, top: 0, bottom: 0,
        width: `${clamp(progress, 0, 1) * 100}%`,
        background: 'var(--accent)',
      }}/>
    </div>
  );
}

// Real Kuwait map — uses SVG of Kuwait (1134 × 979 viewBox).
// Landmass bbox measured: x [74, 962], y [53, 911]. Bubiyan island extends to ~x=1020.
// We crop with margin to include the whole country + surrounding Gulf context.
const SRC_W = 1134.2744;
const SRC_H = 979.20728;
const KW_MIN_X = 30;
const KW_MIN_Y = 20;
const KW_W = 1000;      // includes Bubiyan + Gulf east
const KW_H = 920;       // full north-to-south

// Al-Raudhatain aquifer in source SVG coords.
// Computed from geography: 29.85°N, 47.73°E, mapped onto bbox [74..962] × [53..911].
const RAUDHATAIN_SRC_X = 620;
const RAUDHATAIN_SRC_Y = 187;

// Translate to fractional (0..1) within the cropped view
const RAUD_FRAC_X = (RAUDHATAIN_SRC_X - KW_MIN_X) / KW_W;
const RAUD_FRAC_Y = (RAUDHATAIN_SRC_Y - KW_MIN_Y) / KW_H;

function KuwaitMap({ progress, revealProgress }) {
  // Scale factor: how much to enlarge the 1134x979 SVG so KW_W maps to 100% width
  const scaleX = SRC_W / KW_W;
  const scaleY = SRC_H / KW_H;
  const imgWidthPct = scaleX * 100;
  const imgHeightPct = scaleY * 100;
  const leftPct = -(KW_MIN_X / KW_W) * 100;
  const topPct = -(KW_MIN_Y / KW_H) * 100;

  return (
    <div style={{
      position: 'absolute', inset: 0,
      overflow: 'hidden',
      opacity: revealProgress,
      background: 'var(--bg-alt)',
      border: '1px solid var(--line)',
    }}>
      {/* Real map image, scaled+positioned to show Kuwait */}
      <img src="assets/kuwait.svg" alt="Kuwait" style={{
        position: 'absolute',
        width: `${imgWidthPct}%`,
        height: `${imgHeightPct}%`,
        left: `${leftPct}%`,
        top: `${topPct}%`,
        // Lightly desaturate & boost contrast so coastline reads cleanly
        filter: 'saturate(0.4) contrast(1.1) brightness(1.0)',
        opacity: 0.85,
      }}/>

      {/* Accent overlay tinting Kuwait landmass */}
      <div style={{
        position: 'absolute', inset: 0,
        background: `color-mix(in oklch, var(--accent) 8%, transparent)`,
        mixBlendMode: 'color',
        pointerEvents: 'none',
        opacity: 0.6,
      }}/>

      {/* Region labels */}
      <div style={{
        position: 'absolute', top: 32, left: 32,
        fontFamily: 'JetBrains Mono, monospace', fontSize: 18,
        color: 'var(--ink)', letterSpacing: '0.22em', fontWeight: 600,
        opacity: revealProgress * 0.75,
        textShadow: '0 0 8px var(--bg)',
      }}>IRAQ</div>
      <div style={{
        position: 'absolute', bottom: 32, left: 32,
        fontFamily: 'JetBrains Mono, monospace', fontSize: 18,
        color: 'var(--ink)', letterSpacing: '0.22em', fontWeight: 600,
        opacity: revealProgress * 0.75,
        textShadow: '0 0 8px var(--bg)',
      }}>SAUDI ARABIA</div>
      <div style={{
        position: 'absolute', top: '55%', right: 20,
        transform: 'translateY(-50%) rotate(90deg)',
        transformOrigin: 'center',
        fontFamily: 'JetBrains Mono, monospace', fontSize: 16,
        color: 'var(--ink)', letterSpacing: '0.3em', fontWeight: 600,
        opacity: revealProgress * 0.7,
        textShadow: '0 0 8px var(--bg)',
        whiteSpace: 'nowrap',
      }}>ARABIAN GULF</div>
      <div style={{
        position: 'absolute', left: '45%', top: '55%',
        transform: 'translate(-50%, -50%)',
        fontFamily: 'Bricolage Grotesque, Georgia, serif', fontSize: 46,
        fontWeight: 500,
        color: 'var(--ink)', letterSpacing: '0.24em',
        opacity: revealProgress * 0.55,
        pointerEvents: 'none',
        textShadow: '0 0 12px var(--bg)',
      }}>KUWAIT</div>

      {/* Compass */}
      <div style={{
        position: 'absolute', top: 28, right: 32,
        opacity: revealProgress * 0.7,
        fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
        color: 'var(--dim)', letterSpacing: '0.14em',
        textAlign: 'center',
      }}>
        <div style={{
          width: 32, height: 32,
          border: '1px solid var(--dim)',
          borderRadius: '50%',
          position: 'relative',
          margin: '0 auto 4px',
          background: 'var(--bg)',
        }}>
          <div style={{
            position: 'absolute', left: '50%', top: 3, width: 2, height: 12,
            background: 'var(--accent)', transform: 'translateX(-50%)',
          }}/>
        </div>
        N
      </div>
    </div>
  );
}

// Fractional coordinates used by Scene01 pin placement
const RAUD_FRAC = { x: RAUD_FRAC_X, y: RAUD_FRAC_Y };

// ───────────────────────────────────────────────────────────────────────────
// SCENE 01 — Origin (0 – 5s)
//   Coordinates → Kuwait map draws → pin drops on Al-Raudhatain field
// ───────────────────────────────────────────────────────────────────────────
function Scene01() {
  const { progress, localTime } = useSprite();

  const latProg = clamp((localTime - 0.2) / 0.9, 0, 1);
  const longProg = clamp((localTime - 0.6) / 0.9, 0, 1);
  const mapStrokeProg = clamp((localTime - 0.2) / 2.0, 0, 1);
  const mapFillProg = clamp((localTime - 0.8) / 1.2, 0, 1);
  const depthProg = clamp((localTime - 1.4) / 1.2, 0, 1);
  const pinProg = clamp((localTime - 1.8) / 0.8, 0, 1);

  const ink = 'var(--ink)';
  const accent = 'var(--accent)';
  const display = 'var(--display-font)';
  const mono = 'JetBrains Mono, monospace';
  const arabic = 'var(--arabic-font)';

  const ringCount = 4;

  // Map block — fits full Kuwait country in viewport
  const MAP_W = 860;
  const MAP_H = 860;
  const mapLeft = (W - MAP_W) / 2;
  const mapTop = 560;

  // Pin position inside map block (fractional, computed from real SVG coords)
  const pinX_frac = RAUD_FRAC.x;
  const pinY_frac = RAUD_FRAC.y;

  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--bg)' }}>
      {/* Grid overlay */}
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: `
          linear-gradient(var(--grid) 1px, transparent 1px),
          linear-gradient(90deg, var(--grid) 1px, transparent 1px)`,
        backgroundSize: '60px 60px',
        opacity: 0.4,
      }}/>

      {/* Kuwait map block */}
      <div style={{
        position: 'absolute', left: mapLeft, top: mapTop,
        width: MAP_W, height: MAP_H,
      }}>
        <KuwaitMap progress={mapStrokeProg} revealProgress={mapFillProg}/>

        {/* Ripples emanating from Al-Raudhatain */}
        {[...Array(ringCount)].map((_, i) => {
          const delay = i * 0.25;
          const p = clamp((localTime - 1.8 - delay) / 2.5, 0, 1);
          const size = 50 + p * 380;
          const op = (1 - p) * 0.55;
          return (
            <div key={i} style={{
              position: 'absolute',
              left: `${pinX_frac * 100}%`,
              top: `${pinY_frac * 100}%`,
              transform: 'translate(-50%, -50%)',
              width: size, height: size,
              border: `1.5px solid ${accent}`,
              borderRadius: '50%',
              opacity: op,
            }}/>
          );
        })}

        {/* Pin */}
        <div style={{
          position: 'absolute',
          left: `${pinX_frac * 100}%`,
          top: `${pinY_frac * 100}%`,
          transform: `translate(-50%, -50%) scale(${Easing.easeOutBack(pinProg)})`,
          width: 26, height: 26,
          background: accent,
          borderRadius: '50%',
          boxShadow: `0 0 0 5px var(--bg), 0 0 0 6px ${accent}`,
          opacity: pinProg,
        }}/>

        {/* Pin callout — line goes up-right to label (toward upper right corner) */}
        <div style={{
          position: 'absolute',
          left: `${pinX_frac * 100}%`,
          top: `${pinY_frac * 100}%`,
          width: 180, height: 1,
          background: accent,
          transformOrigin: 'left',
          transform: `rotate(-42deg) scaleX(${clamp((localTime - 2.2) / 0.5, 0, 1)})`,
          opacity: clamp((localTime - 2.2) / 0.3, 0, 1),
        }}/>
        <div style={{
          position: 'absolute',
          left: `calc(${pinX_frac * 100}% + 140px)`,
          top: `calc(${pinY_frac * 100}% - 160px)`,
          fontFamily: mono, fontSize: 20,
          color: accent,
          letterSpacing: '0.14em', textTransform: 'uppercase',
          opacity: clamp((localTime - 2.5) / 0.4, 0, 1),
          whiteSpace: 'nowrap',
        }}>
          AL-RAUDHATAIN<br/>
          <span style={{ color: 'var(--dim)', fontSize: 15 }}>AQUIFER · N. KUWAIT</span>
        </div>
      </div>

      {/* Coordinate readouts — above the map */}
      <div style={{
        position: 'absolute', left: 90, top: 200,
        fontFamily: mono, color: ink,
      }}>
        <div style={{ fontSize: 20, color: 'var(--dim)', letterSpacing: '0.14em', marginBottom: 6 }}>LAT</div>
        <div style={{ fontSize: 62, fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>
          <Counter from={0} to={29.82} progress={latProg} decimals={2} suffix="° N"/>
        </div>
      </div>
      <div style={{
        position: 'absolute', right: 90, top: 200,
        fontFamily: mono, color: ink, textAlign: 'right',
      }}>
        <div style={{ fontSize: 20, color: 'var(--dim)', letterSpacing: '0.14em', marginBottom: 6 }}>LONG</div>
        <div style={{ fontSize: 62, fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>
          <Counter from={0} to={48.14} progress={longProg} decimals={2} suffix="° E"/>
        </div>
      </div>

      {/* Depth meter — between coords and map */}
      <div style={{
        position: 'absolute', left: 90, right: 90, top: 380,
        opacity: clamp((localTime - 1.3) / 0.5, 0, 1),
      }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
          fontFamily: mono, fontSize: 18, color: 'var(--dim)', letterSpacing: '0.14em',
          marginBottom: 10,
        }}>
          <span>AQUIFER DEPTH</span>
          <span style={{ color: ink, fontSize: 24, fontVariantNumeric: 'tabular-nums' }}>
            <Counter from={0} to={450} progress={depthProg} suffix=" M"/>
          </span>
        </div>
        <Ticker progress={depthProg}/>
      </div>

      {/* Bilingual title */}
      <div style={{
        position: 'absolute', left: 90, right: 90, bottom: 150,
        opacity: clamp((localTime - 2.6) / 0.6, 0, 1),
        transform: `translateY(${(1 - clamp((localTime - 2.6) / 0.6, 0, 1)) * 16}px)`,
      }}>
        <div style={{
          fontFamily: display, fontSize: 64, fontWeight: 500,
          color: ink, lineHeight: 1.0, letterSpacing: '-0.02em',
        }}>
          From the depths<br/>
          of Kuwait's desert.
        </div>
        <div style={{
          fontFamily: arabic, fontSize: 36, color: 'var(--dim)',
          marginTop: 48, direction: 'rtl', textAlign: 'right',
          lineHeight: 1,
        }}>
          من أعماق صحراء الكويت
        </div>
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────────────────
// SCENE 02 — Heritage timeline (5 – 11s)
// ───────────────────────────────────────────────────────────────────────────
function Scene02() {
  const { localTime, duration } = useSprite();
  const ink = 'var(--ink)';
  const accent = 'var(--accent)';
  const display = 'var(--display-font)';
  const mono = 'JetBrains Mono, monospace';
  const arabic = 'var(--arabic-font)';

  const milestones = [
    { year: 1981, t: 0.4, label: 'Incorporated in Sharq,\nKuwait.', ar: 'تأسست' },
    { year: 1986, t: 1.3, label: 'First bottling plant\nopens at source.', ar: 'أول مصنع' },
    { year: 2004, t: 2.2, label: 'International\ncertifications secured.', ar: 'شهادات دولية' },
    { year: 2024, t: 3.1, label: 'Rawdatain mobile app\nlaunches on iOS & Android.', ar: 'التطبيق' },
    { year: 2026, t: 4.0, label: 'Leading bottler in Kuwait.', ar: 'الرائد' },
  ];

  const lineProg = clamp(localTime / 4.2, 0, 1);

  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--bg)' }}>
      {/* Header */}
      <div style={{
        position: 'absolute', left: 90, top: 180,
        opacity: clamp(localTime / 0.4, 0, 1),
      }}>
        <div style={{
          fontFamily: mono, fontSize: 20, letterSpacing: '0.2em',
          color: accent, marginBottom: 18, textTransform: 'uppercase',
        }}>
          —— 45 years of heritage
        </div>
        <div style={{
          fontFamily: display, fontSize: 92, fontWeight: 500,
          color: ink, lineHeight: 1, letterSpacing: '-0.03em',
        }}>
          A history<br/>
          poured daily.
        </div>
        <div style={{
          fontFamily: arabic, fontSize: 36, color: 'var(--dim)',
          marginTop: 80, direction: 'rtl', textAlign: 'left',
          lineHeight: 1,
        }}>
          تاريخ يُسكب يوميًا
        </div>
      </div>

      {/* Vertical timeline */}
      <div style={{
        position: 'absolute', left: 160, top: 760, bottom: 180,
        width: 2,
      }}>
        <div style={{
          position: 'absolute', inset: 0, background: 'var(--line)',
        }}/>
        <div style={{
          position: 'absolute', left: 0, top: 0, width: 2,
          height: `${lineProg * 100}%`,
          background: accent,
        }}/>
      </div>

      {/* Milestones */}
      {milestones.map((m, i) => {
        const appear = clamp((localTime - m.t) / 0.5, 0, 1);
        const yBase = 760 + i * 180;
        return (
          <div key={m.year} style={{
            position: 'absolute',
            left: 90, top: yBase,
            opacity: appear,
            transform: `translateX(${(1 - appear) * 20}px)`,
          }}>
            {/* Dot on line */}
            <div style={{
              position: 'absolute', left: 70, top: 20,
              width: 22, height: 22, marginLeft: -10,
              background: 'var(--bg)',
              border: `2px solid ${accent}`,
              borderRadius: '50%',
            }}>
              <div style={{
                position: 'absolute', inset: 4,
                background: accent, borderRadius: '50%',
                transform: `scale(${appear})`,
              }}/>
            </div>
            {/* Year */}
            <div style={{
              marginLeft: 140,
              display: 'flex', alignItems: 'baseline', gap: 32,
            }}>
              <div style={{
                fontFamily: mono, fontSize: 72, fontWeight: 400,
                color: ink, lineHeight: 1, fontVariantNumeric: 'tabular-nums',
                letterSpacing: '-0.02em',
              }}>
                {m.year}
              </div>
              <div style={{
                fontFamily: display, fontSize: 30, color: 'var(--dim)',
                whiteSpace: 'pre-line', lineHeight: 1.2,
              }}>
                {m.label}
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ───────────────────────────────────────────────────────────────────────────
// SCENE 03 — Stats (11 – 17s)
// ───────────────────────────────────────────────────────────────────────────
function Scene03() {
  const { localTime } = useSprite();
  const ink = 'var(--ink)';
  const accent = 'var(--accent)';
  const display = 'var(--display-font)';
  const mono = 'JetBrains Mono, monospace';
  const arabic = 'var(--arabic-font)';

  const stats = [
    { t: 0.3, value: 45, suffix: '+', label: 'Years bottling', ar: 'سنة من التعبئة', decimals: 0 },
    { t: 0.9, value: 100, suffix: '%', label: 'Recyclable PET', ar: 'قابل لإعادة التدوير', decimals: 0 },
    { t: 1.5, value: 1, suffix: 'st', label: 'In Kuwait', ar: 'الأولى في الكويت', decimals: 0 },
    { t: 2.1, value: 24, suffix: '/7', label: 'Daily bottling', ar: 'يوميًا', decimals: 0 },
  ];

  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--bg-alt)' }}>
      {/* Header */}
      <div style={{
        position: 'absolute', left: 90, top: 220,
        opacity: clamp(localTime / 0.4, 0, 1),
      }}>
        <div style={{
          fontFamily: mono, fontSize: 20, letterSpacing: '0.2em',
          color: accent, marginBottom: 18, textTransform: 'uppercase',
        }}>
          —— by the numbers
        </div>
        <div style={{
          fontFamily: display, fontSize: 88, fontWeight: 500,
          color: ink, lineHeight: 0.95, letterSpacing: '-0.03em',
        }}>
          Light. Balanced.<br/>
          <span style={{ color: accent, fontStyle: 'italic' }}>Pure.</span>
        </div>
        <div style={{
          fontFamily: arabic, fontSize: 36, color: 'var(--dim)',
          marginTop: 80, direction: 'rtl', textAlign: 'left',
          lineHeight: 1,
        }}>
          خفيفة. متوازنة. نقية.
        </div>
      </div>

      {/* Stats grid */}
      <div style={{
        position: 'absolute', left: 90, right: 90, top: 760,
        display: 'grid',
        gridTemplateColumns: '1fr 1fr',
        gap: 0,
      }}>
        {stats.map((s, i) => {
          const prog = clamp((localTime - s.t) / 1.0, 0, 1);
          const appear = clamp((localTime - s.t) / 0.4, 0, 1);
          return (
            <div key={i} style={{
              padding: '44px 20px',
              borderTop: i < 2 ? `1px solid var(--line)` : 'none',
              borderBottom: `1px solid var(--line)`,
              borderRight: i % 2 === 0 ? `1px solid var(--line)` : 'none',
              opacity: appear,
              transform: `translateY(${(1 - appear) * 16}px)`,
            }}>
              <div style={{
                fontFamily: display, fontSize: 180, fontWeight: 400,
                color: ink, lineHeight: 0.9, letterSpacing: '-0.05em',
              }}>
                <Counter from={0} to={s.value} progress={prog} decimals={s.decimals}/>
                <span style={{ color: accent, fontSize: 120 }}>{s.suffix}</span>
              </div>
              <div style={{
                fontFamily: mono, fontSize: 22, color: 'var(--dim)',
                marginTop: 18, letterSpacing: '0.1em', textTransform: 'uppercase',
              }}>
                {s.label}
              </div>
              <div style={{
                fontFamily: arabic, fontSize: 26, color: 'var(--dim)',
                marginTop: 6, direction: 'rtl', textAlign: 'left',
              }}>
                {s.ar}
              </div>
            </div>
          );
        })}
      </div>

      {/* Live ticker */}
      <div style={{
        position: 'absolute', left: 90, right: 90, bottom: 200,
        opacity: clamp((localTime - 2.6) / 0.6, 0, 1),
      }}>
        <div style={{
          fontFamily: mono, fontSize: 18, color: 'var(--dim)',
          letterSpacing: '0.18em', textTransform: 'uppercase',
          display: 'flex', justifyContent: 'space-between',
          borderTop: '1px solid var(--line)', paddingTop: 16,
        }}>
          <span>NSF · KQM · FDA · IAS · CPG</span>
          <span style={{ color: accent }}>↗ LIVE</span>
        </div>
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────────────────
// SCENE 04 — Product range (17 – 24s)
// One hero product per segment, cycles through the range
// ───────────────────────────────────────────────────────────────────────────
function Scene04() {
  const { localTime } = useSprite();
  const ink = 'var(--ink)';
  const accent = 'var(--accent)';
  const display = 'var(--display-font)';
  const mono = 'JetBrains Mono, monospace';
  const arabic = 'var(--arabic-font)';

  // 5 segments × 1.3s each (+ 0.5s lead-in / tail)
  const SEG = 1.3;
  const products = [
    {
      code: '01',
      name: 'Rawdatain 330 mL',
      ar: 'روضتين ٣٣٠ مل',
      size: '330 mL PET · 20-pack',
      hero: 'uploads/rawdatain-330ml.png',
      tone: '#1B3A6B',
    },
    {
      code: '02',
      name: 'Glass Bottle',
      ar: 'زجاجة زجاجية',
      size: '240 mL glass · 24-pack',
      hero: 'uploads/52996.png',
      tone: '#2A5588',
    },
    {
      code: '03',
      name: 'Bared',
      ar: 'بارد',
      size: 'Sparkling citrus soda',
      hero: 'uploads/54475.png',
      tone: '#2F7A4F',
    },
    {
      code: '04',
      name: 'Bloom',
      ar: 'بلوم',
      size: 'Sparkling fruit juice',
      hero: 'uploads/54457.png',
      tone: '#B86A4A',
    },
    {
      code: '05',
      name: 'Flavored Water',
      ar: 'مياه بنكهات',
      size: 'Light & refreshing',
      hero: 'uploads/53000.png',
      tone: '#A89334',
    },
  ];

  // Current segment index based on time
  const idx = Math.max(0, Math.min(products.length - 1, Math.floor((localTime - 0.2) / SEG)));

  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--bg-alt)' }}>
      {/* Header */}
      <div style={{
        position: 'absolute', left: 90, top: 200,
        opacity: clamp(localTime / 0.4, 0, 1),
      }}>
        <div style={{
          fontFamily: mono, fontSize: 20, letterSpacing: '0.2em',
          color: accent, marginBottom: 18, textTransform: 'uppercase',
        }}>
          —— the range
        </div>
        <div style={{
          fontFamily: display, fontSize: 78, fontWeight: 500,
          color: ink, lineHeight: 0.95, letterSpacing: '-0.03em',
        }}>
          One source.<br/>
          Many expressions.
        </div>
      </div>
      <div style={{
        position: 'absolute', left: 90, top: 540,
        opacity: clamp(localTime / 0.4, 0, 1),
        fontFamily: arabic, fontSize: 34, color: 'var(--dim)',
        direction: 'rtl', textAlign: 'left',
        lineHeight: 1,
      }}>
        منبع واحد. تعبيرات عديدة.
      </div>

      {/* Segment progress chips */}
      <div style={{
        position: 'absolute', left: 90, right: 90, top: 620,
        display: 'grid',
        gridTemplateColumns: `repeat(${products.length}, 1fr)`,
        gap: 10,
      }}>
        {products.map((p, i) => {
          const active = i === idx;
          const passed = i < idx;
          const segStart = 0.2 + i * SEG;
          const fillProg = clamp((localTime - segStart) / SEG, 0, 1);
          return (
            <div key={i} style={{
              position: 'relative',
              height: 3,
              background: 'var(--line)',
            }}>
              <div style={{
                position: 'absolute', left: 0, top: 0, bottom: 0,
                width: passed ? '100%' : `${fillProg * 100}%`,
                background: active || passed ? accent : 'transparent',
                transition: 'none',
              }}/>
            </div>
          );
        })}
      </div>

      {/* Hero product stage — single product, cross-fades between segments */}
      <div style={{
        position: 'absolute', left: 0, right: 0, top: 720, bottom: 520,
        overflow: 'hidden',
      }}>
        {products.map((p, i) => {
          const segStart = 0.2 + i * SEG;
          const inProg  = clamp((localTime - segStart) / 0.4, 0, 1);
          const outProg = clamp((localTime - segStart - SEG + 0.25) / 0.25, 0, 1);
          const visible = inProg * (1 - outProg);
          if (visible <= 0) return null;

          return (
            <div key={p.code} style={{
              position: 'absolute', inset: 0,
              opacity: visible,
            }}>
              {/* Big index numeral watermark */}
              <div style={{
                position: 'absolute',
                right: -80, top: -120,
                fontFamily: display,
                fontSize: 720, lineHeight: 0.8,
                color: p.tone,
                opacity: 0.1,
                fontWeight: 600,
                letterSpacing: '-0.05em',
                pointerEvents: 'none',
                whiteSpace: 'nowrap',
              }}>
                {p.code}
              </div>

              {/* Product image */}
              <img src={p.hero} alt={p.name} style={{
                position: 'absolute',
                left: '50%', top: '50%',
                width: '82%',
                height: '82%',
                transform: `translate(-50%, calc(-50% + ${(1 - inProg) * 30 + outProg * -20}px)) scale(${0.94 + inProg * 0.06})`,
                objectFit: 'contain',
                filter: 'drop-shadow(0 24px 48px rgba(0,0,0,0.28))',
              }}/>
            </div>
          );
        })}
      </div>

      {/* Footer: current product meta */}
      <div style={{
        position: 'absolute', left: 90, right: 90, bottom: 160,
        borderTop: '1px solid var(--line)',
        paddingTop: 28,
      }}>
        {products.map((p, i) => {
          const segStart = 0.2 + i * SEG;
          const inProg  = clamp((localTime - segStart) / 0.35, 0, 1);
          const outProg = clamp((localTime - segStart - SEG + 0.2) / 0.2, 0, 1);
          const visible = inProg * (1 - outProg);
          if (visible <= 0) return null;

          return (
            <div key={p.code} style={{
              position: 'absolute', left: 90, right: 90, top: 28,
              opacity: visible,
              transform: `translateY(${(1 - inProg) * 18}px)`,
              display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between',
              gap: 40,
            }}>
              <div>
                <div style={{
                  fontFamily: mono, fontSize: 18, color: accent,
                  letterSpacing: '0.18em', marginBottom: 10,
                }}>
                  {p.code} / {String(products.length).padStart(2, '0')}
                </div>
                <div style={{
                  fontFamily: display, fontSize: 56, color: ink,
                  lineHeight: 1, letterSpacing: '-0.03em', fontWeight: 500,
                }}>
                  {p.name}
                </div>
                <div style={{
                  fontFamily: arabic, fontSize: 28, color: 'var(--dim)',
                  direction: 'rtl', textAlign: 'left', marginTop: 10,
                }}>
                  {p.ar}
                </div>
              </div>
              <div style={{
                fontFamily: mono, fontSize: 18, color: 'var(--dim)',
                letterSpacing: '0.12em', textTransform: 'uppercase',
                textAlign: 'right', whiteSpace: 'nowrap', marginTop: 36,
              }}>
                {p.size}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────────────────
// SCENE 05 — Certifications (23 – 28s)
// ───────────────────────────────────────────────────────────────────────────
function Scene05() {
  const { localTime } = useSprite();
  const ink = 'var(--ink)';
  const accent = 'var(--accent)';
  const display = 'var(--display-font)';
  const mono = 'JetBrains Mono, monospace';
  const arabic = 'var(--arabic-font)';

  const certs = [
    { t: 0.4, name: 'NSF',  full: 'National Sanitation Foundation' },
    { t: 0.7, name: 'FDA',  full: 'U.S. Food & Drug Administration' },
    { t: 1.0, name: 'KQM',  full: 'Kuwait Quality Mark' },
    { t: 1.3, name: 'CPG',  full: 'Current Good Manufacturing Practices' },
    { t: 1.6, name: 'IAS',  full: 'International Accreditation Service' },
  ];

  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--bg)' }}>
      <div style={{
        position: 'absolute', left: 90, top: 260,
        opacity: clamp(localTime / 0.4, 0, 1),
      }}>
        <div style={{
          fontFamily: mono, fontSize: 20, letterSpacing: '0.2em',
          color: accent, marginBottom: 18, textTransform: 'uppercase',
        }}>
          —— verified
        </div>
        <div style={{
          fontFamily: display, fontSize: 92, fontWeight: 500,
          color: ink, lineHeight: 0.95, letterSpacing: '-0.03em',
        }}>
          Purity, audited<br/>
          at every step.
        </div>
        <div style={{
          fontFamily: arabic, fontSize: 40, color: 'var(--dim)',
          marginTop: 56, direction: 'rtl', textAlign: 'left',
        }}>
          نقاء مُدقق في كل خطوة
        </div>
      </div>

      {/* Cert stack */}
      <div style={{
        position: 'absolute', left: 90, right: 90, top: 800,
      }}>
        {certs.map((c, i) => {
          const appear = clamp((localTime - c.t) / 0.4, 0, 1);
          return (
            <div key={c.name} style={{
              display: 'flex', alignItems: 'center', gap: 32,
              padding: '28px 0',
              borderBottom: `1px solid var(--line)`,
              opacity: appear,
            }}>
              {/* check box */}
              <div style={{
                width: 46, height: 46,
                border: `2px solid ${accent}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                transform: `scale(${Easing.easeOutBack(appear)})`,
              }}>
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                  <path d="M4 12l5 5L20 6" stroke="currentColor" strokeWidth="2.5"
                        strokeLinecap="round" strokeLinejoin="round"
                        style={{ color: accent,
                          strokeDasharray: 30,
                          strokeDashoffset: 30 * (1 - appear),
                        }}/>
                </svg>
              </div>
              <div style={{
                fontFamily: mono, fontSize: 56, color: ink,
                letterSpacing: '0.02em', width: 180,
              }}>
                {c.name}
              </div>
              <div style={{
                flex: 1,
                fontFamily: display, fontSize: 30, color: 'var(--dim)',
                fontWeight: 400,
              }}>
                {c.full}
              </div>
              <div style={{
                fontFamily: mono, fontSize: 18, color: accent,
                letterSpacing: '0.14em',
              }}>
                ✓ ACTIVE
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────────────────
// SCENE 06 — Logo / outro (28 – 33s)
// ───────────────────────────────────────────────────────────────────────────
function Scene06() {
  const { localTime } = useSprite();
  const ink = 'var(--ink)';
  const accent = 'var(--accent)';
  const display = 'var(--display-font)';
  const mono = 'JetBrains Mono, monospace';
  const arabic = 'var(--arabic-font)';

  const wordmarkProg = clamp(localTime / 1.2, 0, 1);
  const tagProg = clamp((localTime - 1.4) / 0.6, 0, 1);
  const ctaProg = clamp((localTime - 2.4) / 0.5, 0, 1);

  // Floating water droplet SVG (simple circle is allowed per rules)
  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--signoff-bg, var(--ink))' }}>
      {/* Radial accent glow */}
      <div style={{
        position: 'absolute', left: '50%', top: '50%',
        transform: 'translate(-50%, -50%)',
        width: 1200, height: 1200,
        background: `radial-gradient(circle, color-mix(in oklch, var(--accent) 25%, transparent) 0%, transparent 60%)`,
        opacity: clamp(localTime / 1, 0, 1) * 0.8,
      }}/>

      {/* Official logo (contains both English wordmark + Arabic) */}
      <div style={{
        position: 'absolute', left: 0, right: 0, top: 700,
        display: 'flex', justifyContent: 'center',
        opacity: wordmarkProg,
        transform: `translateY(${(1 - wordmarkProg) * 24}px) scale(${0.95 + wordmarkProg * 0.05})`,
      }}>
        <img src="uploads/rawlogo.png" alt="Al Rawdatain" style={{
          width: 780,
          height: 'auto',
          filter: 'var(--logo-filter, brightness(0) invert(1))',
        }}/>
      </div>

      {/* Tagline */}
      <div style={{
        position: 'absolute', left: 0, right: 0, top: 1200,
        textAlign: 'center',
        opacity: tagProg,
        transform: `translateY(${(1 - tagProg) * 12}px)`,
      }}>
        <div style={{
          fontFamily: display, fontSize: 44, color: '#f0efe9',
          fontStyle: 'italic', fontWeight: 400,
          letterSpacing: '-0.01em',
        }}>
          Heritage, bottled daily.
        </div>
        <div style={{
          fontFamily: arabic, fontSize: 32, color: 'rgba(240,239,233,0.65)',
          marginTop: 12, direction: 'rtl',
        }}>
          تراث يُعبأ يوميًا
        </div>
      </div>

      {/* CTA line */}
      <div style={{
        position: 'absolute', left: 90, right: 90, bottom: 320,
        opacity: ctaProg,
        display: 'flex', justifyContent: 'space-between',
        fontFamily: mono, fontSize: 22, color: 'rgba(240,239,233,0.7)',
        letterSpacing: '0.14em', textTransform: 'uppercase',
        borderTop: '1px solid rgba(240,239,233,0.15)',
        borderBottom: '1px solid rgba(240,239,233,0.15)',
        padding: '22px 0',
      }}>
        <span>alrawdatain.com</span>
        <span>+965 1881234</span>
      </div>

      {/* Bottom small text override */}
      <div style={{
        position: 'absolute', bottom: 160, left: 0, right: 0,
        textAlign: 'center',
        fontFamily: mono, fontSize: 16, color: 'rgba(240,239,233,0.55)',
        letterSpacing: '0.2em', textTransform: 'uppercase',
        opacity: ctaProg,
      }}>
        Sharq · Kuwait · Since 1981
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────────────────
// Root composition
// ───────────────────────────────────────────────────────────────────────────
const SCENES = [
  { name: 'ORIGIN',         start: 0,  end: 5,  Component: Scene01 },
  { name: 'HERITAGE',       start: 5,  end: 11, Component: Scene02 },
  { name: 'STATS',          start: 11, end: 17, Component: Scene03 },
  { name: 'PRODUCTS',       start: 17, end: 24, Component: Scene04 },
  { name: 'CERTIFICATIONS', start: 24, end: 29, Component: Scene05 },
  { name: 'SIGNOFF',        start: 29, end: 35, Component: Scene06 },
];

const TOTAL = SCENES[SCENES.length - 1].end;

function Composition() {
  const { time } = useTimeline();
  const activeIdx = SCENES.findIndex(s => time >= s.start && time < s.end);
  const idx = activeIdx === -1 ? SCENES.length - 1 : activeIdx;
  const active = SCENES[idx];

  return (
    <>
      {SCENES.map((s, i) => (
        <Sprite key={s.name} start={s.start} end={s.end}>
          <s.Component/>
        </Sprite>
      ))}

      {/* Global HUD */}
      <CornerHUD
        time={time}
        duration={TOTAL}
        sceneName={active.name}
        sceneIdx={idx + 1}
        total={SCENES.length}
      />

      {/* Safe-area guides (toggleable later if desired) */}
    </>
  );
}

Object.assign(window, { Composition, TOTAL });
