// ui.jsx — shared presentational primitives
const { useState } = React;

function Avatar({ src, size = 38, ring }) {
  return <div className="avatar" style={{ width: size, height: size, backgroundImage: `url(${src})`, boxShadow: ring ? `0 0 0 2px #fff, 0 0 0 4px ${ring}` : undefined }} />;
}

function CatChip({ name }) {
  return <span className="cat-chip"><span className="cat-dot" style={{ background: window.catColor(name) }} />{name}</span>;
}

function StatusBadge({ status }) {
  const map = {
    pending: ['st-pending', 'Pending'], published: ['st-published', 'Published'],
    rejected: ['st-rejected', 'Rejected'], review: ['st-review', 'Under review'],
  };
  const [cls, lbl] = map[status] || map.pending;
  return <span className={`badge-status ${cls}`}>{lbl}</span>;
}

// statistic chips (upvote/downvote/comment/views). Interactive when onVote provided.
function StatChips({ idea, vote, onVote }) {
  const Icon = window.Icon;
  const up = idea.up + (vote === 'up' ? 1 : 0);
  const down = idea.down + (vote === 'down' ? 1 : 0);
  const stop = (e, dir) => { e.stopPropagation(); onVote && onVote(dir); };
  const iv = !!onVote; // interactive only when a handler is provided
  return (
    <div className={`stat-chips ${iv ? '' : 'static'}`} onClick={e => onVote && e.stopPropagation()}>
      <button className={`schip up ${vote === 'up' ? 'on' : ''}`} onClick={e => stop(e, 'up')} disabled={!iv} title="Upvote">
        <Icon name="thumbUp" size={15} />{window.fmt(up)}
      </button>
      <button className={`schip down ${vote === 'down' ? 'on' : ''}`} onClick={e => stop(e, 'down')} disabled={!iv} title="Downvote">
        <Icon name="thumbDown" size={15} />{window.fmt(down)}
      </button>
      <span className="schip comment"><Icon name="comment" size={15} />{idea.comments}</span>
      <span className="schip"><Icon name="eye" size={15} />{window.fmt(idea.views)}</span>
    </div>
  );
}

function StatCard({ s }) {
  const Icon = window.Icon;
  const down = s.trend < 0;
  return (
    <div className="stat">
      <div className="stat-top">
        <div className="stat-ic" style={{ background: s.tint + '18', color: s.tint }}><Icon name={s.icon} size={23} /></div>
        <span className={`stat-trend ${down ? 'trend-down' : 'trend-up'}`}>
          <Icon name={down ? 'trendDown' : 'trendUp'} size={13} />{Math.abs(s.trend)}%
        </span>
      </div>
      <div className="stat-num tnum">{s.value}</div>
      <div className="stat-lbl">{s.label}</div>
    </div>
  );
}

Object.assign(window, { Avatar, CatChip, StatusBadge, StatChips, StatCard });
