/* Small shared UI primitives — buttons, chips, icons, etc. */

const Icon = ({ name, size = 14, color = 'currentColor', strokeWidth = 1.75 }) => {
  const s = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: color, strokeWidth, strokeLinecap: 'round', strokeLinejoin: 'round' };
  const paths = {
    home:     <><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2h-4a2 2 0 0 1-2-2v-5a2 2 0 0 0-2-2 2 2 0 0 0-2 2v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></>,
    mail:     <><rect x="3" y="5" width="18" height="14" rx="2"/><polyline points="3 7 12 13 21 7"/></>,
    file:     <><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></>,
    folder:   <><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></>,
    share:    <><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="11.49"/></>,
    users:    <><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></>,
    clock:    <><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></>,
    settings: <><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></>,
    bell:     <><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></>,
    search:   <><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></>,
    moon:     <><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></>,
    sun:      <><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></>,
    chevronDown: <><polyline points="6 9 12 15 18 9"/></>,
    chevronRight: <><polyline points="9 18 15 12 9 6"/></>,
    chevronLeft: <><polyline points="15 18 9 12 15 6"/></>,
    x:        <><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></>,
    plus:     <><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></>,
    check:    <><polyline points="20 6 9 17 4 12"/></>,
    calendar: <><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></>,
    filter:   <><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></>,
    package:  <><path d="M16.5 9.4l-9-5.19"/><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></>,
    refresh:  <><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></>,
    reset:    <><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></>,
    download: <><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></>,
    expand:   <><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></>,
    moreH:    <><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/></>,
    link:     <><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></>,
    bookmark: <><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></>,
    grid:     <><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></>,
    chart:    <><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></>,
    drag:     <><circle cx="9" cy="6" r="1"/><circle cx="9" cy="12" r="1"/><circle cx="9" cy="18" r="1"/><circle cx="15" cy="6" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="15" cy="18" r="1"/></>,
    eye:      <><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></>,
    eyeOff:   <><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></>,
    lock:     <><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></>,
    info:     <><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></>,
    arrowUp:  <><line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/></>,
    arrowDown: <><line x1="12" y1="5" x2="12" y2="19"/><polyline points="19 12 12 19 5 12"/></>,
    trending: <><polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/><polyline points="16 7 22 7 22 13"/></>,
    external:<><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></>,
    alert:    <><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></>,
  };
  return <svg {...s}>{paths[name] ?? null}</svg>;
};

const IconBtn = ({ name, title, onClick, size = 28, active }) => (
  <button title={title} onClick={onClick}
    style={{
      width: size, height: size, border: 0, borderRadius: 6,
      background: active ? 'var(--rc-hover)' : 'transparent',
      color: active ? 'var(--rc-text)' : 'var(--rc-text-sub)', cursor: 'pointer',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      transition: 'all 120ms ease',
    }}
    onMouseEnter={e => { if (!active) { e.currentTarget.style.background = 'var(--rc-hover)'; e.currentTarget.style.color = 'var(--rc-text)'; }}}
    onMouseLeave={e => { if (!active) { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--rc-text-sub)'; }}}
  ><Icon name={name} size={14} /></button>
);

const Pill = ({ children, tone = 'default', size = 'md' }) => {
  const tones = {
    default: { bg: 'var(--rc-chip-bg)', tx: 'var(--rc-text)', bd: 'var(--rc-border)' },
    green:   { bg: 'color-mix(in srgb, var(--rc-green) 10%, transparent)', tx: 'var(--rc-green-ink)', bd: 'color-mix(in srgb, var(--rc-green) 25%, transparent)' },
    red:     { bg: 'color-mix(in srgb, var(--rc-red) 10%, transparent)', tx: 'var(--rc-red)', bd: 'color-mix(in srgb, var(--rc-red) 25%, transparent)' },
    amber:   { bg: 'color-mix(in srgb, #f59e0b 12%, transparent)', tx: '#b45309', bd: 'color-mix(in srgb, #f59e0b 30%, transparent)' },
    dark:    { bg: 'var(--rc-ink)', tx: '#fff', bd: 'var(--rc-ink)' },
    ghost:   { bg: 'transparent', tx: 'var(--rc-text-sub)', bd: 'var(--rc-border)' },
  }[tone];
  const pad = size === 'sm' ? '2px 7px' : '3px 9px';
  const fs  = size === 'sm' ? 10 : 11;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      padding: pad, borderRadius: 6,
      background: tones.bg, color: tones.tx,
      border: `1px solid ${tones.bd}`,
      fontSize: fs, fontWeight: 500, lineHeight: 1.2,
      whiteSpace: 'nowrap',
    }}>{children}</span>
  );
};

const Segmented = ({ tabs, active, onChange, size = 'md' }) => {
  const pad = size === 'sm' ? '3px 9px' : '5px 11px';
  const fs  = size === 'sm' ? 11 : 12;
  return (
    <div style={{
      display: 'inline-flex', padding: 2, gap: 2,
      background: 'var(--rc-chip-bg)', border: '1px solid var(--rc-border)', borderRadius: 7,
    }}>
      {tabs.map(t => {
        const label = typeof t === 'string' ? t : t.label;
        const val = typeof t === 'string' ? t : t.value;
        const on = val === active;
        return (
          <button key={val} onClick={() => onChange && onChange(val)} style={{
            padding: pad, borderRadius: 5,
            background: on ? 'var(--rc-card)' : 'transparent',
            color: on ? 'var(--rc-text)' : 'var(--rc-text-sub)',
            fontSize: fs, fontWeight: 500, border: 0, cursor: 'pointer',
            boxShadow: on ? '0 1px 2px rgba(15,23,42,0.08)' : 'none',
            fontFamily: 'inherit', whiteSpace: 'nowrap',
          }}>{label}</button>
        );
      })}
    </div>
  );
};

const Btn = ({ children, variant = 'outline', icon, onClick, size = 'md', disabled, title }) => {
  const h = size === 'sm' ? 28 : 32;
  const pad = size === 'sm' ? '0 10px' : '0 12px';
  const fs = size === 'sm' ? 12 : 13;
  const styles = {
    primary: { bg: 'var(--rc-green)', color: '#fff', border: 'transparent' },
    outline: { bg: 'var(--rc-card)', color: 'var(--rc-text)', border: 'var(--rc-border)' },
    ghost:   { bg: 'transparent', color: 'var(--rc-text-sub)', border: 'transparent' },
    danger:  { bg: 'var(--rc-card)', color: 'var(--rc-red)', border: 'color-mix(in srgb, var(--rc-red) 30%, transparent)' },
  }[variant];
  return (
    <button onClick={onClick} disabled={disabled} title={title} style={{
      height: h, padding: pad, display: 'inline-flex', alignItems: 'center', gap: 6,
      background: styles.bg, color: styles.color, border: `1px solid ${styles.border}`, borderRadius: 7,
      fontSize: fs, fontWeight: 500, fontFamily: 'inherit', cursor: disabled ? 'not-allowed' : 'pointer',
      opacity: disabled ? 0.5 : 1, whiteSpace: 'nowrap', transition: 'all 120ms',
    }}>{icon && <Icon name={icon} size={13} />}{children}</button>
  );
};

const Card = ({ children, padding = 0, style = {} }) => (
  <div style={{
    background: 'var(--rc-card)',
    border: '1px solid var(--rc-border)',
    borderRadius: 12,
    boxShadow: '0 1px 2px rgba(15,23,42,0.04)',
    overflow: 'hidden',
    padding,
    ...style,
  }}>{children}</div>
);

const Checkbox = ({ checked, onChange, size = 15 }) => (
  <span onClick={onChange} style={{
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    width: size, height: size, borderRadius: 3, cursor: onChange ? 'pointer' : 'default',
    background: checked ? 'var(--rc-green)' : 'var(--rc-card)',
    border: `1px solid ${checked ? 'var(--rc-green)' : 'var(--rc-border)'}`,
    flexShrink: 0,
  }}>{checked && <Icon name="check" size={size - 5} color="#fff" strokeWidth={3} />}</span>
);

const Delta = ({ value, direction, size = 11 }) => {
  if (value == null || value === '—') return <span style={{ color: 'var(--rc-text-mute)', fontSize: size }}>—</span>;
  const color = direction === 'good' ? 'var(--rc-green-ink)' : direction === 'bad' ? 'var(--rc-negative)' : 'var(--rc-text-sub)';
  return <span style={{ color, fontSize: size, fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>{value}</span>;
};

/* RC-RPT-008 — ASIN cell: per-marketplace domain, hover thumbnail tooltip,
   target="_blank" rel="noopener noreferrer". Placeholder thumbnail is drawn
   from a seeded gradient so each ASIN looks distinct without external images. */
const MARKETPLACE_DOMAINS = {
  US: 'amazon.com', CA: 'amazon.ca', MX: 'amazon.com.mx',
  UK: 'amazon.co.uk', DE: 'amazon.de', FR: 'amazon.fr', IT: 'amazon.it', ES: 'amazon.es',
  JP: 'amazon.co.jp', AU: 'amazon.com.au', IN: 'amazon.in', BR: 'amazon.com.br',
};
const asinThumbColor = (asin) => {
  let h = 0;
  for (let i = 0; i < asin.length; i++) h = (h * 31 + asin.charCodeAt(i)) >>> 0;
  const hue = h % 360;
  const hue2 = (hue + 40 + (h >> 8) % 60) % 360;
  return { c1: `oklch(0.78 0.12 ${hue})`, c2: `oklch(0.62 0.14 ${hue2})` };
};
const AsinCell = ({ asin, name, marketplace = 'US', thumbnailUrl, disabled = false }) => {
  const [hovered, setHovered] = React.useState(false);
  const [coords, setCoords] = React.useState({ x: 0, y: 0 });
  const domain = MARKETPLACE_DOMAINS[marketplace] || MARKETPLACE_DOMAINS.US;
  const href = `https://www.${domain}/dp/${asin}`;
  const { c1, c2 } = asinThumbColor(asin);
  const handleEnter = (e) => {
    if (disabled) return;
    const r = e.currentTarget.getBoundingClientRect();
    setCoords({ x: r.right + 8, y: r.top });
    setHovered(true);
  };
  return (
    <span style={{ position: 'relative', display: 'inline-flex', alignItems: 'center', gap: 6 }}
      onMouseEnter={handleEnter} onMouseLeave={() => setHovered(false)}>
      <a href={disabled ? undefined : href} target="_blank" rel="noopener noreferrer"
        onClick={disabled ? (e) => e.preventDefault() : undefined}
        title={disabled ? 'View-only access' : `Open on ${domain}`}
        style={{
          display: 'inline-flex', alignItems: 'center', gap: 4,
          color: disabled ? 'var(--rc-text-mute)' : 'var(--rc-chart-1)',
          fontWeight: 500, textDecoration: 'none',
          fontVariantNumeric: 'tabular-nums', fontSize: 'inherit',
          cursor: disabled ? 'not-allowed' : 'pointer',
        }}
        onMouseOver={e => { if (!disabled) e.currentTarget.style.textDecoration = 'underline'; }}
        onMouseOut={e => e.currentTarget.style.textDecoration = 'none'}>
        {asin}
        <Icon name="external" size={10} />
      </a>
      {hovered && !disabled && (
        <div style={{
          position: 'fixed', left: coords.x, top: coords.y, zIndex: 300,
          background: 'var(--rc-card)', border: '1px solid var(--rc-border)',
          borderRadius: 10, boxShadow: '0 16px 40px -10px rgba(15,23,42,0.3)',
          padding: 10, width: 220, pointerEvents: 'none',
          display: 'flex', flexDirection: 'column', gap: 8,
        }}>
          <div style={{
            width: '100%', height: 120, borderRadius: 6,
            background: thumbnailUrl
              ? `center/contain no-repeat url(${thumbnailUrl}), var(--rc-subtle)`
              : `linear-gradient(135deg, ${c1}, ${c2})`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: 'rgba(255,255,255,0.9)', fontFamily: 'Poppins',
            fontWeight: 600, fontSize: 13, letterSpacing: 0.4,
            textShadow: '0 1px 2px rgba(0,0,0,0.25)',
          }}>
            {!thumbnailUrl && asin.slice(-4)}
          </div>
          {name && (
            <div style={{ fontSize: 11, color: 'var(--rc-text)', fontWeight: 500, lineHeight: 1.35 }}>
              {name}
            </div>
          )}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 10, color: 'var(--rc-text-sub)', fontVariantNumeric: 'tabular-nums' }}>
            <span>{domain}</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, color: 'var(--rc-chart-1)' }}>
              Open <Icon name="external" size={9} />
            </span>
          </div>
        </div>
      )}
    </span>
  );
};

Object.assign(window, { Icon, IconBtn, Pill, Segmented, Btn, Card, Checkbox, Delta, AsinCell, MARKETPLACE_DOMAINS });
