// CTox app shell — reusable UI: header, sidebar, logo, icons, cursor.
// All sizes baked for a 1920x1080 stage.

const CTX_BLUE = '#1C4137';       // Synvia dark green (primary)
const CTX_BLUE_DARK = '#143025';
const CTX_TEAL = '#1FAFAB';        // gradient end on logo pill (legacy)
const CTX_BG = '#EEEEEE';          // page background
const CTX_INK = '#2C3942';         // dark text
const CTX_MUTED = '#94A3AC';
const CTX_GREEN_DK = '#0C3A2A';
const CTX_GREEN_LIME = '#B2E847';
const CTX_RED = '#E94B4B';
const CTX_SIDEBAR = '#F7F7F7';
const CTX_DIVIDER = '#E5E7EA';

// ── Synvia arrow mark (gradient PNG asset) ────────────────────────────────
const SYNVIA_ARROW_SRC = (typeof window !== 'undefined' && window.__resources && window.__resources.synviaArrow) || 'assets/synvia-arrow.png';
const SYNVIA_LOGO_SRC  = (typeof window !== 'undefined' && window.__resources && window.__resources.synviaLogo)  || 'assets/synvia-logo.png';

function SynviaArrow({ size = 64 }) {
  return (
    <img
      src={SYNVIA_ARROW_SRC}
      alt="Synvia"
      style={{
        width: size, height: size * (1122 / 1028),
        display: 'block',
        objectFit: 'contain',
      }}
    />
  );
}

// Small arrow for header/sidebar — recolors the PNG via CSS filter.
function SynviaLogo({ size = 36, color = '#fff' }) {
  if (color === 'gradient') {
    return <SynviaArrow size={size} />;
  }
  // White: invert the dark-on-transparent PNG. For other colors, we'd need SVG.
  const filter = color === '#fff' || color === 'white'
    ? 'brightness(0) invert(1)'
    : 'none';
  return (
    <img
      src={SYNVIA_ARROW_SRC}
      alt="Synvia"
      style={{
        width: size, height: size * (1122 / 1028),
        display: 'block',
        objectFit: 'contain',
        filter,
      }}
    />
  );
}

// Full logo for the login screen: PNG with the arrow + "synvia" wordmark.
function SynviaLogoFull({ scale = 1 }) {
  const w = 1366 * scale;
  const h = 570 * scale;
  return (
    <img
      src={SYNVIA_LOGO_SRC}
      alt="Synvia"
      style={{
        width: w, height: h,
        display: 'block',
        objectFit: 'contain',
      }}
    />
  );
}

// ── Sidebar icon set (simple line icons) ───────────────────────────────────
const I = {
  burger: (
    <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round">
      <line x1="4" y1="7" x2="20" y2="7"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="17" x2="20" y2="17"/>
    </svg>
  ),
  home: (
    <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round">
      <path d="M4 11l8-7 8 7v9a1 1 0 0 1-1 1h-4v-6h-6v6H5a1 1 0 0 1-1-1z"/>
    </svg>
  ),
  car: (
    <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round" strokeLinecap="round">
      <path d="M3 14l2-5a3 3 0 0 1 2.8-2h8.4A3 3 0 0 1 19 9l2 5v4h-3v-2H6v2H3z"/>
      <circle cx="7.5" cy="16.5" r="1.2"/><circle cx="16.5" cy="16.5" r="1.2"/>
    </svg>
  ),
  scissors: (
    <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/>
      <line x1="20" y1="4" x2="8.5" y2="14"/><line x1="20" y1="20" x2="8.5" y2="10"/>
    </svg>
  ),
  box: (
    <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round">
      <path d="M3.5 7.5 12 4l8.5 3.5v9L12 20l-8.5-3.5z"/><path d="M3.5 7.5 12 11l8.5-3.5M12 11v9"/>
    </svg>
  ),
  send: (
    <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round" strokeLinecap="round">
      <path d="M3 11.5 21 3l-7.5 18-2.5-8z"/>
    </svg>
  ),
  bars: (
    <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round">
      <rect x="4" y="13" width="3" height="7"/><rect x="10.5" y="8" width="3" height="12"/><rect x="17" y="4" width="3" height="16"/>
    </svg>
  ),
  factory: (
    <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round">
      <path d="M3 20V9l5 3V9l5 3V9l5 3v8z"/><line x1="3" y1="20" x2="21" y2="20"/>
    </svg>
  ),
  people: (
    <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round">
      <circle cx="9" cy="9" r="3"/><circle cx="16" cy="10" r="2.2"/>
      <path d="M3 19c0-3 3-5 6-5s6 2 6 5M14 19c0-2 2-4 5-4s4 1.5 4 4"/>
    </svg>
  ),
  flask: (
    <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round">
      <path d="M9 3h6M10 3v6L5 19a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2L14 9V3"/>
    </svg>
  ),
  server: (
    <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round">
      <rect x="3" y="6" width="18" height="5" rx="1"/><rect x="3" y="13" width="18" height="5" rx="1"/>
      <circle cx="7" cy="8.5" r="0.7" fill="currentColor"/><circle cx="7" cy="15.5" r="0.7" fill="currentColor"/>
    </svg>
  ),
  pulse: (
    <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round" strokeLinecap="round">
      <path d="M3 12h4l2-5 3 10 2-7 2 4 5-2"/>
    </svg>
  ),
  docplus: (
    <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round">
      <path d="M6 3h8l4 4v14H6z"/><path d="M12 11v6M9 14h6"/>
    </svg>
  ),
  person: (
    <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round">
      <circle cx="12" cy="8" r="3.4"/><path d="M4 21c0-4 4-6.5 8-6.5s8 2.5 8 6.5"/>
    </svg>
  ),
  pin: (
    <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round">
      <path d="M12 21s7-7.5 7-12a7 7 0 1 0-14 0c0 4.5 7 12 7 12z"/><circle cx="12" cy="9" r="2.4"/>
    </svg>
  ),
  tag: (
    <svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round">
      <path d="M3 13 13 3h7v7L10 20z"/><circle cx="16" cy="8" r="1.3"/>
    </svg>
  ),
  bell: (
    <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round">
      <path d="M6 16V11a6 6 0 0 1 12 0v5l1.5 2h-15z"/><path d="M10 20a2 2 0 0 0 4 0"/>
    </svg>
  ),
  plus: (
    <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
      <circle cx="12" cy="12" r="9"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/>
    </svg>
  ),
  printer: (
    <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round">
      <rect x="6" y="3" width="12" height="6"/><rect x="3" y="9" width="18" height="9" rx="1"/>
      <rect x="6" y="15" width="12" height="5"/>
    </svg>
  ),
  trash: (
    <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round">
      <path d="M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13"/>
    </svg>
  ),
  search: (
    <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round">
      <circle cx="11" cy="11" r="6"/><line x1="16" y1="16" x2="20" y2="20"/>
    </svg>
  ),
  chat: (
    <svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinejoin="round">
      <path d="M4 5h16v11h-9l-5 4v-4H4z"/>
    </svg>
  ),
  back: (
    <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14 6l-6 6 6 6"/>
    </svg>
  ),
  xCircle: (
    <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinejoin="round">
      <circle cx="12" cy="12" r="9"/><line x1="9" y1="9" x2="15" y2="15"/><line x1="15" y1="9" x2="9" y2="15"/>
    </svg>
  ),
  eye: (
    <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor">
      <path d="M12 5c-5 0-9 4.5-10 7 1 2.5 5 7 10 7s9-4.5 10-7c-1-2.5-5-7-10-7zm0 11a4 4 0 110-8 4 4 0 010 8zm0-2a2 2 0 100-4 2 2 0 000 4z"/>
    </svg>
  ),
};

// ── Sidebar ────────────────────────────────────────────────────────────────
const SIDEBAR_ITEMS = [
  { id: 'home', icon: I.home },
  { id: 'car', icon: I.car },
  { id: 'scissors', icon: I.scissors },
  { id: 'box', icon: I.box },
  { id: 'send', icon: I.send },
  { id: 'bars', icon: I.bars },
  { id: 'factory', icon: I.factory },
  { id: 'people', icon: I.people },
  { id: 'flask', icon: I.flask },
  { id: 'server', icon: I.server },
  { id: 'pulse', icon: I.pulse },
  { id: 'docplus', icon: I.docplus },
  { id: 'person', icon: I.person },   // ← Coletores
  { id: 'pin', icon: I.pin },
  { id: 'tag', icon: I.tag },
];

function Sidebar({ active = null, highlight = null }) {
  return (
    <div style={{
      position: 'absolute', top: 0, left: 0,
      width: 96, height: '100%',
      background: CTX_SIDEBAR,
      borderRight: `1px solid ${CTX_DIVIDER}`,
      display: 'flex', flexDirection: 'column',
      alignItems: 'center',
      paddingTop: 0,
      zIndex: 5,
    }}>
      {/* Logo strip */}
      <div style={{
        width: '100%', height: 90,
        background: CTX_BLUE,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <SynviaLogo size={48} />
      </div>

      {/* Burger */}
      <div style={{
        width: '100%', height: 60,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: CTX_INK, opacity: 0.7,
      }}>
        {I.burger}
      </div>

      {/* Icon list */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16, paddingTop: 12 }}>
        {SIDEBAR_ITEMS.map((it) => {
          const isActive = active === it.id;
          const isHi = highlight === it.id;
          return (
            <div key={it.id} style={{
              width: 56, height: 44,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: isActive ? CTX_BLUE : CTX_INK,
              opacity: isHi ? 1 : (isActive ? 1 : 0.78),
              borderLeft: isActive ? `3px solid ${CTX_BLUE}` : '3px solid transparent',
              transition: 'color 200ms, opacity 200ms',
              transform: isHi ? 'scale(1.15)' : 'scale(1)',
            }}>
              {it.icon}
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── Top header bar ─────────────────────────────────────────────────────────
function TopBar({ title, right, leftBack = false }) {
  return (
    <div style={{
      position: 'absolute', top: 0, left: 96, right: 0,
      height: 90,
      background: CTX_BLUE,
      display: 'flex', alignItems: 'center',
      padding: '0 40px',
      color: '#fff',
      zIndex: 4,
    }}>
      {leftBack && (
        <div style={{ marginRight: 24, color: '#fff', display: 'flex' }}>{I.back}</div>
      )}
      <div style={{
        fontSize: 32, fontWeight: 500, letterSpacing: '-0.01em',
      }}>{title}</div>
      <div style={{ flex: 1 }} />
      {right}
    </div>
  );
}

// ── App shell wrapper ──────────────────────────────────────────────────────
function AppShell({ activeSidebar, sidebarHighlight, title, headerRight, headerBack, showChat = true, children }) {
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: CTX_BG,
      fontFamily: '"Helvetica Neue", Helvetica, Arial, sans-serif',
      color: CTX_INK,
    }}>
      <Sidebar active={activeSidebar} highlight={sidebarHighlight} />
      <TopBar title={title} right={headerRight} leftBack={headerBack} />
      <div style={{ position: 'absolute', top: 90, left: 96, right: 0, bottom: 0 }}>
        {children}
      </div>
      {showChat && <ChatButton />}
    </div>
  );
}

// ── Chat button (bottom right) ─────────────────────────────────────────────
function ChatButton({ pulse = false, ring = false }) {
  return (
    <div style={{
      position: 'absolute',
      right: 38, bottom: 38,
      width: 70, height: 70,
      borderRadius: '50%',
      background: '#D9E2EC',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      color: '#5C6F7C',
      boxShadow: '0 6px 18px rgba(0,0,0,0.10)',
      zIndex: 6,
      transform: ring ? 'scale(1.08)' : 'scale(1)',
      transition: 'transform 200ms',
    }}>
      {I.chat}
      {pulse && (
        <span style={{
          position: 'absolute', inset: -8,
          border: `3px solid ${CTX_BLUE}`,
          borderRadius: '50%',
          animation: 'ringPulse 1.4s ease-out infinite',
        }} />
      )}
    </div>
  );
}

// ── Pill button (header CTAs) ──────────────────────────────────────────────
function PillButton({ icon, label, color = CTX_INK, bg = '#fff', highlight = false }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 10,
      padding: '12px 22px',
      background: bg,
      color,
      borderRadius: 999,
      fontSize: 18, fontWeight: 600,
      letterSpacing: '0.04em',
      boxShadow: highlight ? `0 0 0 4px rgba(178, 232, 71, 0.6)` : '0 1px 2px rgba(0,0,0,0.04)',
      transform: highlight ? 'scale(1.05)' : 'scale(1)',
      transition: 'all 200ms',
    }}>
      <span style={{ display: 'flex' }}>{icon}</span>
      <span>{label}</span>
    </div>
  );
}

// ── Animated cursor with click ripple ──────────────────────────────────────
function Cursor({ x, y, clicking = false }) {
  return (
    <div style={{
      position: 'absolute',
      left: x, top: y,
      pointerEvents: 'none',
      zIndex: 100,
      transform: `translate(-4px, -2px) scale(${clicking ? 0.85 : 1})`,
      transition: 'transform 90ms ease-out',
      willChange: 'transform, left, top',
    }}>
      <svg width="34" height="40" viewBox="0 0 34 40" style={{ filter: 'drop-shadow(0 3px 6px rgba(0,0,0,0.30))' }}>
        <path d="M3 2 L3 30 L11 22 L15 32 L20 30 L16 20 L26 20 Z"
          fill="#111"
          stroke="#fff" strokeWidth="1.6" strokeLinejoin="round"/>
      </svg>
      {clicking && (
        <div style={{
          position: 'absolute', left: 6, top: 4,
          width: 36, height: 36, marginLeft: -10, marginTop: -10,
          borderRadius: '50%',
          border: `3px solid ${CTX_BLUE}`,
          animation: 'clickRing 360ms ease-out forwards',
        }} />
      )}
    </div>
  );
}

// ── Typed text helper: returns text[0..N] based on progress ───────────────
function typed(text, progress) {
  const n = Math.floor(text.length * clamp(progress, 0, 1) + 0.0001);
  return text.slice(0, n);
}

// ── Caption strip (lower-third) ────────────────────────────────────────────
function Caption({ text, x = 80, y = 950, width = 800, accent = CTX_GREEN_LIME, dark = true }) {
  const { progress, localTime, duration } = useSprite();
  const entryDur = 0.4;
  const exitDur = 0.3;
  let opacity = 1, ty = 0;
  if (localTime < entryDur) {
    const t = Easing.easeOutBack(localTime / entryDur);
    opacity = clamp(localTime / entryDur, 0, 1);
    ty = (1 - t) * 14;
  } else if (localTime > duration - exitDur) {
    const t = Easing.easeInCubic((localTime - (duration - exitDur)) / exitDur);
    opacity = 1 - t;
    ty = -t * 10;
  }
  return (
    <div style={{
      position: 'absolute', left: x, top: y, width,
      transform: `translateY(${ty}px)`,
      opacity,
      zIndex: 200,
    }}>
      <div style={{
        background: dark ? '#0E1418' : '#fff',
        color: dark ? '#fff' : CTX_INK,
        padding: '20px 28px',
        borderRadius: 12,
        borderLeft: `5px solid ${accent}`,
        fontSize: 26,
        fontWeight: 500,
        letterSpacing: '-0.005em',
        lineHeight: 1.35,
        boxShadow: '0 12px 32px rgba(0,0,0,0.25)',
      }}>
        {text}
      </div>
    </div>
  );
}

// SubSprite: like Sprite but timed relative to the parent sprite's localTime.
// Use this inside another <Sprite> to gate children to a window relative to
// the parent's start time.
function SubSprite({ start = 0, end = Infinity, children, keepMounted = false }) {
  const parent = React.useContext(SpriteContext);
  const parentLocal = parent.localTime || 0;
  const visible = parentLocal >= start && parentLocal <= end;
  if (!visible && !keepMounted) return null;
  const duration = end - start;
  const localTime = Math.max(0, parentLocal - start);
  const progress = duration > 0 && isFinite(duration)
    ? clamp(localTime / duration, 0, 1)
    : 0;
  const value = { localTime, progress, duration, visible };
  return (
    <SpriteContext.Provider value={value}>
      {typeof children === 'function' ? children(value) : children}
    </SpriteContext.Provider>
  );
}

Object.assign(window, {
  CTX_BLUE, CTX_BLUE_DARK, CTX_TEAL, CTX_BG, CTX_INK, CTX_MUTED,
  CTX_GREEN_DK, CTX_GREEN_LIME, CTX_RED, CTX_SIDEBAR, CTX_DIVIDER,
  SynviaArrow, SynviaLogo, SynviaLogoFull, I, Sidebar, TopBar, AppShell, ChatButton, PillButton,
  Cursor, typed, Caption, SubSprite,
});
