// dashboard.jsx — Subtle looping dashboard animation
// Restyled to match uploads/index.html (OpsKings) design system:
//   gold #a68358, surfaces #0a0a0a, rounded-full pills, white/5 borders.
// Text content is replaced with soft pill-shaped placeholder blocks.

const LOOP = 24; // seconds

// ── Design tokens (from index.html) ─────────────────────────────────────────
const C = {
  bg: '#050505',              // brand.dark
  surface: '#0a0a0a',         // brand.surface
  panel: 'rgba(255,255,255,0.03)',
  panelSolid: '#0c0c0c',
  border: 'rgba(255,255,255,0.05)',     // border-white/5
  borderStrong: 'rgba(255,255,255,0.1)',// border-white/10
  text: 'rgba(255,255,255,0.92)',
  textMute: 'rgba(255,255,255,0.6)',
  textDim: 'rgba(255,255,255,0.4)',

  gold: '#a68358',
  goldLight: '#dcc195',
  goldSoft: 'rgba(166,131,88,0.14)',
  goldGlow: 'rgba(166,131,88,0.25)',

  // Pill tones for text placeholders (light on dark, matching hero skeletons)
  pillBase: 'rgba(255,255,255,0.08)',
  pillSoft: 'rgba(255,255,255,0.05)',
  pillStrong: 'rgba(255,255,255,0.14)',
  pillGold: 'rgba(166,131,88,0.22)',
};

// ── Motion helpers (seamlessly looping) ─────────────────────────────────────
const wave = (t, period, phase = 0) =>
  Math.sin(((t / period) + phase) * Math.PI * 2);
const wave01 = (t, period, phase = 0) => (wave(t, period, phase) + 1) / 2;

// ── Pill: rounded placeholder for text ──────────────────────────────────────
function Pill({ width, height = 8, color = C.pillBase, style = {} }) {
  return (
    <div style={{
      width,
      height,
      borderRadius: 999,
      background: color,
      ...style,
    }} />
  );
}

// ── Sidebar (layout preserved; text → pills; gold accent) ──────────────────
function SidebarRow({ iconDot, pillWidth, active, sub, indicator }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      height: 30,
      padding: '0 10px',
      marginLeft: sub ? 14 : 0,
      borderRadius: 999,
      background: active ? C.goldSoft : 'transparent',
      border: active ? `1px solid ${C.gold}33` : '1px solid transparent',
    }}>
      {iconDot && (
        <div style={{
          width: 14, height: 14, borderRadius: 4,
          background: active ? C.gold : C.pillBase,
          opacity: active ? 0.9 : 0.7,
        }} />
      )}
      <Pill width={pillWidth} height={7} color={active ? C.pillGold : C.pillBase} />
      {indicator && (
        <>
          <div style={{ flex: 1 }} />
          <div style={{ width: 6, height: 6, borderRadius: 999, background: C.pillBase }} />
        </>
      )}
    </div>
  );
}

function Sidebar() {
  const t = useTime();
  const avatarPulse = 1 + wave(t, 8, 0) * 0.012;
  return (
    <div style={{
      width: 210, height: '100%',
      borderRight: `1px solid ${C.border}`,
      display: 'flex', flexDirection: 'column',
      padding: '16px 12px',
      background: C.bg,
    }}>
      {/* Brand / logo area */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '0 8px 16px' }}>
        <div style={{
          width: 22, height: 22, borderRadius: 999,
          background: `linear-gradient(135deg, ${C.gold}, ${C.goldLight})`,
          boxShadow: `0 0 14px ${C.goldGlow}`,
        }} />
        <Pill width={72} height={8} color={C.pillStrong} />
      </div>

      <SidebarRow iconDot pillWidth={68} />
      <div style={{ height: 12 }} />
      <SidebarRow iconDot pillWidth={52} />
      <SidebarRow iconDot pillWidth={60} indicator />
      <SidebarRow iconDot pillWidth={74} />

      {/* Active group with gold accent */}
      <div style={{
        marginTop: 4,
        borderRadius: 14,
        background: C.goldSoft,
        border: `1px solid ${C.gold}33`,
        padding: '2px',
      }}>
        <SidebarRow iconDot pillWidth={58} active indicator />
        <div style={{ padding: '2px 0 4px' }}>
          <SidebarRow pillWidth={48} sub />
          <SidebarRow pillWidth={64} sub />
          {/* Selected sub-item */}
          <div style={{
            marginLeft: 14,
            height: 28,
            display: 'flex', alignItems: 'center',
            padding: '0 10px',
            borderRadius: 999,
            background: 'rgba(255,255,255,0.06)',
            border: `1px solid ${C.borderStrong}`,
          }}>
            <Pill width={62} height={7} color={C.pillStrong} />
          </div>
          <SidebarRow pillWidth={52} sub />
          <SidebarRow pillWidth={70} sub />
          <SidebarRow pillWidth={40} sub />
        </div>
      </div>

      <div style={{ flex: 1 }} />

      {/* User card — gold outline (matches index.html CTA aesthetic) */}
      <div style={{
        border: `1px solid ${C.gold}`,
        borderRadius: 999,
        padding: '8px 12px',
        display: 'flex', alignItems: 'center', gap: 10,
        background: 'rgba(166,131,88,0.05)',
        boxShadow: `0 0 ${14 + wave01(t, 6) * 8}px -4px ${C.goldGlow}`,
        transform: `scale(${avatarPulse})`,
        transformOrigin: 'left center',
      }}>
        <div style={{
          width: 24, height: 24, borderRadius: 999,
          background: `linear-gradient(135deg, ${C.gold}, ${C.goldLight})`,
        }} />
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 4 }}>
          <Pill width={60} height={6} color={C.pillStrong} />
          <Pill width={84} height={5} color={C.pillSoft} />
        </div>
      </div>
    </div>
  );
}

// ── KPI card (big number + pill label) ─────────────────────────────────────
function KpiCard({ baseValue, phase, decoPath }) {
  const t = useTime();
  const raw = baseValue + wave(t, 16, phase) * 1.3 + wave(t, 7, phase * 0.7) * 0.4;
  const display = Math.max(0, Math.round(raw));
  const sinceTickHint = Math.abs(Math.sin(raw * Math.PI));
  const ty = (1 - sinceTickHint) * -0.5;

  return (
    <div style={{
      position: 'relative',
      background: C.panel,
      border: `1px solid ${C.border}`,
      borderRadius: 20,
      padding: '18px 20px',
      height: 110,
      overflow: 'hidden',
      backdropFilter: 'blur(10px)',
      WebkitBackdropFilter: 'blur(10px)',
    }}>
      {/* Decorative gold line art, faint */}
      <div style={{
        position: 'absolute',
        right: -10, top: -10,
        opacity: 0.22,
        color: C.gold,
        transform: `rotate(${wave(t, 20, phase) * 2}deg)`,
      }}>
        <svg width="96" height="96" viewBox="0 0 24 24" fill="none"
             stroke={C.gold} strokeWidth="1" strokeLinecap="round" strokeLinejoin="round">
          {decoPath}
        </svg>
      </div>
      {/* Number */}
      <div style={{
        fontSize: 40, fontWeight: 500, color: '#fff',
        letterSpacing: '-0.03em',
        fontVariantNumeric: 'tabular-nums',
        transform: `translateY(${ty}px)`,
        fontFamily: "'Neue Haas Grotesk', -apple-system, BlinkMacSystemFont, sans-serif",
      }}>
        {display}
      </div>
      {/* Label pill */}
      <div style={{ marginTop: 10 }}>
        <Pill width={68 + (phase * 40 % 30)} height={7} color={C.pillBase} />
      </div>
      {/* Gold glow dot bottom-right */}
      <div style={{
        position: 'absolute', right: 14, bottom: 14,
        width: 28, height: 28, borderRadius: 999,
        background: C.goldSoft,
        border: `1px solid ${C.gold}55`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: `0 0 ${10 + wave01(t, 5, phase) * 8}px -2px ${C.goldGlow}`,
      }}>
        <div style={{ width: 8, height: 8, borderRadius: 999, background: C.gold, opacity: 0.9 }} />
      </div>
    </div>
  );
}

// ── Radar chart (gold palette) ──────────────────────────────────────────────
function RadarChart() {
  const t = useTime();
  const cx = 180, cy = 135, R = 92;
  const n = 6;
  const base = [0.62, 0.74, 0.58, 0.68, 0.55, 0.66];
  const values = base.map((b, i) =>
    clamp(b + wave(t, 9 + i * 0.8, i * 0.13) * 0.06 + wave(t, 14, i * 0.21) * 0.03, 0.1, 0.98)
  );

  const pointFor = (i, r) => {
    const angle = -Math.PI / 2 + (i / n) * Math.PI * 2;
    return [cx + Math.cos(angle) * R * r, cy + Math.sin(angle) * R * r];
  };
  const gridLevels = [0.25, 0.5, 0.75, 1.0];
  const polygon = values.map((v, i) => pointFor(i, v).join(',')).join(' ');

  return (
    <svg width="360" height="270" viewBox="0 0 360 270">
      <defs>
        <radialGradient id="radarFill" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor={C.gold} stopOpacity="0.45" />
          <stop offset="100%" stopColor={C.gold} stopOpacity="0.1" />
        </radialGradient>
      </defs>
      {gridLevels.map((lvl, li) => {
        const pts = Array.from({ length: n }, (_, i) => pointFor(i, lvl).join(',')).join(' ');
        return <polygon key={li} points={pts} fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="1" />;
      })}
      {Array.from({ length: n }).map((_, i) => {
        const [x, y] = pointFor(i, 1);
        return <line key={i} x1={cx} y1={cy} x2={x} y2={y} stroke="rgba(255,255,255,0.05)" strokeWidth="1" />;
      })}
      <polygon
        points={polygon}
        fill="url(#radarFill)"
        stroke={C.gold}
        strokeWidth="1.5"
        strokeLinejoin="round"
      />
      {values.map((v, i) => {
        const [x, y] = pointFor(i, v);
        const pulse = 2 + wave01(t, 3.5, i * 0.17) * 1.2;
        return <circle key={i} cx={x} cy={y} r={pulse} fill={C.goldLight} />;
      })}
      {/* axis label pills (rendered in HTML overlay via foreignObject) */}
      {Array.from({ length: n }).map((_, i) => {
        const [x, y] = pointFor(i, 1.22);
        const w = 22 + (i % 3) * 8;
        return (
          <rect key={i}
            x={x - w / 2} y={y - 3} width={w} height={6} rx="3"
            fill={C.pillBase} />
        );
      })}
    </svg>
  );
}

// ── Bar chart (gold bars) ──────────────────────────────────────────────────
function BarChart() {
  const t = useTime();
  const baseH = [108, 104, 100, 96, 92, 90, 86, 82];
  const barW = 28;
  const gap = 14;
  const startX = 24;
  const baseY = 180;

  return (
    <svg width="480" height="230" viewBox="0 0 480 230">
      <defs>
        <linearGradient id="barFill" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor={C.goldLight} stopOpacity="0.95" />
          <stop offset="100%" stopColor={C.gold} stopOpacity="0.75" />
        </linearGradient>
        <linearGradient id="barTop" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="#fff" stopOpacity="0.35" />
          <stop offset="100%" stopColor="#fff" stopOpacity="0" />
        </linearGradient>
      </defs>
      <line x1="12" y1={baseY + 1} x2="472" y2={baseY + 1} stroke="rgba(255,255,255,0.06)" />
      {baseH.map((bh, i) => {
        const h = bh + wave(t, 7 + i * 0.35, i * 0.19) * 4 + wave(t, 13, i * 0.11) * 2;
        const x = startX + i * (barW + gap);
        const shimmerPhase = ((t / LOOP) * baseH.length + i) % baseH.length;
        const shimmerBoost = shimmerPhase < 1 ? (1 - shimmerPhase) * 0.25 : 0;
        return (
          <g key={i}>
            <rect x={x} y={baseY - h} width={barW} height={h} rx={barW / 2}
                  fill="url(#barFill)" opacity={0.85 + shimmerBoost * 0.4} />
            <rect x={x} y={baseY - h} width={barW} height={Math.min(20, h)} rx={barW / 2}
                  fill="url(#barTop)" opacity="0.6" />
            {/* label pill under each bar */}
            <rect x={x + (barW - 14) / 2} y={baseY + 10} width="14" height="5" rx="2.5"
                  fill={C.pillBase} />
          </g>
        );
      })}
    </svg>
  );
}

// ── Card row (pill placeholders + progress) ─────────────────────────────────
function CardRow({ basePct, baseValue, phase, titleW, subW1, subW2, tagW, iconSeed = 0 }) {
  const t = useTime();
  const pct = clamp(basePct + wave(t, 11, phase) * 0.8 + wave(t, 19, phase * 0.6) * 0.3, 0, 100);
  const count = Math.round(baseValue + wave(t, 17, phase) * 1.1);

  return (
    <div style={{
      background: C.panel,
      border: `1px solid ${C.border}`,
      borderRadius: 20,
      padding: '16px 18px',
      display: 'flex', flexDirection: 'column', gap: 12,
      backdropFilter: 'blur(10px)',
      WebkitBackdropFilter: 'blur(10px)',
    }}>
      {/* Header: icon + title pill + tag pill */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{
          width: 30, height: 30, borderRadius: 999,
          background: C.goldSoft,
          border: `1px solid ${C.gold}55`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <div style={{ width: 10, height: 10, borderRadius: 999, background: C.gold }} />
        </div>
        <Pill width={titleW} height={9} color={C.pillStrong} />
        <div style={{ flex: 1 }} />
        <div style={{
          padding: '4px 10px',
          borderRadius: 999,
          background: C.goldSoft,
          border: `1px solid ${C.gold}44`,
        }}>
          <Pill width={tagW} height={6} color={C.pillGold} />
        </div>
      </div>

      {/* Subtitle: two stacked pills (varying width) */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, paddingLeft: 2 }}>
        <Pill width={subW1} height={6} color={C.pillBase} />
        <Pill width={subW2} height={6} color={C.pillSoft} />
      </div>

      {/* Progress bar (gold) */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 2 }}>
        <div style={{
          flex: 1, height: 5,
          background: 'rgba(255,255,255,0.05)',
          borderRadius: 999,
          overflow: 'hidden',
          position: 'relative',
        }}>
          <div style={{
            height: '100%',
            width: `${pct}%`,
            background: `linear-gradient(90deg, ${C.gold}, ${C.goldLight})`,
            borderRadius: 999,
            boxShadow: `0 0 10px ${C.goldGlow}`,
          }} />
          <div style={{
            position: 'absolute', top: 0, bottom: 0,
            left: `${((t * 5 + phase * 100) % 130) - 20}%`,
            width: '18%',
            background: 'linear-gradient(90deg, transparent, rgba(255,255,255,0.35), transparent)',
            pointerEvents: 'none',
          }} />
        </div>
        {/* tabular count rendered as a tiny number (kept for "live feel") */}
        <div style={{
          fontSize: 11, color: C.textMute, fontVariantNumeric: 'tabular-nums',
          minWidth: 28, textAlign: 'right',
          fontFamily: "'Neue Haas Grotesk', sans-serif",
        }}>{count}</div>
      </div>
    </div>
  );
}

// ── Top bar ────────────────────────────────────────────────────────────────
function TopBar() {
  const t = useTime();
  const pulse = 0.85 + wave01(t, 4) * 0.15;
  return (
    <div style={{
      height: 52,
      borderBottom: `1px solid ${C.border}`,
      display: 'flex', alignItems: 'center',
      padding: '0 22px',
      gap: 12,
      flexShrink: 0,
    }}>
      {/* Breadcrumb: icon dot + pill */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ width: 14, height: 14, borderRadius: 4, background: C.pillBase }} />
        <Pill width={96} height={8} color={C.pillStrong} />
      </div>
      <div style={{ flex: 1 }} />
      {/* Gold pill CTA button (matches index.html primary button aesthetic) */}
      <div style={{
        height: 34,
        padding: '0 16px',
        display: 'flex', alignItems: 'center', gap: 8,
        borderRadius: 999,
        background: '#0a0a0a',
        border: `1px solid ${C.gold}`,
        boxShadow: `0 0 ${14 * pulse}px -3px ${C.goldGlow}`,
        position: 'relative', overflow: 'hidden',
      }}>
        {/* Subtle inner gradient to match the hero CTA */}
        <div style={{
          position: 'absolute', inset: 0,
          background: `radial-gradient(80% 120% at 50% 120%, ${C.goldGlow}, transparent 60%)`,
          pointerEvents: 'none',
        }} />
        <div style={{
          width: 10, height: 10, borderRadius: 999,
          background: C.gold,
          position: 'relative',
        }} />
        <Pill width={70} height={7} color={C.pillGold} style={{ position: 'relative' }} />
      </div>
    </div>
  );
}

// ── Section panel ──────────────────────────────────────────────────────────
const Panel = ({ titleW, children, style }) => (
  <div style={{
    background: C.panel,
    border: `1px solid ${C.border}`,
    borderRadius: 22,
    padding: 20,
    display: 'flex', flexDirection: 'column',
    backdropFilter: 'blur(10px)',
    WebkitBackdropFilter: 'blur(10px)',
    ...style,
  }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
      <div style={{ width: 12, height: 12, borderRadius: 4, background: C.pillBase }} />
      <Pill width={titleW} height={8} color={C.pillStrong} />
    </div>
    <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      {children}
    </div>
  </div>
);

// ── Dashboard ──────────────────────────────────────────────────────────────
function Dashboard() {
  const t = useTime();
  const bgScale = 1 + wave(t, 18) * 0.003;
  const bgTy = wave(t, 22, 0.3) * 2;

  return (
    <div style={{
      width: '100%', height: '100%',
      display: 'flex',
      color: C.text,
      fontFamily: "'Neue Haas Grotesk', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
      background: C.bg,
      transform: `scale(${bgScale}) translateY(${bgTy}px)`,
      transformOrigin: 'center center',
    }}>
      <Sidebar />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
        <TopBar />
        <div style={{
          flex: 1, padding: 22,
          display: 'flex', flexDirection: 'column', gap: 18,
          overflow: 'hidden',
        }}>
          {/* KPI row */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 18 }}>
            <KpiCard baseValue={5} phase={0}
              decoPath={<><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></>} />
            <KpiCard baseValue={2} phase={0.25}
              decoPath={<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>} />
            <KpiCard baseValue={2} phase={0.5}
              decoPath={<path d="M22 12h-4l-3 9L9 3l-3 9H2"/>} />
            <KpiCard baseValue={3} phase={0.75}
              decoPath={<><path d="M9 18h6"/><path d="M10 22h4"/><path d="M12 2a7 7 0 0 0-4 12.7c.6.5 1 1.3 1 2.1V17h6v-.2c0-.8.4-1.6 1-2.1A7 7 0 0 0 12 2z"/></>} />
          </div>

          {/* Charts row */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.25fr', gap: 18, minHeight: 0 }}>
            <Panel titleW={120} style={{ minHeight: 290 }}>
              <RadarChart />
            </Panel>
            <Panel titleW={140} style={{ minHeight: 290 }}>
              <BarChart />
            </Panel>
          </div>

          {/* Card row */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18 }}>
            <CardRow basePct={76} baseValue={103} phase={0.1}
              titleW={58} subW1={120} subW2={86} tagW={42} />
            <CardRow basePct={71} baseValue={102} phase={0.35}
              titleW={64} subW1={132} subW2={72} tagW={56} />
            <CardRow basePct={86} baseValue={99} phase={0.6}
              titleW={82} subW1={108} subW2={94} tagW={48} />
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Background wrapper ─────────────────────────────────────────────────────
function BackgroundDashboard() {
  const tw = (typeof window !== 'undefined' && window.__TWEAKS) || { blur: 0, surface: 1, accent: 1, grid: false };

  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: C.bg,
      overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        filter: `blur(${tw.blur}px) saturate(${0.92 + tw.accent * 0.08})`,
        opacity: 0.94 * tw.surface,
      }}>
        <Dashboard />
      </div>

      {/* Gold ambient wash (matches index.html hero lighting) */}
      <div style={{
        position: 'absolute', inset: 0,
        pointerEvents: 'none',
        background:
          `radial-gradient(ellipse at 20% 10%, rgba(166,131,88,0.08), transparent 55%),` +
          `radial-gradient(ellipse at 85% 90%, rgba(166,131,88,0.06), transparent 55%),` +
          `radial-gradient(ellipse at 50% 50%, transparent 55%, rgba(0,0,0,0.45) 100%)`,
      }} />
      <div style={{
        position: 'absolute', left: 0, right: 0, top: 0, height: 140,
        background: 'linear-gradient(to bottom, rgba(255,255,255,0.02), transparent)',
        pointerEvents: 'none',
      }} />
    </div>
  );
}

Object.assign(window, { Dashboard, BackgroundDashboard, LOOP });
