// Scene 4: Admin — Enterprise Control (28–33s, 5s)
// Rebuilt: spring panel transitions, FLIP-style sidebar active pill,
// spring counters on stats, staggered bar chart with spring heights.

function SceneAdmin() {
  const { localTime } = useSprite();
  const t = localTime;

  const cursorPath = [
    { t: 0.0, x: 960, y: 540 },
    { t: 1.3, x: 320, y: 250, click: true },
    { t: 3.2, x: 320, y: 300, click: true },
    { t: 5.0, x: 320, y: 300 },
  ];
  const cursor = cursorPhysics(cursorPath, t);

  const panel = t < 1.35 ? 'users' : t < 3.25 ? 'audit' : 'tenant';

  const camStops = [
    { t: 0.0, scale: 1.02, x: 960, y: 540 },
    { t: 1.4, scale: 1.02, x: 960, y: 540 },
    { t: 2.0, scale: 1.04, x: 960, y: 520 },
    { t: 3.4, scale: 1.02, x: 960, y: 540 },
    { t: 5.0, scale: 1.04, x: 960, y: 540 },
  ];

  const navItems = [
    { id: 'users', label: 'Users', icon: Icons.users, y: 0 },
    { id: 'audit', label: 'Audit Log', icon: Icons.log, y: 1 },
    { id: 'tenant', label: 'Tenant Overview', icon: Icons.chart, y: 2 },
  ];
  // FLIP-ish: the active pill position springs between positions
  const activeIdx = panel === 'users' ? 0 : panel === 'audit' ? 1 : 2;
  const pillY = spring(t, 0, activeIdx, 0, { stiffness: 240, damping: 24 })
              + (activeIdx > 0 ? spring(t, 0, activeIdx, activeIdx === 1 ? 1.35 : 3.25, { stiffness: 240, damping: 24 }) - activeIdx : 0);
  // Simpler: animate to current target from last target
  const targetY = activeIdx;
  const prevSwitch = activeIdx === 0 ? 0 : activeIdx === 1 ? 1.35 : 3.25;
  const pillYAnimated = spring(t, activeIdx > 0 ? activeIdx - 1 : 0, targetY, prevSwitch, { stiffness: 240, damping: 24 });

  return (
    <Camera stops={camStops}>
      <AewitaShell activeMode="admin">
        <div style={{ position: 'absolute', inset: 0, display: 'flex' }}>
          {/* Admin sub-sidebar */}
          <div style={{
            width: 240, flexShrink: 0,
            borderRight: `1px solid ${COLORS.border}`,
            padding: '18px 12px',
            display: 'flex', flexDirection: 'column', gap: 3,
            position: 'relative',
          }}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '6px 12px 14px',
              fontSize: 18, fontFamily: FONTS.serif, fontWeight: 600,
              color: COLORS.textPrimary,
            }}>
              <span style={{ color: COLORS.copper }}>{Icons.shield}</span>
              Admin
            </div>

            {/* FLIP-style active pill */}
            <div style={{
              position: 'absolute',
              left: 12, right: 12,
              top: 58,
              height: 38,
              background: 'rgba(217,72,78,0.10)',
              border: `1px solid rgba(217,72,78,0.18)`,
              borderRadius: 8,
              transform: `translateY(${pillYAnimated * 41}px)`,
              willChange: 'transform',
              pointerEvents: 'none',
            }}/>

            {navItems.map(item => (
              <div key={item.id} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '9px 12px', borderRadius: 8,
                color: panel === item.id ? COLORS.accent : COLORS.textSecondary,
                fontSize: 13, fontWeight: panel === item.id ? 600 : 400,
                position: 'relative', zIndex: 1,
              }}>
                <div>{item.icon}</div>
                <span>{item.label}</span>
              </div>
            ))}
          </div>

          {/* Panel content */}
          <div style={{ flex: 1, overflow: 'hidden', padding: '24px 32px' }}>
            {panel === 'users' && <UsersPanel t={t} />}
            {panel === 'audit' && <AuditPanel t={t - 1.35} />}
            {panel === 'tenant' && <TenantPanel t={t - 3.25} />}
          </div>
        </div>
      </AewitaShell>
      <Cursor x={cursor.x} y={cursor.y} clicking={cursor.clicking} scale={cursor.scale} />
    </Camera>
  );
}

function UsersPanel({ t }) {
  const users = [
    { name: 'Sam Marchetti', email: 'sam@firm.com', role: 'admin', initials: 'SM' },
    { name: 'Priya Chandran', email: 'priya@firm.com', role: 'partner', initials: 'PC' },
    { name: 'Elena Vasquez', email: 'elena@firm.com', role: 'associate', initials: 'EV' },
    { name: 'Jonah Weller', email: 'jonah@firm.com', role: 'paralegal', initials: 'JW' },
  ];
  return (
    <>
      <div style={{
        fontFamily: FONTS.serif, fontSize: 26, fontWeight: 600, color: COLORS.textPrimary,
        opacity: spring(t, 0, 1, 0, Springs.snappy),
        transform: `translateY(${(1 - spring(t, 0, 1, 0, Springs.snappy)) * 6}px)`,
      }}>Users</div>
      <div style={{ fontSize: 13, color: COLORS.textSecondary, marginTop: 4, marginBottom: 24,
                    opacity: spring(t, 0, 1, 0.05, Springs.snappy) }}>
        Manage team members and roles.
      </div>
      <div style={{
        background: COLORS.bgCard,
        border: `1px solid ${COLORS.border}`,
        borderRadius: 12,
        padding: 20,
        opacity: spring(t, 0, 1, 0.1, Springs.snappy),
        transform: `translateY(${(1 - spring(t, 0, 1, 0.1, Springs.snappy)) * 10}px)`,
      }}>
        <div style={{ fontSize: 15, fontWeight: 600, color: COLORS.textPrimary, marginBottom: 6 }}>Team Members</div>
        <div style={{ fontSize: 12, color: COLORS.textMuted, marginBottom: 16 }}>Users with access to this tenant</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {users.map((u, i) => {
            const p = stagger(t, i, 0.06, 0.2, { stiffness: 260, damping: 22 });
            return (
              <div key={u.email} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '10px 4px',
                borderBottom: i < users.length - 1 ? `1px solid ${COLORS.border}` : 'none',
                opacity: Math.min(1, p),
                transform: `translateX(${(1 - Math.min(1, p)) * -10}px)`,
              }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 16,
                  background: '#2A2D31', color: COLORS.textSecondary,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 11, fontWeight: 600,
                }}>{u.initials}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, color: COLORS.textPrimary, fontWeight: 500 }}>{u.name}</div>
                  <div style={{ fontSize: 11, color: COLORS.textMuted }}>{u.email}</div>
                </div>
                <div style={{
                  padding: '3px 10px', borderRadius: 10,
                  background: u.role === 'admin' ? 'rgba(200,133,107,0.15)' : 'rgba(232,224,216,0.06)',
                  color: u.role === 'admin' ? COLORS.copper : COLORS.textSecondary,
                  fontSize: 10, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase',
                }}>{u.role}</div>
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
}

function AuditPanel({ t }) {
  const rows = [
    { time: '14:42:18', user: 'sam@firm.com', action: 'document.query', target: 'Reeves v. Meridian Health' },
    { time: '14:40:03', user: 'sam@firm.com', action: 'document.upload', target: 'Expert_Report_Lindeman.pdf' },
    { time: '14:38:50', user: 'priya@firm.com', action: 'draft.export', target: 'Motion for Summary Judgment → NetDocs' },
    { time: '14:35:22', user: 'elena@firm.com', action: 'memory.approved', target: 'Texas liquidated damages rule' },
    { time: '14:33:11', user: 'sam@firm.com', action: 'session.created', target: 'Opposing counsel · penalty doctrine' },
    { time: '14:28:07', user: 'jonah@firm.com', action: 'document.viewed', target: 'Vendor Addendum — Meridian.pdf' },
    { time: '14:24:55', user: 'priya@firm.com', action: 'citation.verified', target: 'FPL Energy v. TXU Portfolio' },
  ];
  return (
    <>
      <div style={{
        fontFamily: FONTS.serif, fontSize: 26, fontWeight: 600, color: COLORS.textPrimary,
        opacity: spring(t, 0, 1, 0, Springs.snappy),
        transform: `translateY(${(1 - spring(t, 0, 1, 0, Springs.snappy)) * 6}px)`,
      }}>Audit Log</div>
      <div style={{ fontSize: 13, color: COLORS.textSecondary, marginTop: 4, marginBottom: 24,
                    opacity: spring(t, 0, 1, 0.05, Springs.snappy) }}>
        Every action is timestamped, attributed, and signed. Nothing leaves your infrastructure.
      </div>
      <div style={{
        background: COLORS.bgCard,
        border: `1px solid ${COLORS.border}`,
        borderRadius: 12,
        overflow: 'hidden',
        opacity: spring(t, 0, 1, 0.1, Springs.snappy),
        transform: `translateY(${(1 - spring(t, 0, 1, 0.1, Springs.snappy)) * 12}px)`,
      }}>
        <div style={{
          display: 'grid', gridTemplateColumns: '110px 180px 180px 1fr',
          padding: '10px 16px',
          background: COLORS.bgSunken,
          borderBottom: `1px solid ${COLORS.border}`,
          fontSize: 10, fontFamily: FONTS.mono, letterSpacing: '0.08em', textTransform: 'uppercase',
          color: COLORS.textMuted, fontWeight: 600,
        }}>
          <div>TIME</div><div>USER</div><div>ACTION</div><div>TARGET</div>
        </div>
        {rows.map((r, i) => {
          const p = stagger(t, i, 0.055, 0.2, { stiffness: 280, damping: 24 });
          return (
            <div key={i} style={{
              display: 'grid', gridTemplateColumns: '110px 180px 180px 1fr',
              padding: '11px 16px',
              borderBottom: i < rows.length - 1 ? `1px solid ${COLORS.border}` : 'none',
              fontSize: 12,
              opacity: Math.min(1, p),
              transform: `translateX(${(1 - Math.min(1, p)) * -10}px)`,
            }}>
              <div style={{ fontFamily: FONTS.mono, color: COLORS.textMuted }}>{r.time}</div>
              <div style={{ color: COLORS.textSecondary }}>{r.user}</div>
              <div style={{ fontFamily: FONTS.mono, color: COLORS.copper, fontSize: 11 }}>{r.action}</div>
              <div style={{ color: COLORS.textPrimary }}>{r.target}</div>
            </div>
          );
        })}
      </div>
    </>
  );
}

function TenantPanel({ t }) {
  const stats = [
    { label: 'Active users', value: 34, decimals: 0, suffix: '' },
    { label: 'Matters', value: 127, decimals: 0, suffix: '' },
    { label: 'Documents indexed', value: 42800, decimals: 0, suffix: '' },
    { label: 'Storage used', value: 1.3, decimals: 1, suffix: ' TB' },
  ];
  return (
    <>
      <div style={{
        fontFamily: FONTS.serif, fontSize: 26, fontWeight: 600, color: COLORS.textPrimary,
        opacity: spring(t, 0, 1, 0, Springs.snappy),
      }}>Tenant Overview</div>
      <div style={{ fontSize: 13, color: COLORS.textSecondary, marginTop: 4, marginBottom: 24,
                    opacity: spring(t, 0, 1, 0.05, Springs.snappy) }}>
        Self-hosted on your infrastructure. All metrics local.
      </div>
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
        gap: 12, marginBottom: 20,
      }}>
        {stats.map((s, i) => {
          const p = stagger(t, i, 0.08, 0.1, { stiffness: 240, damping: 22 });
          const countT = countUp(t, 0, s.value, 0.1 + i * 0.08, { stiffness: 70, damping: 22 });
          const displayed = s.decimals > 0
            ? countT.toFixed(s.decimals)
            : Math.round(countT).toLocaleString();
          return (
            <div key={s.label} style={{
              padding: 18,
              background: COLORS.bgCard,
              border: `1px solid ${COLORS.border}`,
              borderRadius: 10,
              opacity: Math.min(1, p),
              transform: `translateY(${(1 - Math.min(1, p)) * 14}px) scale(${0.96 + 0.04 * Math.min(1, p)})`,
            }}>
              <div style={{ fontSize: 11, color: COLORS.textMuted, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{s.label}</div>
              <div style={{
                fontSize: 28, fontFamily: FONTS.serif, fontWeight: 600,
                color: COLORS.textPrimary, marginTop: 6,
                fontVariantNumeric: 'tabular-nums',
              }}>
                {displayed}{s.suffix}
              </div>
            </div>
          );
        })}
      </div>

      <div style={{
        padding: 20,
        background: COLORS.bgCard,
        border: `1px solid ${COLORS.border}`,
        borderRadius: 12,
        opacity: spring(t, 0, 1, 0.4, Springs.gentle),
        transform: `translateY(${(1 - spring(t, 0, 1, 0.4, Springs.gentle)) * 16}px)`,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: COLORS.textPrimary }}>Model performance · last 7 days</div>
          <div style={{ fontSize: 11, color: COLORS.sage, fontFamily: FONTS.mono }}>● all systems nominal</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 90 }}>
          {[0.45, 0.52, 0.48, 0.61, 0.58, 0.72, 0.68, 0.80, 0.74, 0.65, 0.70, 0.78, 0.82, 0.76].map((h, i) => {
            const p = clampN(spring(t, 0, 1, 0.6 + i * 0.035, { stiffness: 220, damping: 18 }), 0, 1);
            return (
              <div key={i} style={{
                flex: 1,
                height: `${h * p * 100}%`,
                background: `linear-gradient(to top, ${COLORS.copperDim}, ${COLORS.copper})`,
                borderRadius: 2,
                minHeight: 2,
                transformOrigin: 'bottom',
              }}/>
            );
          })}
        </div>
        <div style={{
          display: 'flex', justifyContent: 'space-between',
          fontSize: 10, fontFamily: FONTS.mono, color: COLORS.textMuted,
          marginTop: 8,
        }}>
          <span>apr 14</span><span>apr 21</span>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { SceneAdmin });
