// koryo-ui.jsx
// Shared building blocks for the Koryo demo: brand chrome, app shell,
// sidebar, cross-pattern bg, cursor overlay, captions, messaging-app mock.

// ── Brand tokens ────────────────────────────────────────────────────────────
const KORYO = {
  bg: '#f4f3fb',
  bgCard: '#ffffff',
  ink: '#0e0e1a',
  inkSoft: 'oklch(55% 0.04 280)',
  inkMute: 'oklch(70% 0.03 280)',
  border: 'oklch(90% 0.02 280)',
  borderSoft: 'oklch(94% 0.015 280)',
  indigo: 'oklch(60% 0.21 280)',
  indigoSoft: 'oklch(92% 0.05 280)',
  indigoText: 'oklch(55% 0.20 280)',
  sidebarBg: '#0a0d1a',
  sidebarMute: 'oklch(75% 0.04 280)',
  sidebarMute2: 'oklch(55% 0.03 280)',
  red: 'oklch(62% 0.20 25)',
  redBg: 'oklch(94% 0.04 25)',
  green: 'oklch(60% 0.16 155)',
  greenBg: 'oklch(94% 0.05 155)',
  amber: 'oklch(72% 0.15 75)',
  amberBg: 'oklch(95% 0.06 75)',
  font: '"Inter", system-ui, -apple-system, sans-serif',
  fontMono: '"JetBrains Mono", ui-monospace, monospace',
};

// ── Multi-color glyph used to indicate "Slack channel" (stylized, not a brand mark) ─
function SlackGlyph({ size = 14, active = true }) {
  // 4 rounded rects arranged in a pinwheel — generic "messenger" style.
  // When inactive, render in monochrome muted.
  const c1 = active ? 'oklch(75% 0.18 30)'  : 'oklch(70% 0.02 280)';  // warm
  const c2 = active ? 'oklch(75% 0.16 145)' : 'oklch(70% 0.02 280)';  // green
  const c3 = active ? 'oklch(70% 0.18 220)' : 'oklch(70% 0.02 280)';  // blue
  const c4 = active ? 'oklch(80% 0.16 95)'  : 'oklch(70% 0.02 280)';  // yellow
  return (
    <svg width={size} height={size} viewBox="0 0 20 20" fill="none">
      <rect x="2"  y="8"  width="6" height="2.4" rx="1.2" fill={c1}/>
      <rect x="8"  y="2"  width="2.4" height="6" rx="1.2" fill={c4}/>
      <rect x="12" y="9.6" width="6" height="2.4" rx="1.2" fill={c2}/>
      <rect x="9.6" y="12" width="2.4" height="6" rx="1.2" fill={c3}/>
    </svg>
  );
}

// ── Cross pattern background ────────────────────────────────────────────────
function CrossBG({ children, style }) {
  const svg = "<svg xmlns='http://www.w3.org/2000/svg' width='52' height='52' viewBox='0 0 52 52'><g stroke='%237a78c2' stroke-width='1.4' opacity='0.42' stroke-linecap='round'><line x1='26' y1='22' x2='26' y2='30'/><line x1='22' y1='26' x2='30' y2='26'/></g></svg>";
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: KORYO.bg,
      backgroundImage: `url("data:image/svg+xml;utf8,${svg}")`,
      backgroundSize: '52px 52px',
      ...style,
    }}>
      {children}
    </div>
  );
}

// ── Heart-rate logo mark ───────────────────────────────────────────────────
function KoryoMark({ size = 28, color = KORYO.indigo }) {
  return (
    <svg width={size} height={size * 0.72} viewBox="0 0 50 36" fill="none">
      <path d="M2 18 H12 L16 8 L22 28 L28 14 L32 22 L36 18 H48"
        stroke={color} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

// ── App icon (square w/ heart-rate) ────────────────────────────────────────
function KoryoAppIcon({ size = 72 }) {
  return (
    <div style={{
      width: size, height: size,
      background: '#0e0e1a',
      borderRadius: size * 0.22,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      boxShadow: '0 8px 24px rgba(14,14,26,0.16)',
    }}>
      <KoryoMark size={size * 0.62} color="oklch(78% 0.16 280)"/>
    </div>
  );
}

// ── Sidebar nav icon ───────────────────────────────────────────────────────
function NavIcon({ kind, size = 18, color = 'currentColor' }) {
  const s = { width: size, height: size, stroke: color, fill: 'none', strokeWidth: 1.7, strokeLinecap: 'round', strokeLinejoin: 'round' };
  if (kind === 'users') return (
    <svg viewBox="0 0 24 24" {...s}>
      <circle cx="9" cy="8" r="3.2"/><path d="M2.5 20c.7-3.5 3.4-5.4 6.5-5.4s5.8 1.9 6.5 5.4"/>
      <circle cx="17" cy="7" r="2.6"/><path d="M15 14.2c2.5.2 4.6 1.7 5.5 4.3"/>
    </svg>
  );
  if (kind === 'surveys') return (
    <svg viewBox="0 0 24 24" {...s}>
      <rect x="4" y="3" width="13" height="15" rx="2"/>
      <rect x="7" y="6" width="13" height="15" rx="2" fill="rgba(255,255,255,0.08)"/>
    </svg>
  );
  if (kind === 'results') return (
    <svg viewBox="0 0 24 24" {...s}>
      <line x1="4" y1="20" x2="4" y2="11"/><line x1="10" y1="20" x2="10" y2="7"/>
      <line x1="16" y1="20" x2="16" y2="14"/><line x1="2" y1="21" x2="22" y2="21"/>
    </svg>
  );
  if (kind === 'settings') return (
    <svg viewBox="0 0 24 24" {...s}>
      <circle cx="12" cy="12" r="3"/>
      <path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 0 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 0 1 0-4h.1A1.7 1.7 0 0 0 4.6 9a1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9A1.7 1.7 0 0 0 10 3.1V3a2 2 0 0 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 0 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/>
    </svg>
  );
  if (kind === 'cards') return (
    <svg viewBox="0 0 24 24" {...s}>
      <rect x="4" y="3" width="13" height="15" rx="2"/>
      <rect x="7" y="6" width="13" height="15" rx="2"/>
    </svg>
  );
  return null;
}

// ── Sidebar ────────────────────────────────────────────────────────────────
function KoryoSidebar({ active = 'home' }) {
  const item = (key, label, icon) => {
    const on = active === key;
    return (
      <div style={{
        display: 'flex', alignItems: 'center', gap: 14,
        padding: '11px 22px',
        color: on ? KORYO.indigo : KORYO.sidebarMute,
        fontWeight: on ? 700 : 500,
        fontSize: 15,
        background: on ? 'rgba(120,110,240,0.10)' : 'transparent',
        borderLeft: on ? `3px solid ${KORYO.indigo}` : '3px solid transparent',
      }}>
        <NavIcon kind={icon} size={18}/>
        <span>{label}</span>
      </div>
    );
  };
  return (
    <div style={{
      width: 230, height: '100%',
      background: KORYO.sidebarBg,
      color: '#fff',
      display: 'flex', flexDirection: 'column',
      fontFamily: KORYO.font,
      flexShrink: 0,
    }}>
      <div style={{ padding: '22px 22px 16px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <KoryoMark size={22}/>
          <div style={{ fontWeight: 800, fontSize: 22, letterSpacing: '-0.02em' }}>koryo</div>
        </div>
        <div style={{ marginTop: 14, fontSize: 12.5, color: KORYO.sidebarMute, lineHeight: 1.35 }}>
          Employee Experience<br/>
          <span style={{ color: KORYO.sidebarMute2 }}>Axon Apps</span>
        </div>
      </div>
      <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 2 }}>
        {item('users','Users','users')}
        {item('surveys','Surveys','cards')}
        {item('results','Results','results')}
        {item('settings','Settings','settings')}
      </div>
      <div style={{ flex: 1 }}/>
      <div style={{ padding: '14px 22px 16px', borderTop: '1px solid rgba(255,255,255,0.06)' }}>
        <div style={{ fontWeight: 700, fontSize: 13.5, color: '#fff' }}>Alex Kim</div>
        <div style={{ fontSize: 12, color: KORYO.sidebarMute, marginTop: 2 }}>alex.kim@axonapps.io</div>
        <div style={{ fontSize: 12, color: KORYO.indigo, marginTop: 8 }}>○ Super admin</div>
        <div style={{ fontSize: 12, color: KORYO.sidebarMute, marginTop: 4 }}>Change password</div>
        <div style={{ fontSize: 12, color: 'oklch(65% 0.18 25)', marginTop: 4 }}>Sign out</div>
      </div>
      <div style={{ padding: '12px 22px 18px', display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{ fontSize: 13, color: KORYO.sidebarMute }}>☀ Light</span>
        <div style={{ width: 28, height: 16, borderRadius: 10, background: 'rgba(255,255,255,0.12)', position: 'relative' }}>
          <div style={{ position: 'absolute', left: 2, top: 2, width: 12, height: 12, background: '#fff', borderRadius: 6 }}/>
        </div>
      </div>
    </div>
  );
}

// ── App-shell frame (sidebar + content area on cross bg) ───────────────────
function KoryoApp({ active = 'home', children, browserChrome = true }) {
  return (
    <div style={{
      width: '100%', height: '100%',
      display: 'flex', flexDirection: 'column',
      background: '#dcdaed',
      fontFamily: KORYO.font,
    }}>
      {browserChrome && (
        <div style={{
          height: 36, background: '#dcdaed',
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '0 14px',
          borderBottom: '1px solid rgba(0,0,0,0.04)',
          flexShrink: 0,
        }}>
          <div style={{ display: 'flex', gap: 6 }}>
            <div style={{ width: 11, height: 11, borderRadius: 6, background: '#ff5f57' }}/>
            <div style={{ width: 11, height: 11, borderRadius: 6, background: '#febc2e' }}/>
            <div style={{ width: 11, height: 11, borderRadius: 6, background: '#28c840' }}/>
          </div>
          <div style={{
            marginLeft: 14,
            background: '#fff',
            border: '1px solid rgba(0,0,0,0.05)',
            borderRadius: 6,
            padding: '4px 12px',
            fontSize: 11,
            color: KORYO.inkSoft,
            fontFamily: KORYO.fontMono,
            minWidth: 360,
          }}>
            app.koryo.work / axon-apps
          </div>
        </div>
      )}
      <div style={{ display: 'flex', flex: 1, minHeight: 0 }}>
        <KoryoSidebar active={active}/>
        <div style={{ flex: 1, position: 'relative' }}>
          <CrossBG/>
          <div style={{ position: 'absolute', inset: 0 }}>
            {children}
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Animated cursor pointer ────────────────────────────────────────────────
function Cursor({ path, color = '#0e0e1a' }) {
  // path: [{t, x, y}, ...] — t is progress 0..1 across the sprite duration
  const { progress } = useSprite();
  if (!path || path.length === 0) return null;

  let x = path[0].x, y = path[0].y;
  if (progress >= path[path.length - 1].t) {
    x = path[path.length - 1].x; y = path[path.length - 1].y;
  } else {
    for (let i = 0; i < path.length - 1; i++) {
      const a = path[i], b = path[i + 1];
      if (progress >= a.t && progress <= b.t) {
        const span = b.t - a.t;
        const local = span === 0 ? 0 : (progress - a.t) / span;
        const eased = Easing.easeInOutCubic(local);
        x = a.x + (b.x - a.x) * eased;
        y = a.y + (b.y - a.y) * eased;
        break;
      }
    }
  }

  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      pointerEvents: 'none', zIndex: 50,
      filter: 'drop-shadow(0 3px 4px rgba(0,0,0,0.18))',
    }}>
      <svg width="22" height="26" viewBox="0 0 22 26" fill="none">
        <path d="M2 2 L2 19 L7 15 L10 22 L13 21 L10 14 L17 14 Z" fill="#fff" stroke={color} strokeWidth="1.5" strokeLinejoin="round"/>
      </svg>
    </div>
  );
}

// ── Click pulse (shows when cursor "clicks") ───────────────────────────────
function ClickPulse({ x, y, at, color = KORYO.indigo }) {
  const { localTime } = useSprite();
  const dt = localTime - at;
  if (dt < 0 || dt > 0.7) return null;
  const p = dt / 0.7;
  const r = 8 + p * 22;
  const op = 1 - p;
  return (
    <div style={{
      position: 'absolute', left: x - r, top: y - r,
      width: r * 2, height: r * 2,
      borderRadius: '50%',
      border: `2px solid ${color}`,
      opacity: op,
      zIndex: 49,
      pointerEvents: 'none',
    }}/>
  );
}

// ── Caption (bottom-left explainer chip) ───────────────────────────────────
function Caption({ kicker, line }) {
  const { localTime, duration } = useSprite();
  const inAt = 0.25;
  const outAt = duration - 0.3;
  let opacity = 1, ty = 0;
  if (localTime < inAt) {
    const t = Easing.easeOutCubic(clamp(localTime / inAt, 0, 1));
    opacity = t; ty = (1 - t) * 12;
  } else if (localTime > outAt) {
    const t = Easing.easeInCubic(clamp((localTime - outAt) / 0.3, 0, 1));
    opacity = 1 - t; ty = -t * 8;
  }
  return (
    <div style={{
      position: 'absolute', left: 0, right: 0, bottom: 0,
      opacity, transform: `translateY(${ty}px)`,
      zIndex: 100,
      padding: '22px 60px 26px',
      background: 'linear-gradient(to top, rgba(8,8,14,0.78) 0%, rgba(8,8,14,0.62) 60%, rgba(8,8,14,0) 100%)',
      display: 'flex', alignItems: 'center', gap: 26,
    }}>
      {kicker && (
        <div style={{
          fontFamily: KORYO.fontMono,
          fontSize: 13,
          letterSpacing: '0.20em',
          textTransform: 'uppercase',
          color: 'oklch(82% 0.14 280)',
          fontWeight: 700,
          whiteSpace: 'nowrap',
          paddingRight: 22,
          borderRight: '1px solid rgba(255,255,255,0.22)',
        }}>
          {kicker}
        </div>
      )}
      <div style={{
        fontFamily: KORYO.font,
        fontSize: 30,
        fontWeight: 700,
        color: '#fff',
        letterSpacing: '-0.02em',
        lineHeight: 1.18,
        textWrap: 'pretty',
        flex: 1,
      }}>
        {line}
      </div>
    </div>
  );
}

// ── Scene letterbox / vignette helper (subtle dark edges) ──────────────────
function SceneVignette() {
  return (
    <div style={{
      position: 'absolute', inset: 0, pointerEvents: 'none',
      background: 'radial-gradient(ellipse at center, transparent 55%, rgba(0,0,0,0.18) 100%)',
    }}/>
  );
}

// ── Crossfade wrapper: fades the entire scene in and out ───────────────────
function SceneFade({ children, fadeIn = 0.5, fadeOut = 0.5 }) {
  const { localTime, duration } = useSprite();
  let opacity = 1;
  if (localTime < fadeIn) opacity = Easing.easeOutCubic(localTime / fadeIn);
  else if (localTime > duration - fadeOut) opacity = 1 - Easing.easeInCubic((localTime - (duration - fadeOut)) / fadeOut);
  return (
    <div style={{ position: 'absolute', inset: 0, opacity, willChange: 'opacity' }}>
      {children}
    </div>
  );
}

// ── Camera move (scale + translate the whole scene) ─────────────────────────
function CameraMove({ from = { x: 0, y: 0, scale: 1 }, to = { x: 0, y: 0, scale: 1 }, ease = Easing.easeInOutCubic, children }) {
  const { progress } = useSprite();
  const t = ease(progress);
  const x = from.x + (to.x - from.x) * t;
  const y = from.y + (to.y - from.y) * t;
  const s = from.scale + (to.scale - from.scale) * t;
  return (
    <div style={{
      position: 'absolute', inset: 0,
      transform: `translate(${x}px, ${y}px) scale(${s})`,
      transformOrigin: 'center center',
      willChange: 'transform',
    }}>
      {children}
    </div>
  );
}

Object.assign(window, {
  KORYO, CrossBG, KoryoMark, KoryoAppIcon, NavIcon, SlackGlyph,
  KoryoSidebar, KoryoApp, Cursor, ClickPulse, Caption,
  SceneVignette, SceneFade, CameraMove,
});
