// video-helpers.jsx — primitives for the Ejen demo film
// Phone frame, chat bubbles, typing dots, animated cursor, shimmer skeletons,
// channel glyphs, etc. All scaled for a 1920×1080 stage.

const COL = {
  signal:  '#c4ff45',
  signalSoft: 'rgba(196,255,69,0.16)',
  signalRing: 'rgba(196,255,69,0.40)',
  void:    '#070707',
  panel:   '#0b0d0f',
  panelEl: '#131517',
  ash:     '#25282e',
  silver:  '#b6bbc2',
  optic:   '#f8f7f2',
  charcoal:'#111316',
  whatsapp:'#25D366',
  igPink:  '#E1306C',
  border:  'rgba(255,255,255,0.08)',
  borderStrong: 'rgba(255,255,255,0.13)',
  gradHero: 'linear-gradient(180deg, rgba(196,255,69,0.10), transparent 60%)',
};

const FONT = {
  sans: 'Inter, ui-sans-serif, system-ui, sans-serif',
  ar:   '"IBM Plex Sans Arabic", Inter, system-ui, sans-serif',
  mono: '"Geist Mono", ui-monospace, monospace',
};

// ─── Tiny utilities ─────────────────────────────────────────────────────────

const lerp = (a, b, t) => a + (b - a) * t;
const ease = (k) => Easing.easeOutCubic(clamp(k, 0, 1));

// fade in/out helper: returns 0..1 across [start, in, out, end] within local time t
function fadeWindow(t, fadeIn = 0, holdStart = 0.4, holdEnd = Infinity, fadeOut = 0.4) {
  if (t < fadeIn) return ease(t / Math.max(0.001, fadeIn - 0));
  // simpler: pass [in, out] markers as actual times
  return 1;
}

// fade(t, inStart, inEnd, outStart, outEnd) → opacity
function fade(t, inStart, inEnd, outStart = Infinity, outEnd = Infinity) {
  let o = 1;
  if (t < inStart) return 0;
  if (t < inEnd)   o = ease((t - inStart) / Math.max(0.001, inEnd - inStart));
  if (t > outEnd)  return 0;
  if (t > outStart) o = Math.min(o, 1 - ease((t - outStart) / Math.max(0.001, outEnd - outStart)));
  return o;
}

// ─── Logo (mark + wordmark) ─────────────────────────────────────────────────

function LogoMark({ size = 80, glow = false }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" style={{
      filter: glow ? `drop-shadow(0 0 24px ${COL.signalRing})` : 'none',
    }}>
      <rect x="2" y="2" width="28" height="28" rx="8" fill={COL.signal}/>
      <path d="M10 9.5h12M10 15.5h8M10 21.5h12" stroke={COL.void} strokeWidth="2.4" strokeLinecap="round"/>
      <circle cx="22" cy="15.5" r="1.6" fill={COL.void}/>
    </svg>
  );
}

function LogoWordmark({ size = 32, color = COL.optic }) {
  return (
    <span style={{
      fontFamily: FONT.sans,
      fontWeight: 600,
      fontSize: size,
      letterSpacing: '-0.025em',
      color,
    }}>
      Ejen <span style={{ color: COL.silver, fontWeight: 400 }}>Studio</span>
    </span>
  );
}

// ─── Phone frame (for chat scene) ───────────────────────────────────────────

function Phone({ x, y, width = 380, height = 760, scale = 1, opacity = 1, ty = 0, children }) {
  return (
    <div style={{
      position: 'absolute',
      left: x, top: y,
      width, height,
      transform: `translateY(${ty}px) scale(${scale})`,
      transformOrigin: 'center top',
      opacity,
      borderRadius: 48,
      background: '#000',
      border: `1.5px solid ${COL.borderStrong}`,
      boxShadow: '0 50px 120px -30px rgba(0,0,0,0.9), 0 0 0 8px #181a1d',
      overflow: 'hidden',
      willChange: 'transform, opacity',
    }}>
      {/* notch */}
      <div style={{
        position: 'absolute', top: 14, left: '50%', transform: 'translateX(-50%)',
        width: 110, height: 28, background: '#000', borderRadius: 14, zIndex: 2,
      }}/>
      <div style={{
        width: '100%', height: '100%',
        background: COL.panel,
        display: 'flex', flexDirection: 'column',
      }}>
        {children}
      </div>
    </div>
  );
}

// WhatsApp-styled header for the chat
function WhatsAppHeader() {
  return (
    <div style={{
      flexShrink: 0,
      paddingTop: 56, paddingBottom: 12, paddingLeft: 18, paddingRight: 18,
      background: '#0a3d31',
      display: 'flex', alignItems: 'center', gap: 12,
      borderBottom: '1px solid rgba(255,255,255,0.06)',
    }}>
      <div style={{
        width: 38, height: 38, borderRadius: 12,
        background: COL.signal,
        display: 'grid', placeItems: 'center',
      }}>
        <svg width="22" height="22" viewBox="0 0 32 32"><path d="M10 9.5h12M10 15.5h8M10 21.5h12" stroke={COL.void} strokeWidth="2.6" strokeLinecap="round"/><circle cx="22" cy="15.5" r="1.6" fill={COL.void}/></svg>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: FONT.sans, fontSize: 15, fontWeight: 600, color: COL.optic, letterSpacing: '-0.01em' }}>Ejen · your agent</div>
        <div style={{ fontFamily: FONT.sans, fontSize: 11, color: 'rgba(246,247,242,0.7)', display: 'flex', alignItems: 'center', gap: 6, marginTop: 2 }}>
          <span style={{ width: 6, height: 6, borderRadius: 3, background: COL.signal }}/>
          online · replies in seconds
        </div>
      </div>
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.7)" strokeWidth="1.6"><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-6A19.79 19.79 0 0 1 2.12 4.18 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 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.33 1.85.57 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
    </div>
  );
}

// chat scroll area background
function ChatBackground({ children }) {
  return (
    <div style={{
      flex: 1, minHeight: 0,
      overflow: 'hidden',
      padding: '14px 14px 18px',
      background: '#0d1411',
      backgroundImage:
        'radial-gradient(circle at 20% 20%, rgba(255,255,255,0.025) 1px, transparent 1px),' +
        'radial-gradient(circle at 70% 60%, rgba(255,255,255,0.02) 1px, transparent 1px)',
      backgroundSize: '24px 24px',
      display: 'flex', flexDirection: 'column', gap: 8,
      justifyContent: 'flex-end',
    }}>
      {children}
    </div>
  );
}

// chat composer at bottom
function ChatComposer({ value = '', dir = 'rtl', placeholder = 'اكتب رسالة…', cursor = false }) {
  return (
    <div style={{
      flexShrink: 0,
      padding: '8px 10px 14px',
      background: '#0a3d31',
      display: 'flex', alignItems: 'center', gap: 8,
    }}>
      <div style={{
        flex: 1,
        minHeight: 38,
        background: '#152921',
        borderRadius: 19,
        padding: '8px 14px',
        fontFamily: dir === 'rtl' ? FONT.ar : FONT.sans,
        fontSize: 14,
        color: value ? COL.optic : 'rgba(246,247,242,0.45)',
        direction: dir,
        textAlign: dir === 'rtl' ? 'right' : 'left',
        display: 'flex', alignItems: 'center',
      }}>
        {value || placeholder}
        {cursor && (
          <span style={{
            display: 'inline-block', width: 1.5, height: 16,
            background: COL.signal, marginLeft: 2, marginRight: 2,
            animation: 'blink 1s steps(2) infinite',
          }}/>
        )}
      </div>
      <div style={{
        width: 38, height: 38, borderRadius: 19, background: COL.signal,
        display: 'grid', placeItems: 'center',
      }}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={COL.void} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>
      </div>
    </div>
  );
}

// ─── Chat bubbles ───────────────────────────────────────────────────────────

function Bubble({ side = 'left', children, opacity = 1, ty = 0, dir = 'ltr', maxWidth = '78%', tone = 'normal' }) {
  const isMe = side === 'right';
  const palette = isMe
    ? { bg: '#1f3a2e', color: COL.optic, border: 'transparent' }
    : tone === 'agent'
      ? { bg: COL.signalSoft, color: COL.optic, border: 'rgba(196,255,69,0.30)' }
      : { bg: '#1a2622', color: COL.optic, border: 'transparent' };

  return (
    <div style={{
      alignSelf: isMe ? 'flex-end' : 'flex-start',
      maxWidth,
      transform: `translateY(${ty}px)`,
      opacity,
      willChange: 'transform, opacity',
    }}>
      <div style={{
        background: palette.bg,
        color: palette.color,
        padding: '8px 12px',
        borderRadius: 14,
        borderBottomRightRadius: isMe ? 4 : 14,
        borderBottomLeftRadius:  isMe ? 14 : 4,
        border: `1px solid ${palette.border}`,
        fontFamily: dir === 'rtl' ? FONT.ar : FONT.sans,
        fontSize: 14,
        lineHeight: 1.45,
        direction: dir,
        textAlign: dir === 'rtl' ? 'right' : 'left',
        boxShadow: '0 1px 1px rgba(0,0,0,0.35)',
      }}>
        {children}
      </div>
    </div>
  );
}

// 3 bouncing dots
function TypingDots({ opacity = 1, ty = 0 }) {
  const t = useTime();
  const phase = (t * 1000) % 900;
  const d = (i) => {
    const p = (phase + i * 220) % 900 / 900;
    const k = Math.sin(p * Math.PI * 2);
    return Math.max(0, k) * 4;
  };
  return (
    <div style={{
      alignSelf: 'flex-start',
      transform: `translateY(${ty}px)`,
      opacity,
    }}>
      <div style={{
        background: '#1a2622', padding: '10px 14px', borderRadius: 14, borderBottomLeftRadius: 4,
        display: 'inline-flex', alignItems: 'center', gap: 5,
      }}>
        {[0,1,2].map(i => (
          <span key={i} style={{
            display: 'block', width: 7, height: 7, borderRadius: 4,
            background: 'rgba(255,255,255,0.55)',
            transform: `translateY(${-d(i)}px)`,
          }}/>
        ))}
      </div>
    </div>
  );
}

// ─── Animated cursor ────────────────────────────────────────────────────────

function Cursor({ x, y, opacity = 1, label = null, clicking = false }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y, opacity,
      pointerEvents: 'none', willChange: 'transform, opacity',
      zIndex: 50,
    }}>
      {clicking && (
        <span style={{
          position: 'absolute', left: -10, top: -10,
          width: 30, height: 30, borderRadius: 15,
          background: 'rgba(196,255,69,0.30)',
          animation: 'cursor-ping 0.6s ease-out',
        }}/>
      )}
      <svg width="22" height="22" viewBox="0 0 24 24" style={{ filter: 'drop-shadow(0 2px 4px rgba(0,0,0,0.5))' }}>
        <path d="M5 3 L5 18 L9 14 L11.5 19 L14 18 L11.5 13 L17 13 Z"
              fill={COL.optic} stroke={COL.void} strokeWidth="1" strokeLinejoin="round"/>
      </svg>
      {label && (
        <span style={{
          position: 'absolute', left: 22, top: 18,
          background: COL.void, color: COL.signal,
          fontFamily: FONT.mono, fontSize: 10,
          padding: '3px 6px', borderRadius: 4,
          whiteSpace: 'nowrap',
          border: `1px solid ${COL.borderStrong}`,
        }}>{label}</span>
      )}
    </div>
  );
}

// ─── Channel glyphs ─────────────────────────────────────────────────────────

function ChannelGlyph({ ch, size = 28 }) {
  const wrap = (bg, svg) => (
    <span style={{
      display: 'inline-grid', placeItems: 'center',
      width: size, height: size, borderRadius: size * 0.32,
      background: bg, flexShrink: 0,
    }}>{svg}</span>
  );
  if (ch === 'whatsapp') return wrap(COL.whatsapp,
    <svg width={size*0.6} height={size*0.6} viewBox="0 0 24 24" fill="#fff"><path d="M19.05 4.91A9.81 9.81 0 0 0 12.05 2C6.58 2 2.13 6.45 2.13 11.92a9.86 9.86 0 0 0 1.32 4.96L2 22l5.25-1.38a9.92 9.92 0 0 0 4.79 1.22h.01c5.46 0 9.91-4.45 9.91-9.92a9.85 9.85 0 0 0-2.91-7.01z"/></svg>
  );
  if (ch === 'instagram') return wrap('linear-gradient(45deg,#f09433,#dc2743,#bc1888)',
    <svg width={size*0.6} height={size*0.6} viewBox="0 0 24 24" fill="#fff"><path d="M12 2.16c3.2 0 3.58.01 4.85.07 1.17.05 1.8.25 2.23.41.56.22.96.48 1.38.9.42.42.68.82.9 1.38.16.42.36 1.06.41 2.23.06 1.27.07 1.65.07 4.85s-.01 3.58-.07 4.85c-.05 1.17-.25 1.8-.41 2.23-.22.56-.48.96-.9 1.38-.42.42-.82.68-1.38.9-.42.16-1.06.36-2.23.41-1.27.06-1.65.07-4.85.07s-3.58-.01-4.85-.07c-1.17-.05-1.8-.25-2.23-.41a3.71 3.71 0 0 1-1.38-.9 3.71 3.71 0 0 1-.9-1.38c-.16-.42-.36-1.06-.41-2.23C2.17 15.58 2.16 15.2 2.16 12s.01-3.58.07-4.85c.05-1.17.25-1.8.41-2.23.22-.56.48-.96.9-1.38.42-.42.82-.68 1.38-.9.42-.16 1.06-.36 2.23-.41C8.42 2.17 8.8 2.16 12 2.16zM12 7.84a4.16 4.16 0 1 0 0 8.32 4.16 4.16 0 0 0 0-8.32z"/></svg>
  );
  if (ch === 'tiktok') return wrap('#000',
    <svg width={size*0.55} height={size*0.55} viewBox="0 0 24 24" fill="#fff"><path d="M19.59 6.69a4.83 4.83 0 0 1-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 0 1-5.2 1.74 2.89 2.89 0 0 1 2.31-4.64 2.93 2.93 0 0 1 .88.13V9.4a6.84 6.84 0 0 0-1-.05A6.33 6.33 0 0 0 5.8 20.1a6.34 6.34 0 0 0 10.86-4.43V8.45a8.16 8.16 0 0 0 4.77 1.52v-3.4a4.85 4.85 0 0 1-1.84-.88z"/></svg>
  );
  if (ch === 'x') return wrap('#000',
    <svg width={size*0.5} height={size*0.5} viewBox="0 0 24 24" fill="#fff"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231z"/></svg>
  );
  return null;
}

// ─── Skeleton/shimmer ───────────────────────────────────────────────────────

function Shimmer({ width = '100%', height = 14, radius = 4 }) {
  return (
    <div style={{
      width, height, borderRadius: radius,
      background:
        'linear-gradient(90deg, rgba(255,255,255,0.04) 0%, rgba(255,255,255,0.10) 30%, rgba(196,255,69,0.18) 50%, rgba(255,255,255,0.10) 70%, rgba(255,255,255,0.04) 100%)',
      backgroundSize: '300% 100%',
      animation: 'shimmer 1.6s linear infinite',
    }}/>
  );
}

// ─── Tags / pills ───────────────────────────────────────────────────────────

function Pill({ children, color = COL.signal, bg = COL.signalSoft, border = 'rgba(196,255,69,0.30)', dir }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '5px 10px',
      borderRadius: 999,
      background: bg, color,
      border: `1px solid ${border}`,
      fontFamily: dir === 'rtl' ? FONT.ar : FONT.sans,
      fontSize: 12, fontWeight: 500, letterSpacing: '0.02em',
      whiteSpace: 'nowrap',
    }}>{children}</span>
  );
}

// ─── App chrome (sidebar+topbar minified for studio scene) ──────────────────

function AppFrame({ active = 'studio', children, opacity = 1, scale = 1 }) {
  const NAV = [
    { id: 'home', label: 'Home', icon: 'home' },
    { id: 'agents', label: 'Agents', icon: 'sparkle' },
    { id: 'inbox', label: 'Inbox', icon: 'inbox' },
    { id: 'calendar', label: 'Calendar', icon: 'cal' },
    { id: 'studio', label: 'Studio', icon: 'wand' },
    { id: 'library', label: 'Library', icon: 'lib' },
  ];
  const ICON = {
    home: <path d="M3 11l9-7 9 7v9a2 2 0 0 1-2 2h-4v-7H9v7H5a2 2 0 0 1-2-2v-9z"/>,
    sparkle: <path d="M12 2v4M12 18v4M2 12h4M18 12h4M5 5l3 3M16 16l3 3M5 19l3-3M16 8l3-3"/>,
    inbox: <path d="M22 12h-6l-2 3h-4l-2-3H2M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/>,
    cal: <><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></>,
    wand: <><path d="M15 4 V2 M15 16 V14 M8 9h-2 M22 9h-2 M17.8 11.8 19 13 M15 9h0 M17.8 6.2 19 5"/><path d="M3 21l9-9"/><path d="M12.2 9.8 14 8"/></>,
    lib: <><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/></>,
  };
  return (
    <div style={{
      position: 'absolute', inset: 0, opacity,
      transform: `scale(${scale})`, transformOrigin: 'center',
      display: 'flex', flexDirection: 'row',
      background: COL.void,
      willChange: 'transform, opacity',
    }}>
      {/* sidebar */}
      <aside style={{
        width: 224, padding: 20, flexShrink: 0,
        background: '#08090b', borderRight: `1px solid ${COL.border}`,
        display: 'flex', flexDirection: 'column', gap: 4,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 24 }}>
          <LogoMark size={28} />
          <span style={{ fontFamily: FONT.sans, fontSize: 14, fontWeight: 600, color: COL.optic, letterSpacing: '-0.02em' }}>Ejen</span>
        </div>
        {NAV.map(n => (
          <div key={n.id} style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '8px 10px', borderRadius: 8,
            background: active === n.id ? 'rgba(196,255,69,0.10)' : 'transparent',
            color: active === n.id ? COL.signal : COL.silver,
            fontFamily: FONT.sans, fontSize: 13, fontWeight: active === n.id ? 600 : 400,
            borderLeft: active === n.id ? `2px solid ${COL.signal}` : '2px solid transparent',
            paddingLeft: 8,
          }}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">{ICON[n.icon]}</svg>
            {n.label}
          </div>
        ))}
      </aside>
      {/* main */}
      <main style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
        <header style={{
          height: 56, flexShrink: 0,
          display: 'flex', alignItems: 'center', padding: '0 24px',
          borderBottom: `1px solid ${COL.border}`,
          background: 'rgba(7,7,7,0.7)',
          backdropFilter: 'blur(10px)',
          gap: 16,
        }}>
          <span style={{ fontFamily: FONT.sans, fontSize: 14, fontWeight: 600, color: COL.optic, letterSpacing: '-0.01em', textTransform: 'capitalize' }}>{active}</span>
          <span style={{ flex: 1 }}/>
          <Pill color={COL.silver} bg="rgba(255,255,255,0.04)" border={COL.border}>
            <span style={{ width: 6, height: 6, borderRadius: 3, background: COL.signal }}/>
            agent on
          </Pill>
        </header>
        <div style={{ flex: 1, padding: 32, overflow: 'hidden', position: 'relative' }}>{children}</div>
      </main>
    </div>
  );
}

// ─── Global animation styles ────────────────────────────────────────────────

function GlobalStyles() {
  React.useEffect(() => {
    if (document.getElementById('vid-globals')) return;
    const style = document.createElement('style');
    style.id = 'vid-globals';
    style.textContent = `
      @keyframes blink { 50% { opacity: 0; } }
      @keyframes shimmer { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }
      @keyframes cursor-ping { 0% { transform: scale(0.4); opacity: 0.7; } 100% { transform: scale(2.4); opacity: 0; } }
      @keyframes pulse-ring { 0%, 100% { box-shadow: 0 0 0 0 rgba(196,255,69,0.55); } 50% { box-shadow: 0 0 0 12px rgba(196,255,69,0); } }
    `;
    document.head.appendChild(style);
  }, []);
  return null;
}

Object.assign(window, {
  COL, FONT, lerp, ease, fade,
  LogoMark, LogoWordmark,
  Phone, WhatsAppHeader, ChatBackground, ChatComposer,
  Bubble, TypingDots, Cursor,
  ChannelGlyph, Shimmer, Pill,
  AppFrame, GlobalStyles,
});
