// Shared visual atoms used across all artboards.

const { MINISTRIES, TRUST } = window.DHAM;

// Tiny monk silhouette — abstract, head + shoulders + robe.
// size is total height in px; color = robe; accent = sash/ring.
function Monk({ size = 22, robe = '#D4A843', sash = '#F5A623', glow = null }) {
  const w = size * 0.62;
  const h = size;
  return (
    <svg width={w} height={h} viewBox="0 0 62 100" style={{ overflow: 'visible', filter: glow ? `drop-shadow(0 0 6px ${glow})` : undefined }}>
      {/* Halo / glow */}
      {glow && <circle cx="31" cy="22" r="16" fill={glow} opacity="0.18" />}
      {/* Head (bald) */}
      <circle cx="31" cy="22" r="11" fill={robe === '#E8E8E8' ? '#C9B99A' : '#C4A77A'} />
      {/* Robe body — trapezoid */}
      <path d="M14 96 L20 42 Q31 36 42 42 L48 96 Z" fill={robe} />
      {/* Inner shadow */}
      <path d="M20 42 Q31 38 42 42 L42 50 Q31 46 20 50 Z" fill="rgba(0,0,0,0.18)" />
      {/* Sash across chest */}
      <path d="M20 52 Q31 58 42 52 L42 58 Q31 64 20 58 Z" fill={sash} />
    </svg>
  );
}

// Round avatar — initials on ministry-colored ring, with status dot.
function Avatar({ agent, size = 36, showStatus = true, onClick = null }) {
  const m = MINISTRIES[agent.ministry] || { color: '#888' };
  const initials = agent.pali.split(' ').map((p) => p[0]).slice(0, 2).join('');
  const statusColor = agent.status === 'online' ? '#4ADE80' : agent.status === 'working' ? '#FBBF24' : '#6B7280';
  return (
    <div onClick={onClick} style={{ position: 'relative', width: size, height: size, flexShrink: 0, cursor: onClick ? 'pointer' : 'default' }}>
      <div style={{
        width: size, height: size, borderRadius: '50%',
        background: `linear-gradient(140deg, ${m.color}44, ${m.color}22)`,
        border: `1.5px solid ${m.color}`,
        color: 'var(--text)', fontWeight: 600,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: size * 0.34, letterSpacing: 0.4, fontFamily: 'var(--sans)',
      }}>{initials}</div>
      {showStatus && (
        <div style={{
          position: 'absolute', right: -1, bottom: -1,
          width: size * 0.28, height: size * 0.28, borderRadius: '50%',
          background: statusColor, border: '2px solid var(--surface)',
          boxShadow: agent.status === 'working' ? `0 0 6px ${statusColor}` : 'none',
          animation: agent.status === 'working' ? 'dham-pulse 1.6s infinite' : 'none',
        }} />
      )}
    </div>
  );
}

// Ministry tag chip.
function MinistryTag({ id, size = 'sm' }) {
  const m = MINISTRIES[id];
  if (!m) return null;
  const fs = size === 'sm' ? 10 : size === 'md' ? 11 : 12;
  const py = size === 'sm' ? 2 : 3;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      padding: `${py}px 7px`, borderRadius: 3,
      background: `${m.color}18`,
      color: m.color,
      fontSize: fs, fontWeight: 600, letterSpacing: 0.6, textTransform: 'uppercase',
      fontFamily: 'var(--mono)',
      border: `1px solid ${m.color}33`,
      whiteSpace: 'nowrap',
    }}>
      <span style={{ width: 5, height: 5, borderRadius: '50%', background: m.color }} />
      {m.short}
    </span>
  );
}

// Dharma stars — 5 dots, filled by trust level.
function DharmaStars({ level, size = 8 }) {
  return (
    <div style={{ display: 'flex', gap: 3 }}>
      {[0, 1, 2, 3, 4].map((i) => (
        <div key={i} style={{
          width: size, height: size,
          transform: 'rotate(45deg)',
          background: i <= level ? 'var(--gold)' : 'transparent',
          border: `1px solid ${i <= level ? 'var(--gold)' : 'var(--text-faint)'}`,
        }} />
      ))}
    </div>
  );
}

// Mini lotus glyph — 6 petals around a center.
function Lotus({ size = 14, color = 'currentColor', opacity = 1 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" style={{ opacity }}>
      {[0, 60, 120, 180, 240, 300].map((a) => (
        <ellipse key={a} cx="12" cy="6" rx="2.4" ry="5" fill={color} opacity="0.7" transform={`rotate(${a} 12 12)`} />
      ))}
      <circle cx="12" cy="12" r="1.6" fill={color} />
    </svg>
  );
}

// Section-header ornamental rule — thin line with a lotus in the middle.
function OrnamentRule({ color = 'var(--gold)' }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, color }}>
      <div style={{ flex: 1, height: 1, background: 'currentColor', opacity: 0.3 }} />
      <Lotus size={10} opacity={0.8} />
      <div style={{ flex: 1, height: 1, background: 'currentColor', opacity: 0.3 }} />
    </div>
  );
}

// Status pill.
function StatusPill({ status }) {
  const map = {
    online:  { c: 'var(--online)',  t: 'Online' },
    working: { c: 'var(--working)', t: 'Working' },
    offline: { c: 'var(--offline)', t: 'Offline' },
  };
  const { c, t } = map[status] || map.offline;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      fontSize: 10, fontFamily: 'var(--mono)', textTransform: 'uppercase', letterSpacing: 0.8,
      color: c,
    }}>
      <span style={{
        width: 6, height: 6, borderRadius: '50%', background: c,
        boxShadow: status === 'working' ? `0 0 6px ${c}` : 'none',
        animation: status === 'working' ? 'dham-pulse 1.6s infinite' : 'none',
      }} />
      {t}
    </span>
  );
}

// Sparkline — tiny inline chart.
function Sparkline({ data, width = 60, height = 18, color = 'var(--gold)' }) {
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = max - min || 1;
  const pts = data.map((v, i) => `${(i / (data.length - 1)) * width},${height - ((v - min) / range) * height}`).join(' ');
  return (
    <svg width={width} height={height} style={{ display: 'block' }}>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

// Chrome frame for every artboard — gives the dashboard viewport + top nav feel.
// activePage = 'map' | 'monitor' | 'kanban' | 'profile' | 'brain' | 'chat' | 'settings'
function AppChrome({ activePage, children, title, subtitle, rightSlot, padded = true }) {
  const pages = [
    { id: 'map', label: 'City Map' },
    { id: 'monitor', label: 'Live Monitor' },
    { id: 'kanban', label: 'Tasks' },
    { id: 'profile', label: 'Agents' },
    { id: 'brain', label: 'Citta · Brain' },
    { id: 'chat', label: 'Chat' },
    { id: 'settings', label: 'Settings' },
  ];
  return (
    <div className="dham-app" style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--base)', color: 'var(--text)', fontFamily: 'var(--sans)', overflow: 'hidden' }}>
      {/* Top bar */}
      <div style={{ display: 'flex', alignItems: 'center', padding: '14px 22px', borderBottom: '1px solid var(--line)', background: 'var(--surface-lo)', gap: 28, flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <Lotus size={22} color="var(--gold)" />
          <div>
            <div style={{ fontFamily: 'var(--thai)', fontSize: 15, fontWeight: 600, color: 'var(--gold)', letterSpacing: 0.2, lineHeight: 1 }}>ธัมมนคร</div>
            <div style={{ fontSize: 10, letterSpacing: 2, color: 'var(--text-dim)', marginTop: 3, fontFamily: 'var(--mono)' }}>DHAMMANAKHARA</div>
          </div>
        </div>
        <nav style={{ display: 'flex', gap: 2, fontSize: 12 }}>
          {pages.map((p) => (
            <div key={p.id} style={{
              padding: '7px 12px', borderRadius: 3, cursor: 'default',
              color: p.id === activePage ? 'var(--text)' : 'var(--text-dim)',
              background: p.id === activePage ? 'var(--surface)' : 'transparent',
              border: p.id === activePage ? '1px solid var(--line)' : '1px solid transparent',
              fontWeight: p.id === activePage ? 600 : 400,
            }}>{p.label}</div>
          ))}
        </nav>
        <div style={{ flex: 1 }} />
        {rightSlot}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, paddingLeft: 12, borderLeft: '1px solid var(--line)' }}>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 11, fontWeight: 600, lineHeight: 1.1 }}>You · Brahma</div>
            <div style={{ fontSize: 9, color: 'var(--text-dim)', fontFamily: 'var(--mono)', letterSpacing: 0.5 }}>ARAHANT · L4</div>
          </div>
          <div style={{ width: 28, height: 28, borderRadius: '50%', background: 'var(--gold)', color: 'var(--base)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700 }}>BR</div>
        </div>
      </div>
      {/* Page header */}
      {(title || subtitle) && (
        <div style={{ padding: '20px 28px 12px', flexShrink: 0 }}>
          {subtitle && <div style={{ fontSize: 10, letterSpacing: 2, color: 'var(--text-dim)', fontFamily: 'var(--mono)', textTransform: 'uppercase', marginBottom: 4 }}>{subtitle}</div>}
          {title && <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: -0.4 }}>{title}</div>}
        </div>
      )}
      <div style={{ flex: 1, overflow: 'hidden', padding: padded ? '0 28px 28px' : 0, display: 'flex', flexDirection: 'column' }}>{children}</div>
    </div>
  );
}

Object.assign(window, { Monk, Avatar, MinistryTag, DharmaStars, Lotus, OrnamentRule, StatusPill, Sparkline, AppChrome });
