// trace-ui.jsx — Trace UI primitives, ported from the teaser kit
// (Trace UI Teaser (f)/trace-ui.jsx) for use in page-flow layouts rather
// than an absolutely-positioned video stage.
const clamp = (v, min, max) => Math.max(min, Math.min(max, v));

const TRACE = {
  bg:     '#F4EFE6',
  bgDark: '#0A122A',
  ink:    '#000000',
  inkDark:'#FCF7F8',
  panel:  '#FFFFFF',
  panel2: '#F6F0F2',
  hair:   'rgba(0,0,0,0.12)',
  hair2:  'rgba(0,0,0,0.06)',
  muted:  'rgba(0,0,0,0.78)',
  dim:    'rgba(0,0,0,0.58)',
  faint:  'rgba(0,0,0,0.32)',
  sky:    '#00A6FB',
  amber:  '#E3B23C',
  mauve:  '#775B59',
  grey:   '#9CA3AF',
  green:  '#16a34a',
  red:    '#dc2626',
  serif:  "'Canela', 'Tiempos Headline', 'GT Sectra', 'Cormorant Garamond', Georgia, 'Times New Roman', serif",
  sans:   "-apple-system, BlinkMacSystemFont, 'SF Pro Display', 'SF Pro Text', 'Inter', 'Helvetica Neue', Helvetica, Arial, sans-serif",
  mono:   "'SF Mono', 'JetBrains Mono', 'IBM Plex Mono', Menlo, Consolas, monospace",
};

// ── Wordmark: "TRACE." with cyan dot ───────────────────────────
function Wordmark({ size = 16, color, dotColor }) {
  const c = color || TRACE.ink;
  const dc = dotColor || TRACE.sky;
  return (
    <span style={{
      fontFamily: TRACE.sans,
      fontWeight: 600,
      letterSpacing: '0.32em',
      fontSize: size,
      textTransform: 'uppercase',
      color: c,
      display: 'inline-flex',
      alignItems: 'center',
    }}>
      TRACE
      <span style={{
        display: 'inline-block',
        width: size * 0.36,
        height: size * 0.36,
        borderRadius: '50%',
        background: dc,
        marginLeft: size * 0.28,
        transform: 'translateY(-1px)',
      }} />
    </span>
  );
}

// ── Eyebrow: tiny tracking-wide caps ────────────────────────────
function Eyebrow({ children, color, style }) {
  return (
    <div style={{
      fontFamily: TRACE.sans,
      fontSize: 11,
      letterSpacing: '0.18em',
      textTransform: 'uppercase',
      color: color || TRACE.muted,
      fontWeight: 500,
      ...style,
    }}>{children}</div>
  );
}

// ── DayArc: proportional day ring. Self-contained size, safe in flow. ──
function DayArc({ size = 320, segments = [], fill = 1, label, sublabel, ink = TRACE.ink, hair = TRACE.hair, hair2 = TRACE.hair2, dim = TRACE.dim, muted = TRACE.muted }) {
  const r = size / 2 - 14;
  const cx = size / 2, cy = size / 2;
  const rOuter = r - 2, rInner = r - 22;

  function arcPath(a0, a1) {
    const toXY = (a, rr) => [
      cx + rr * Math.cos((a * Math.PI) / 180),
      cy + rr * Math.sin((a * Math.PI) / 180),
    ];
    const large = a1 - a0 > 180 ? 1 : 0;
    const [x0o, y0o] = toXY(a0, rOuter);
    const [x1o, y1o] = toXY(a1, rOuter);
    const [x0i, y0i] = toXY(a0, rInner);
    const [x1i, y1i] = toXY(a1, rInner);
    return `M ${x0o} ${y0o} A ${rOuter} ${rOuter} 0 ${large} 1 ${x1o} ${y1o} L ${x1i} ${y1i} A ${rInner} ${rInner} 0 ${large} 0 ${x0i} ${y0i} Z`;
  }

  const totalFrac = segments.reduce((s, x) => s + x.frac, 0) || 1;
  const drawnEnd = clamp(fill, 0, 1) * 360;
  let cum = 0;
  const segs = segments.map((s) => {
    const a0 = (cum / totalFrac) * 360 - 90;
    cum += s.frac;
    const a1 = (cum / totalFrac) * 360 - 90;
    return { ...s, a0, a1 };
  });

  return (
    <div style={{ position: 'relative', width: size, height: size, flexShrink: 0 }}>
      <svg width={size} height={size} style={{ display: 'block' }}>
        <circle cx={cx} cy={cy} r={r} fill="none" stroke={hair} strokeWidth="1" />
        <circle cx={cx} cy={cy} r={r - 22} fill="none" stroke={hair2} strokeWidth="1" />
        {segs.map((s, i) => {
          const drawnA0 = -90;
          const visibleEnd = drawnA0 + drawnEnd;
          if (s.a0 >= visibleEnd) return null;
          const a1 = Math.min(s.a1, visibleEnd);
          if (a1 - s.a0 < 0.5) return null;
          return (
            <path
              key={i}
              d={arcPath(s.a0, a1)}
              fill={s.color}
              opacity={s.opacity != null ? s.opacity : 0.92}
            />
          );
        })}
      </svg>
      <div style={{
        position: 'absolute', inset: 0,
        display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center',
        pointerEvents: 'none',
      }}>
        {label && (
          <Eyebrow color={muted} style={{ marginBottom: 4 }}>{label}</Eyebrow>
        )}
        {sublabel && (
          <div style={{
            fontFamily: TRACE.serif,
            fontSize: size * 0.18,
            lineHeight: 1,
            letterSpacing: '-0.02em',
            color: ink,
          }}>
            {sublabel}
          </div>
        )}
      </div>
    </div>
  );
}

// ── MockWindow: macOS chrome. Renders in-flow (relative) by default;
// pass x/y only when the parent is an explicitly-sized relative box. ──
function MockWindow({ width, height, x, y, title, children, dark = false, scale = 1, opacity = 1, shadow = true, style }) {
  const bg = dark ? TRACE.bgDark : TRACE.bg;
  const ink = dark ? TRACE.inkDark : TRACE.ink;
  const hair = dark ? 'rgba(252,247,248,0.12)' : TRACE.hair;
  const positioned = x != null || y != null;
  return (
    <div style={{
      position: positioned ? 'absolute' : 'relative',
      left: x, top: y, width, height,
      borderRadius: 12, overflow: 'hidden',
      background: bg, color: ink,
      border: `1px solid ${hair}`,
      boxShadow: shadow ? '0 24px 80px rgba(0,0,0,0.18), 0 4px 12px rgba(0,0,0,0.06)' : 'none',
      transform: scale !== 1 ? `scale(${scale})` : undefined,
      transformOrigin: 'center',
      opacity,
      ...style,
    }}>
      {/* Title bar */}
      <div style={{
        height: 32, padding: '0 14px',
        display: 'flex', alignItems: 'center', gap: 6,
        borderBottom: `1px solid ${hair}`,
        background: dark ? 'rgba(255,255,255,0.02)' : 'rgba(0,0,0,0.015)',
        position: 'relative',
      }}>
        <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#FF5F56' }} />
        <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#FFBD2E' }} />
        <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#27C93F' }} />
        {title && (
          <div style={{
            position: 'absolute', left: 0, right: 0,
            textAlign: 'center', fontSize: 11,
            color: dark ? 'rgba(252,247,248,0.42)' : TRACE.dim,
            fontFamily: TRACE.sans, letterSpacing: '0.02em',
            pointerEvents: 'none',
          }}>{title}</div>
        )}
      </div>
      <div style={{ position: 'relative', width: '100%', height: 'calc(100% - 32px)', overflow: 'auto' }}>
        {children}
      </div>
    </div>
  );
}

// ── TraceSidebar: the actual sidebar from the app ──────────────
function TraceSidebar({ activeView = 'dashboard', onSelect, height, dark = false }) {
  const ink = dark ? TRACE.inkDark : TRACE.ink;
  const muted = dark ? 'rgba(252,247,248,0.66)' : TRACE.muted;
  const dim = dark ? 'rgba(252,247,248,0.42)' : TRACE.dim;
  const hair = dark ? 'rgba(252,247,248,0.12)' : TRACE.hair;
  const panel2 = dark ? '#161E42' : TRACE.panel2;
  const items = [
    { id: 'dashboard', label: 'Dashboard' },
    { id: 'timeline',  label: 'Timeline' },
    { id: 'projects',  label: 'Projects' },
    { id: 'rules',     label: 'Rules' },
    { id: 'settings',  label: 'Settings' },
  ];
  return (
    <div style={{
      width: 220, height,
      borderRight: `1px solid ${hair}`,
      display: 'flex', flexDirection: 'column',
      flexShrink: 0,
    }}>
      <div style={{
        padding: '24px 22px 22px',
        borderBottom: `1px solid ${hair}`,
      }}>
        <Wordmark size={13} color={ink} />
      </div>
      <nav style={{ padding: '16px 0', flex: 1 }}>
        {items.map(it => {
          const active = it.id === activeView;
          const clickable = !!onSelect;
          return (
            <div key={it.id}
              onClick={clickable ? () => onSelect(it.id) : undefined}
              style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '9px 14px',
                margin: '1px 8px',
                borderRadius: 10,
                fontSize: 13,
                color: active ? ink : muted,
                background: active ? panel2 : 'transparent',
                fontFamily: TRACE.sans,
                position: 'relative',
                cursor: clickable ? 'pointer' : 'default',
              }}>
              {active && (
                <span style={{
                  position: 'absolute', left: -8, top: '50%',
                  width: 3, height: 14, marginTop: -7,
                  background: TRACE.sky, borderRadius: 2,
                }} />
              )}
              <NavIcon name={it.id} color={active ? ink : muted} />
              <span>{it.label}</span>
            </div>
          );
        })}
      </nav>
      <div style={{
        padding: '16px 22px',
        borderTop: `1px solid ${hair}`,
        fontSize: 11, color: dim, fontFamily: TRACE.sans,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 4 }}>
          <span style={{
            width: 7, height: 7, borderRadius: '50%',
            background: TRACE.green,
            animation: 'pulse-soft 2.2s ease-in-out infinite',
          }} />
          <span style={{ color: ink }}>Tracking</span>
        </div>
        <div style={{ fontSize: 10.5, letterSpacing: '0.04em' }}>local · v0.1.0</div>
      </div>
    </div>
  );
}

function NavIcon({ name, color = TRACE.muted }) {
  const props = { width: 15, height: 15, fill: 'none', stroke: color, strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch (name) {
    case 'dashboard': return <svg viewBox="0 0 24 24" {...props}><rect x="3" y="3" width="7" height="9"/><rect x="14" y="3" width="7" height="5"/><rect x="14" y="12" width="7" height="9"/><rect x="3" y="16" width="7" height="5"/></svg>;
    case 'timeline':  return <svg viewBox="0 0 24 24" {...props}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>;
    case 'projects':  return <svg viewBox="0 0 24 24" {...props}><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z"/></svg>;
    case 'rules':     return <svg viewBox="0 0 24 24" {...props}><path d="M3 6h18M6 12h12M9 18h6"/></svg>;
    case 'settings':  return <svg viewBox="0 0 24 24" {...props}><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 1 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.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1 1.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.3h0a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 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.8v0a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>;
    default: return null;
  }
}

// ── Card: hairlined panel ──────────────────────────────────────
function Card({ children, padding = 16, dark = false, style, ...rest }) {
  const bg = dark ? '#11193A' : TRACE.panel;
  const hair = dark ? 'rgba(252,247,248,0.12)' : TRACE.hair;
  return (
    <div style={{
      background: bg,
      border: `1px solid ${hair}`,
      borderRadius: 10,
      padding,
      fontFamily: TRACE.sans,
      ...style,
    }} {...rest}>{children}</div>
  );
}

// ── Hairline ───────────────────────────────────────────────────
function Hairline({ color, style }) {
  return <div style={{
    height: 1, background: color || TRACE.hair, ...style,
  }} />;
}

// Sample project palette used across scenes and the live demo
const PROJECTS = [
  { id: 'acme',    client: 'Acme Corp.',   name: 'Brand refresh',     color: TRACE.sky },
  { id: 'north',   client: 'Northwind',    name: 'Q3 retainer',       color: TRACE.mauve },
  { id: 'lawful',  client: 'Hayes & Co.',  name: 'Discovery review',  color: TRACE.amber },
  { id: 'self',    client: 'Internal',     name: 'Admin · email',     color: TRACE.grey },
];

Object.assign(window, {
  TRACE, clamp, Wordmark, Eyebrow, DayArc, MockWindow, TraceSidebar,
  Card, Hairline, PROJECTS,
});
