// Shared UI primitives

const Card = ({ title, subtitle, action, children, className = "", padded = true, footer = null }) => (
  <div className={"card " + className}>
    {(title || action) && (
      <div className="card-hd">
        <div>
          {title && <div className="ttl">{title}</div>}
          {subtitle && <div className="sub">{subtitle}</div>}
        </div>
        {action}
      </div>
    )}
    <div className={padded ? "card-body" : ""}>{children}</div>
    {footer}
  </div>
);

const Badge = ({ tone = "neutral", children, dot = false }) => (
  <span className={"badge " + tone}>
    {dot && <span className="dot" />}
    {children}
  </span>
);

const StatusBadge = ({ status }) => {
  const map = {
    active: ['green', 'Active'],
    inactive: ['neutral', 'Inactive'],
    maintenance: ['amber', 'Maintenance'],
    decommissioned: ['neutral', 'Decommissioned'],
    pending: ['amber', 'Pending'],
    online: ['green', 'Online'],
    offline: ['neutral', 'Offline'],
    paid: ['green', 'Paid'],
    draft: ['neutral', 'Draft'],
    sent: ['blue', 'Sent'],
    pending_payment: ['amber', 'Pending Payment'],
    pending_verification: ['blue', 'Pending Verification'],
    overdue: ['red', 'Overdue'],
    disputed: ['red', 'Disputed'],
  };
  const [tone, label] = map[status] || ['neutral', status];
  return <Badge tone={tone} dot>{label}</Badge>;
};

const Button = ({ children, variant = "default", size = "", icon = null, onClick, type = "button", className = "" }) => (
  <button type={type} className={`btn ${variant} ${size} ${className}`} onClick={onClick}>
    {icon}{children}
  </button>
);

const Toggle = ({ on, onChange }) => (
  <div className="toggle" data-on={on} onClick={() => onChange && onChange(!on)}>
    <i />
  </div>
);

const TenantAvatar = ({ name, variant = "" }) => {
  const initials = (name || '?').split(/\s+/).slice(0, 2).map(s => s[0]).join('').toUpperCase();
  return <div className={"tenant-chip " + variant}><div className="av">{initials}</div></div>;
};

const TenantChip = ({ tenant, variant = "" }) => {
  const initials = (tenant?.name || '?').split(/\s+/).slice(0, 2).map(s => s[0]).join('').toUpperCase();
  return (
    <div className={"tenant-chip " + variant}>
      <div className="av">{initials}</div>
      <div className="meta">
        <div className="name">{tenant?.name}</div>
        {tenant?.contact && <div className="sub">{tenant.contact}</div>}
      </div>
    </div>
  );
};

// avatar variants spread deterministically
function tenantVariant(idx) {
  return ['', 'alt', 'alt2'][idx % 3];
}

const KPI = ({ label, value, unit, foot, trend, icon, tone = "" }) => (
  <div className={"kpi " + tone}>
    <div className="label">{label}</div>
    <div className="value">
      {value}{unit && <span className="unit">{unit}</span>}
    </div>
    {(foot || trend) && (
      <div className="foot">
        {trend && <span className={"trend " + trend.dir}>{trend.dir === 'up' ? '▲' : '▼'} {trend.value}</span>}
        {foot && <span>{foot}</span>}
      </div>
    )}
    {icon && <div className="icon">{icon}</div>}
  </div>
);

const PageHead = ({ title, subtitle, actions }) => (
  <div className="page-head">
    <div>
      <div className="title">{title}</div>
      {subtitle && <div className="subtitle">{subtitle}</div>}
    </div>
    {actions && <div className="actions">{actions}</div>}
  </div>
);

const Tabs = ({ tabs, active, onChange }) => (
  <div className="tabs">
    {tabs.map(t => (
      <button key={t.id} className="tab" data-on={active === t.id} onClick={() => onChange(t.id)}>
        {t.label}
        {t.count != null && <span className="count">{t.count}</span>}
      </button>
    ))}
  </div>
);

const Modal = ({ open, onClose, title, subtitle, size = "", children, footer }) => {
  if (!open) return null;
  return (
    <div className="scrim" onClick={e => e.target.classList.contains('scrim') && onClose()}>
      <div className={"modal " + size}>
        <div className="modal-hd">
          <div>
            <div className="ttl">{title}</div>
            {subtitle && <div className="sub">{subtitle}</div>}
          </div>
          <button className="btn ghost sm" onClick={onClose} aria-label="Close"><Icon.X size={16} /></button>
        </div>
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-ft">{footer}</div>}
      </div>
    </div>
  );
};

const Toast = ({ msg }) => msg ? (
  <div className="toast">
    <span className="ico"><Icon.Check size={14} /></span>
    {msg}
  </div>
) : null;

// Field
const Field = ({ label, hint, children, required }) => (
  <div className="fld">
    <label>{label}{required && <span style={{ color: 'var(--red-500)', marginLeft: 4 }}>*</span>}</label>
    {children}
    {hint && <div className="hint">{hint}</div>}
  </div>
);

// Connectivity dot + label
const ConnDot = ({ status }) => (
  <span style={{
    display: 'inline-flex', alignItems: 'center', gap: 6,
    fontSize: 12, color: status === 'online' ? 'var(--green-700)' : 'var(--ink-400)'
  }}>
    <span style={{
      width: 7, height: 7, borderRadius: '50%',
      background: status === 'online' ? 'var(--green-600)' : 'var(--ink-300)',
      boxShadow: status === 'online' ? '0 0 0 3px rgba(91,170,111,0.18)' : 'none'
    }} />
    {status === 'online' ? 'Online' : 'Offline'}
  </span>
);

// Format SDG currency
const fmtSDG = (n) => {
  if (n == null) return '—';
  return n.toLocaleString('en-US') + ' SDG';
};

const fmtNum = (n, decimals = 0) => {
  if (n == null) return '—';
  return n.toLocaleString('en-US', { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
};

Object.assign(window, {
  Card, Badge, StatusBadge, Button, Toggle, TenantAvatar, TenantChip, tenantVariant,
  KPI, PageHead, Tabs, Modal, Toast, Field, ConnDot, fmtSDG, fmtNum
});
