// Shared components used across all scenes.

// ─────────────────── PALETTE ───────────────────
const FAJR = {
  navy: '#1a2f3f',
  navy900: '#0f1f2b',
  navy800: '#152633',
  navy700: '#22404f',
  gold: '#d4a853',
  goldSoft: '#e6c687',
  goldDim: '#8a6d34',
  ivory: '#f5f1e8',
  paper: '#fafaf7',
  ink: '#14222c',
  muted: '#5b6d78',
  green: '#7fc18a',
  red: '#e85d5d',
  blue: '#5b9bd5',
  orange: '#e8a44d',
  line: 'rgba(212,168,83,.22)',
  lineDark: 'rgba(245,241,232,.08)',
};

// ─────────────────── SCENE BG ───────────────────
// Dark navy background with grid + two glows, reused in every scene.
function SceneBG({ showGrid = true }) {
  return (
    <>
      <div style={{
        position: 'absolute', inset: 0,
        background: `linear-gradient(180deg, ${FAJR.navy900}, ${FAJR.navy})`,
      }} />
      {showGrid && (
        <div style={{
          position: 'absolute', inset: 0,
          backgroundImage: `
            linear-gradient(rgba(212,168,83,.035) 1px, transparent 1px),
            linear-gradient(90deg, rgba(212,168,83,.035) 1px, transparent 1px)`,
          backgroundSize: '48px 48px',
        }} />
      )}
      <div style={{
        position: 'absolute', top: -300, left: -300,
        width: 900, height: 900,
        background: 'radial-gradient(circle, rgba(212,168,83,.09) 0%, transparent 60%)',
        pointerEvents: 'none',
      }} />
      <div style={{
        position: 'absolute', bottom: -200, right: -200,
        width: 700, height: 700,
        background: 'radial-gradient(circle, rgba(127,193,138,.06) 0%, transparent 60%)',
        pointerEvents: 'none',
      }} />
    </>
  );
}

// ─────────────────── SCENE HEADER ───────────────────
// Top-left: slide number + title caption. Animates in.
function SceneHeader({ number, label, title, desc }) {
  const { localTime } = useSprite();
  const fadeIn = Easing.easeOutCubic(clamp(localTime / 0.6, 0, 1));
  const ty = (1 - fadeIn) * 14;

  return (
    <div style={{
      position: 'absolute',
      top: 40, right: 60, left: 60,
      display: 'flex', flexDirection: 'column',
      alignItems: 'center',
      opacity: fadeIn,
      transform: `translateY(${ty}px)`,
      zIndex: 5,
    }}>
      <div style={{
        fontFamily: 'IBM Plex Mono, monospace',
        fontSize: 13, color: FAJR.goldDim,
        letterSpacing: '.2em', direction: 'ltr',
        marginBottom: 14,
      }}>
        {number} — {label}
      </div>
      <h2 style={{
        fontSize: 38, fontWeight: 700, color: FAJR.ivory,
        textAlign: 'center', margin: 0, letterSpacing: '-0.01em',
        lineHeight: 1.2,
      }}>
        {title}
      </h2>
      {desc && (
        <p style={{
          fontSize: 16, fontWeight: 300, color: 'rgba(245,241,232,.7)',
          maxWidth: 620, textAlign: 'center', lineHeight: 1.6,
          marginTop: 10, textWrap: 'pretty',
        }}>
          {desc}
        </p>
      )}
    </div>
  );
}

// ─────────────────── MOUSE CURSOR ───────────────────
// Animates from (x1,y1) to (x2,y2) over [start, moveEnd], then fades at fadeStart.
// Triggers a click ripple + tap sound at moveEnd.
function Cursor({ x1, y1, x2, y2, start = 0, moveEnd = 1, fadeStart = null, clickAt = null }) {
  const { localTime } = useSprite();
  if (localTime < start) return null;

  const moveT = clamp((localTime - start) / (moveEnd - start), 0, 1);
  const eased = Easing.easeInOutCubic(moveT);
  const x = x1 + (x2 - x1) * eased;
  const y = y1 + (y2 - y1) * eased;

  let opacity = 1;
  if (fadeStart != null && localTime >= fadeStart) {
    opacity = clamp(1 - (localTime - fadeStart) / 0.3, 0, 1);
  }

  const actualClickAt = clickAt != null ? clickAt : moveEnd;
  const sinceClick = localTime - actualClickAt;
  const showRipple = sinceClick >= 0 && sinceClick < 0.5;
  const rippleScale = showRipple ? 1 + sinceClick * 3 : 0;
  const rippleOpacity = showRipple ? 1 - (sinceClick / 0.5) : 0;

  // Fire tap sound on click frame (approx)
  const firedRef = React.useRef(false);
  React.useEffect(() => {
    if (sinceClick >= 0 && sinceClick < 0.08 && !firedRef.current) {
      firedRef.current = true;
      if (window.FajrAudio) window.FajrAudio.play('tap');
    }
    if (sinceClick < -0.05) firedRef.current = false;
  }, [sinceClick]);

  return (
    <>
      {showRipple && (
        <div style={{
          position: 'absolute',
          left: x - 20, top: y - 20,
          width: 40, height: 40,
          borderRadius: '50%',
          border: `2px solid ${FAJR.gold}`,
          transform: `scale(${rippleScale})`,
          opacity: rippleOpacity,
          pointerEvents: 'none',
          zIndex: 99,
        }} />
      )}
      <svg width="28" height="28" viewBox="0 0 28 28" style={{
        position: 'absolute',
        left: x, top: y,
        opacity,
        pointerEvents: 'none',
        zIndex: 100,
        filter: 'drop-shadow(0 4px 10px rgba(0,0,0,0.5))',
        transform: 'translate(-4px, -3px)',
      }}>
        <path d="M4 3 L4 22 L10 16 L14 24 L17 22 L13 14 L21 14 Z"
          fill={FAJR.ivory}
          stroke={FAJR.navy900}
          strokeWidth="1.2"
          strokeLinejoin="round" />
      </svg>
    </>
  );
}

// ─────────────────── DEVICE FRAMES ───────────────────

// Phone frame — positioned inside the scene.
function PhoneFrame({ x, y, width = 320, children, entryStart = 0 }) {
  const { localTime } = useSprite();
  const t = clamp((localTime - entryStart) / 0.7, 0, 1);
  const eased = Easing.easeOutBack(t);
  const scale = 0.7 + 0.3 * eased;
  const opacity = t;

  return (
    <div style={{
      position: 'absolute', left: x, top: y, width,
      transform: `scale(${scale})`, transformOrigin: 'center',
      opacity,
      background: `linear-gradient(160deg, ${FAJR.navy700}, ${FAJR.navy800})`,
      border: `1px solid ${FAJR.lineDark}`,
      borderRadius: 32, padding: 16,
      boxShadow: '0 50px 100px -25px rgba(0,0,0,.7), 0 0 0 1px rgba(212,168,83,.1)',
    }}>
      <div style={{
        width: 120, height: 6, borderRadius: 3,
        background: 'rgba(245,241,232,.12)',
        margin: '0 auto 16px',
      }} />
      <div style={{
        background: 'rgba(15,31,43,.7)',
        border: `1px solid ${FAJR.lineDark}`,
        borderRadius: 18, padding: 20,
        minHeight: 380,
      }}>
        {children}
      </div>
    </div>
  );
}

// Desktop frame.
function DesktopFrame({ x, y, width = 780, url = 'fajrone.iq', children, entryStart = 0 }) {
  const { localTime } = useSprite();
  const t = clamp((localTime - entryStart) / 0.7, 0, 1);
  const eased = Easing.easeOutCubic(t);
  const scale = 0.9 + 0.1 * eased;
  const opacity = t;

  return (
    <div style={{
      position: 'absolute', left: x, top: y, width,
      transform: `scale(${scale})`, transformOrigin: 'center',
      opacity,
      background: `linear-gradient(160deg, ${FAJR.navy700}, ${FAJR.navy800})`,
      border: `1px solid ${FAJR.lineDark}`,
      borderRadius: 14, padding: 16,
      boxShadow: '0 50px 100px -25px rgba(0,0,0,.7), 0 0 0 1px rgba(212,168,83,.1)',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8,
        paddingBottom: 12,
        borderBottom: `1px solid ${FAJR.lineDark}`,
        marginBottom: 16,
      }}>
        <span style={{ width: 9, height: 9, borderRadius: '50%', background: 'rgba(232,93,93,.6)' }} />
        <span style={{ width: 9, height: 9, borderRadius: '50%', background: 'rgba(232,164,77,.6)' }} />
        <span style={{ width: 9, height: 9, borderRadius: '50%', background: 'rgba(127,193,138,.6)' }} />
        <div style={{
          flex: 1, textAlign: 'center',
          fontFamily: 'IBM Plex Mono, monospace',
          fontSize: 11, color: 'rgba(245,241,232,.45)',
          direction: 'ltr',
        }}>{url}</div>
      </div>
      <div style={{
        background: 'rgba(15,31,43,.55)',
        border: `1px solid ${FAJR.lineDark}`,
        borderRadius: 10, padding: 20,
        minHeight: 280,
      }}>
        {children}
      </div>
    </div>
  );
}

// ─────────────────── MOCK ELEMENTS ───────────────────

function MockRow({ avatar, name, sub, badge, badgeColor = 'gold', appearAt = 0, children }) {
  const { localTime } = useSprite();
  const t = clamp((localTime - appearAt) / 0.45, 0, 1);
  const eased = Easing.easeOutCubic(t);
  const opacity = t;
  const tx = (1 - eased) * -20;

  // play soft-tick on appearance
  const firedRef = React.useRef(false);
  React.useEffect(() => {
    if (localTime >= appearAt && localTime < appearAt + 0.1 && !firedRef.current) {
      firedRef.current = true;
      if (window.FajrAudio) window.FajrAudio.play('soft-tick');
    }
    if (localTime < appearAt - 0.05) firedRef.current = false;
  }, [localTime, appearAt]);

  const badgeColors = {
    gold: { bg: 'rgba(212,168,83,.15)', color: FAJR.gold },
    green: { bg: 'rgba(127,193,138,.15)', color: FAJR.green },
    blue: { bg: 'rgba(91,155,213,.15)', color: FAJR.blue },
    orange: { bg: 'rgba(232,164,77,.15)', color: FAJR.orange },
    red: { bg: 'rgba(232,93,93,.15)', color: FAJR.red },
  };
  const bc = badgeColors[badgeColor] || badgeColors.gold;

  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '12px 14px', borderRadius: 10,
      background: 'rgba(15,31,43,.5)',
      border: `1px solid ${FAJR.lineDark}`,
      marginBottom: 9,
      opacity, transform: `translateX(${tx}px)`,
      fontSize: 13,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        {avatar && (
          <div style={{
            width: 32, height: 32, borderRadius: '50%',
            background: `linear-gradient(135deg, ${FAJR.gold}, #a67d33)`,
            display: 'grid', placeItems: 'center',
            fontSize: 12, fontWeight: 600, color: FAJR.navy900,
          }}>{avatar}</div>
        )}
        <div>
          <div style={{ color: FAJR.ivory, fontSize: 14 }}>{name}</div>
          {sub && <div style={{ color: 'rgba(245,241,232,.5)', fontSize: 11, marginTop: 2 }}>{sub}</div>}
        </div>
      </div>
      {badge && (
        <span style={{
          padding: '5px 11px', borderRadius: 20,
          fontSize: 11, fontWeight: 500,
          fontFamily: 'IBM Plex Mono, monospace', direction: 'ltr',
          background: bc.bg, color: bc.color,
        }}>{badge}</span>
      )}
      {children}
    </div>
  );
}

function MockHeader({ title, badge, badgeColor }) {
  const badgeColors = {
    gold: { bg: 'rgba(212,168,83,.15)', color: FAJR.gold },
    green: { bg: 'rgba(127,193,138,.15)', color: FAJR.green },
    blue: { bg: 'rgba(91,155,213,.15)', color: FAJR.blue },
    orange: { bg: 'rgba(232,164,77,.15)', color: FAJR.orange },
    red: { bg: 'rgba(232,93,93,.15)', color: FAJR.red },
  };
  const bc = badgeColors[badgeColor] || badgeColors.gold;
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      marginBottom: 16, paddingBottom: 12,
      borderBottom: `1px solid ${FAJR.lineDark}`,
    }}>
      <span style={{ fontSize: 14, fontWeight: 600, color: FAJR.ivory }}>{title}</span>
      {badge && (
        <span style={{
          padding: '5px 11px', borderRadius: 20,
          fontSize: 11, fontWeight: 500,
          fontFamily: 'IBM Plex Mono, monospace', direction: 'ltr',
          background: bc.bg, color: bc.color,
        }}>{badge}</span>
      )}
    </div>
  );
}

// ─────────────────── SCENE TRANSITION OVERLAY ───────────────────
// Gold sweep between scenes.
function SceneTransition({ at, duration = 0.6 }) {
  const { localTime } = useSprite();
  const dt = localTime - at;
  if (dt < 0 || dt > duration) return null;
  const t = dt / duration;

  // Sweep from right to left (RTL direction)
  const x = (1 - t) * 100; // 100% -> 0%

  return (
    <div style={{
      position: 'absolute', inset: 0,
      pointerEvents: 'none', zIndex: 200,
      overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute',
        top: 0, bottom: 0,
        right: `${-30 + x}%`,
        width: '60%',
        background: `linear-gradient(90deg, transparent, ${FAJR.gold} 40%, ${FAJR.goldSoft} 50%, ${FAJR.gold} 60%, transparent)`,
        opacity: 0.85,
        filter: 'blur(1px)',
      }} />
    </div>
  );
}

// Export all to window so other scripts can use
Object.assign(window, {
  FAJR,
  SceneBG, SceneHeader,
  Cursor,
  PhoneFrame, DesktopFrame,
  MockRow, MockHeader,
  SceneTransition,
});
