// ── Theme tokens + shared primitives ──────────────────────────
const { useState, useRef, useEffect } = React;

const ACCENTS = {
  'مونوکروم': null,
  'بنفش':   '#6d4aff',
  'آبی':    '#2a6fdb',
  'سبز':    '#1f8a5b',
  'نارنجی': '#ff5a1f',
};

function makeTheme(dark, tw) {
  const accentColor = ACCENTS[tw.accent] || null;
  const accent = accentColor || (dark ? '#f5f5f5' : '#111111');
  const accentInk = accentColor ? '#ffffff' : (dark ? '#111111' : '#ffffff');
  const base = dark ? {
    '--bg': '#0b0b0b', '--surface': '#161616', '--surface-2': '#1f1f1f',
    '--ink': '#f5f5f5', '--ink-2': '#9a9a9a', '--ink-3': '#666666',
    '--line': 'rgba(255,255,255,0.10)', '--line-2': 'rgba(255,255,255,0.18)',
    '--field': '#202020',
  } : {
    '--bg': '#f4f4f3', '--surface': '#ffffff', '--surface-2': '#f0f0ef',
    '--ink': '#111111', '--ink-2': '#6e6e6e', '--ink-3': '#a8a8a6',
    '--line': 'rgba(17,17,17,0.08)', '--line-2': 'rgba(17,17,17,0.15)',
    '--field': '#f4f4f3',
  };
  const dens = tw.density === 'فشرده' ? { '--pad': '13px', '--gap': '9px' }
            : tw.density === 'راحت'   ? { '--pad': '20px', '--gap': '16px' }
            : { '--pad': '16px', '--gap': '12px' };
  return {
    ...base, ...dens,
    '--accent': accent, '--accent-ink': accentInk,
    '--r': (tw.radius ?? 18) + 'px',
    '--r-sm': Math.max(6, (tw.radius ?? 18) - 8) + 'px',
    '--font': "'Vazirmatn', sans-serif",
    fontFamily: "'Vazirmatn', sans-serif",
    fontFeatureSettings: "'tnum'",
  };
}

// monogram avatar
function Avatar({ mono, size = 42, sub }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%', flexShrink: 0,
      background: 'var(--surface-2)', border: '1px solid var(--line)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      color: 'var(--ink)', fontWeight: 700, fontSize: size * 0.4,
      position: 'relative',
    }}>
      {mono}
      {sub && <span style={{
        position: 'absolute', bottom: -2, left: -2, width: 14, height: 14,
        borderRadius: '50%', background: 'var(--accent)', color: 'var(--accent-ink)',
        fontSize: 9, fontWeight: 700, display: 'flex', alignItems: 'center',
        justifyContent: 'center', border: '2px solid var(--surface)',
      }}>{sub}</span>}
    </div>
  );
}

const STATUS = {
  open:     { label: 'باز',       fill: true },
  pending:  { label: 'در انتظار', ring: true },
  resolved: { label: 'حل‌شده',    mute: true },
};
function StatusDot({ status, size = 8 }) {
  const s = STATUS[status] || STATUS.open;
  return (
    <span style={{
      width: size, height: size, borderRadius: '50%', flexShrink: 0,
      background: s.fill ? 'var(--accent)' : s.mute ? 'var(--ink-3)' : 'transparent',
      border: s.ring ? '2px solid var(--ink-2)' : 'none',
      boxSizing: 'border-box', display: 'inline-block',
    }} />
  );
}

function Chip({ children, active, onClick, count }) {
  return (
    <button onClick={onClick} style={{
      font: 'inherit', fontSize: 13, fontWeight: 500, cursor: 'pointer',
      padding: '7px 14px', borderRadius: 999, whiteSpace: 'nowrap',
      background: active ? 'var(--accent)' : 'var(--surface)',
      color: active ? 'var(--accent-ink)' : 'var(--ink-2)',
      border: '1px solid ' + (active ? 'var(--accent)' : 'var(--line)'),
      display: 'inline-flex', alignItems: 'center', gap: 6,
      transition: 'all .15s', flexShrink: 0,
    }}>
      {children}
      {count != null && <span style={{
        fontSize: 11, opacity: active ? 0.8 : 0.6, fontWeight: 700,
      }}>{count}</span>}
    </button>
  );
}

function Tag({ children }) {
  return (
    <span style={{
      fontSize: 11, fontWeight: 500, color: 'var(--ink-2)',
      border: '1px solid var(--line-2)', borderRadius: 6,
      padding: '2px 8px', whiteSpace: 'nowrap',
    }}>{children}</span>
  );
}

function Card({ children, style, onClick, pad = true }) {
  return (
    <div onClick={onClick} style={{
      background: 'var(--surface)', borderRadius: 'var(--r)',
      border: '1px solid var(--line)',
      padding: pad ? 'var(--pad)' : 0,
      ...style,
    }}>{children}</div>
  );
}

function SectionLabel({ children, action }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      margin: '4px 2px 10px',
    }}>
      <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink-2)', letterSpacing: '.01em' }}>{children}</span>
      {action}
    </div>
  );
}

// up/down delta — monochrome, arrow conveys direction
function Delta({ value, suffix = '٪' }) {
  const up = value >= 0;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 2, fontSize: 11.5,
      fontWeight: 600, color: 'var(--ink-2)',
      padding: '2px 6px', borderRadius: 6, background: 'var(--surface-2)',
    }}>
      <Icon name={up ? 'arrow-up' : 'arrow-down'} size={11} sw={2.4} />
      {fa(Math.abs(value))}{suffix}
    </span>
  );
}

// sparkline
function Sparkline({ data, w = 70, h = 26 }) {
  const min = Math.min(...data), max = Math.max(...data);
  const rng = max - min || 1;
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = h - ((v - min) / rng) * (h - 4) - 2;
    return [x, y];
  });
  const d = pts.map((p, i) => (i ? 'L' : 'M') + p[0].toFixed(1) + ' ' + p[1].toFixed(1)).join(' ');
  const area = d + ` L${w} ${h} L0 ${h} Z`;
  return (
    <svg width={w} height={h} style={{ display: 'block', overflow: 'visible' }}>
      <path d={area} fill="var(--ink)" opacity="0.06" />
      <path d={d} fill="none" stroke="var(--ink)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="2.4" fill="var(--accent)" />
    </svg>
  );
}

Object.assign(window, {
  makeTheme, Avatar, StatusDot, STATUS, Chip, Tag, Card, SectionLabel, Delta, Sparkline, ACCENTS,
});
