// Shared small components for Routing

const R = window.React;

// ── Status chips ──────────────────────────────────────────────────
const statusMeta = {
  en_ruta:      { label: 'En ruta',      bg: '#dcfce7', color: '#15803d' },
  completado:   { label: 'Completado',   bg: '#f0fdf4', color: '#166534' },
  programado:   { label: 'Programado',   bg: '#eff6ff', color: '#1d4ed8' },
  retrasado:    { label: 'Retrasado',    bg: '#fef9c3', color: '#854d0e' },
  disponible:   { label: 'Disponible',   bg: '#f0fdf4', color: '#15803d' },
  mantenimiento:{ label: 'Mantenimiento',bg: '#fff7ed', color: '#c2410c' },
  descanso:     { label: 'Descanso',     bg: '#f5f3ff', color: '#6d28d9' },
};

function Chip({ status, small }) {
  const m = statusMeta[status] || { label: status, bg: '#f3f4f6', color: '#374151' };
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      padding: small ? '2px 8px' : '3px 10px',
      borderRadius: 20, fontSize: small ? 11 : 12, fontWeight: 600,
      background: m.bg, color: m.color, whiteSpace: 'nowrap',
    }}>
      <span style={{ width: 6, height: 6, borderRadius: '50%', background: m.color, flexShrink: 0 }} />
      {m.label}
    </span>
  );
}

// ── Delay badge ───────────────────────────────────────────────────
function DelayBadge({ minutes }) {
  if (minutes == null) return null;
  if (minutes <= 0) return <span style={{ color: '#15803d', fontWeight: 600, fontSize: 12 }}>▲ {Math.abs(minutes)} min adelanto</span>;
  if (minutes > 90) return <span style={{ color: '#dc2626', fontWeight: 700, fontSize: 12 }}>▼ +{minutes} min retraso</span>;
  return <span style={{ color: '#d97706', fontWeight: 700, fontSize: 12 }}>▼ +{minutes} min retraso</span>;
}

// ── Stat card ─────────────────────────────────────────────────────
function StatCard({ label, value, sub, accent, icon, trend }) {
  return (
    <div style={{
      background: '#fff', borderRadius: 12, padding: '20px 22px',
      boxShadow: '0 1px 4px rgba(0,0,0,.06)', flex: 1, minWidth: 160,
      borderTop: `3px solid ${accent || '#10B981'}`,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div style={{ fontSize: 13, color: '#5a7366', fontWeight: 500, marginBottom: 8 }}>{label}</div>
        {icon && <span style={{ fontSize: 18, opacity: .55 }}>{icon}</span>}
      </div>
      <div style={{ fontSize: 32, fontWeight: 700, color: '#1a2e25', lineHeight: 1 }}>{value}</div>
      {sub && <div style={{ fontSize: 12, color: '#5a7366', marginTop: 6 }}>{sub}</div>}
      {trend != null && (
        <div style={{ fontSize: 12, marginTop: 4, color: trend >= 0 ? '#15803d' : '#dc2626', fontWeight: 600 }}>
          {trend >= 0 ? '↑' : '↓'} {Math.abs(trend)}% vs semana anterior
        </div>
      )}
    </div>
  );
}

// ── Section header ────────────────────────────────────────────────
function SectionHeader({ title, sub, action }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 16 }}>
      <div>
        <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700, color: '#1a2e25' }}>{title}</h2>
        {sub && <p style={{ margin: '2px 0 0', fontSize: 13, color: '#5a7366' }}>{sub}</p>}
      </div>
      {action}
    </div>
  );
}

// ── Mini progress bar ─────────────────────────────────────────────
function ProgressBar({ value, color, height }) {
  return (
    <div style={{ background: '#e8f0ec', borderRadius: 4, height: height || 6, overflow: 'hidden', width: '100%' }}>
      <div style={{ width: `${value}%`, height: '100%', background: color || '#10B981', borderRadius: 4, transition: 'width .4s' }} />
    </div>
  );
}

// ── Route arrow ───────────────────────────────────────────────────
function RouteArrow({ origin, destination }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 13, color: '#1a2e25' }}>
      <span style={{ fontWeight: 600 }}>{origin}</span>
      <span style={{ color: '#10B981', fontWeight: 700 }}>→</span>
      <span style={{ fontWeight: 600 }}>{destination}</span>
    </span>
  );
}

// ── Table wrapper ─────────────────────────────────────────────────
function Table({ headers, rows, onRowClick }) {
  return (
    <div style={{ background: '#fff', borderRadius: 12, boxShadow: '0 1px 4px rgba(0,0,0,.06)', overflow: 'hidden' }}>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr style={{ background: '#f7faf8', borderBottom: '1px solid #e4ede8' }}>
            {headers.map((h, i) => (
              <th key={i} style={{ padding: '11px 16px', textAlign: 'left', fontSize: 11, fontWeight: 700, color: '#5a7366', textTransform: 'uppercase', letterSpacing: '.06em', whiteSpace: 'nowrap' }}>{h}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((row, i) => (
            <tr key={i}
              onClick={() => onRowClick && onRowClick(i)}
              style={{ borderBottom: '1px solid #f0f4f2', cursor: onRowClick ? 'pointer' : 'default', transition: 'background .12s' }}
              onMouseEnter={e => onRowClick && (e.currentTarget.style.background = '#f7faf8')}
              onMouseLeave={e => (e.currentTarget.style.background = '')}
            >
              {row.map((cell, j) => (
                <td key={j} style={{ padding: '12px 16px', fontSize: 13, color: '#1a2e25', verticalAlign: 'middle' }}>{cell}</td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ── Button ────────────────────────────────────────────────────────
function Btn({ children, onClick, variant, small }) {
  const base = {
    border: 'none', borderRadius: 8, cursor: 'pointer', fontWeight: 600,
    padding: small ? '6px 14px' : '8px 18px', fontSize: small ? 12 : 13,
    transition: 'opacity .15s, box-shadow .15s', display: 'inline-flex', alignItems: 'center', gap: 6,
  };
  const styles = {
    primary:  { ...base, background: '#10B981', color: '#fff', boxShadow: '0 2px 8px rgba(16,185,129,.25)' },
    ghost:    { ...base, background: 'transparent', color: '#5a7366', border: '1px solid #dde8e2' },
    danger:   { ...base, background: '#fef2f2', color: '#dc2626', border: '1px solid #fecaca' },
  };
  const s = styles[variant || 'primary'];
  return <button style={s} onClick={onClick} onMouseEnter={e => (e.currentTarget.style.opacity='.82')} onMouseLeave={e => (e.currentTarget.style.opacity='1')}>{children}</button>;
}

// ── Input / filter ────────────────────────────────────────────────
function FilterInput({ placeholder, value, onChange, width }) {
  return (
    <input
      value={value} onChange={e => onChange(e.target.value)}
      placeholder={placeholder}
      style={{
        border: '1px solid #dde8e2', borderRadius: 8, padding: '7px 12px',
        fontSize: 13, color: '#1a2e25', background: '#fff', outline: 'none',
        width: width || 180,
      }}
    />
  );
}

function FilterSelect({ value, onChange, options }) {
  return (
    <select value={value} onChange={e => onChange(e.target.value)}
      style={{ border: '1px solid #dde8e2', borderRadius: 8, padding: '7px 12px', fontSize: 13, color: '#1a2e25', background: '#fff', outline: 'none', cursor: 'pointer' }}>
      {options.map((o, i) => <option key={i} value={o.value}>{o.label}</option>)}
    </select>
  );
}

// ── Empty state ───────────────────────────────────────────────────
function EmptyState({ message }) {
  return (
    <div style={{ padding: '48px 24px', textAlign: 'center', color: '#5a7366', fontSize: 14 }}>
      <div style={{ fontSize: 32, marginBottom: 12, opacity: .4 }}>○</div>
      {message}
    </div>
  );
}

// ── Page layout ───────────────────────────────────────────────────
function PageShell({ title, sub, actions, children }) {
  return (
    <div style={{ flex: 1, overflowY: 'auto', background: '#f0f4f2', padding: '28px 32px', fontFamily: 'inherit' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 22, fontWeight: 700, color: '#1a2e25' }}>{title}</h1>
          {sub && <p style={{ margin: '3px 0 0', fontSize: 13, color: '#5a7366' }}>{sub}</p>}
        </div>
        {actions && <div style={{ display: 'flex', gap: 10 }}>{actions}</div>}
      </div>
      {children}
    </div>
  );
}

Object.assign(window, { Chip, DelayBadge, StatCard, SectionHeader, ProgressBar, RouteArrow, Table, Btn, FilterInput, FilterSelect, EmptyState, PageShell, statusMeta });
