/* global React */
const { useState, useEffect, useMemo, useRef, useCallback } = React;

/* =====================================================================
   Icons — minimal stroked SVGs, no emoji
   ===================================================================== */
const Icon = ({ d, size = 16, strokeWidth = 1.8, fill = 'none', children, ...rest }) => (
  <svg
    xmlns="http://www.w3.org/2000/svg"
    width={size} height={size}
    viewBox="0 0 24 24"
    fill={fill}
    stroke="currentColor"
    strokeWidth={strokeWidth}
    strokeLinecap="round"
    strokeLinejoin="round"
    {...rest}
  >
    {children || (d ? <path d={d} /> : null)}
  </svg>
);

const Icons = {
  search: (p) => <Icon {...p}><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></Icon>,
  bell: (p) => <Icon {...p}><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10 21a2 2 0 0 0 4 0"/></Icon>,
  chevDown: (p) => <Icon {...p}><polyline points="6 9 12 15 18 9"/></Icon>,
  chevRight: (p) => <Icon {...p}><polyline points="9 6 15 12 9 18"/></Icon>,
  chevLeft: (p) => <Icon {...p}><polyline points="15 6 9 12 15 18"/></Icon>,
  layout: (p) => <Icon {...p}><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></Icon>,
  search2: (p) => <Icon {...p}><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></Icon>,
  list: (p) => <Icon {...p}><line x1="8" y1="6" x2="20" y2="6"/><line x1="8" y1="12" x2="20" y2="12"/><line x1="8" y1="18" x2="20" y2="18"/><circle cx="4" cy="6" r="1.2"/><circle cx="4" cy="12" r="1.2"/><circle cx="4" cy="18" r="1.2"/></Icon>,
  bolt: (p) => <Icon {...p}><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></Icon>,
  chart: (p) => <Icon {...p}><path d="M3 3v18h18"/><path d="M7 14l4-4 4 3 5-7"/></Icon>,
  users: (p) => <Icon {...p}><circle cx="9" cy="8" r="4"/><path d="M2 21a7 7 0 0 1 14 0"/><path d="M16 3.5a4 4 0 0 1 0 9"/><path d="M22 21a7 7 0 0 0-4-6.3"/></Icon>,
  gear: (p) => <Icon {...p}><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 1 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 1 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 1 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 1 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 1 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 1 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 1 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 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></Icon>,
  plus: (p) => <Icon {...p}><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></Icon>,
  filter: (p) => <Icon {...p}><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></Icon>,
  close: (p) => <Icon {...p}><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></Icon>,
  check: (p) => <Icon {...p} strokeWidth="3"><polyline points="20 6 9 17 4 12"/></Icon>,
  ext: (p) => <Icon {...p}><path d="M14 4h6v6"/><path d="M10 14 21 3"/><path d="M20 14v6a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h6"/></Icon>,
  amazon: (p) => <Icon {...p} fill="currentColor" stroke="none"><path d="M14.5 16.6c-2 1.4-4.8 2.2-7.2 2.2-3.4 0-6.4-1.2-8.7-3.3-.2-.2 0-.4.2-.3 2.5 1.5 5.5 2.3 8.7 2.3 2.2 0 4.6-.5 6.8-1.4.4-.2.7.2.2.5z M15.4 15.5c-.3-.3-1.7-.2-2.4-.1-.2 0-.2-.2-.1-.3 1.1-.8 3-.6 3.2-.3.2.3-.1 2.2-1.1 3.1-.2.1-.3.1-.2-.1.2-.4.9-1.9.6-2.3z M13 6.4V5.5c0-.1.1-.2.2-.2h4.4c.1 0 .2.1.2.2v.7c0 .1-.1.3-.3.5l-2.3 3.3c.8-.1 1.7 0 2.5.5.2.1.2.2.2.4v.9c0 .1-.1.3-.3.2-1.4-.7-3.2-.8-4.6 0-.2.1-.3 0-.3-.2v-.8c0-.2 0-.4.2-.6L15.5 7H13.2c-.1 0-.2-.1-.2-.2zM4.4 13c-.1 0-.2-.1-.2-.2V5.5c0-.1.1-.2.2-.2h2c.1 0 .2.1.2.2v1c.5-1.2 1.4-1.8 2.6-1.8s1.9.6 2.4 1.8c.5-1.2 1.6-1.8 2.7-1.8.8 0 1.7.3 2.2 1.1.6.8.5 2 .5 3v6.1c0 .1-.1.2-.2.2h-2.1c-.1 0-.2-.1-.2-.2V8c0-.4 0-1.4-.1-1.7-.1-.6-.5-.7-1-.7-.4 0-.9.3-1.1.8-.2.5-.2 1.3-.2 1.7v6.1c0 .1-.1.2-.2.2H9.7c-.1 0-.2-.1-.2-.2V8c0-1 .2-2.5-1.1-2.5s-1.2 1.4-1.2 2.5v6.1c0 .1-.1.2-.2.2h-2z"/></Icon>,
  cart: (p) => <Icon {...p}><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.7 13.4a2 2 0 0 0 2 1.6h9.7a2 2 0 0 0 2-1.6L23 6H6"/></Icon>,
  link: (p) => <Icon {...p}><path d="M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7"/><path d="M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7"/></Icon>,
  star: (p) => <Icon {...p} fill="currentColor"><polygon points="12 2 15 8.5 22 9.3 17 14.1 18.2 21 12 17.7 5.8 21 7 14.1 2 9.3 9 8.5 12 2"/></Icon>,
  starHalf: (p) => <Icon {...p}><polygon points="12 2 15 8.5 22 9.3 17 14.1 18.2 21 12 17.7 5.8 21 7 14.1 2 9.3 9 8.5 12 2" fill="currentColor" clipPath="inset(0 50% 0 0)"/></Icon>,
  starEmpty: (p) => <Icon {...p}><polygon points="12 2 15 8.5 22 9.3 17 14.1 18.2 21 12 17.7 5.8 21 7 14.1 2 9.3 9 8.5 12 2"/></Icon>,
  trash: (p) => <Icon {...p}><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></Icon>,
  tag: (p) => <Icon {...p}><path d="M20 12 12 20l-9-9V3h8z"/><circle cx="7.5" cy="7.5" r="1.4" fill="currentColor"/></Icon>,
  more: (p) => <Icon {...p}><circle cx="12" cy="6" r="1.4" fill="currentColor"/><circle cx="12" cy="12" r="1.4" fill="currentColor"/><circle cx="12" cy="18" r="1.4" fill="currentColor"/></Icon>,
  download: (p) => <Icon {...p}><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"/></Icon>,
  upload: (p) => <Icon {...p}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></Icon>,
  folder: (p) => <Icon {...p}><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"/></Icon>,
  columns: (p) => <Icon {...p}><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="9" y1="3" x2="9" y2="21"/><line x1="15" y1="3" x2="15" y2="21"/></Icon>,
  drag: (p) => <Icon {...p} fill="currentColor" stroke="none"><circle cx="9" cy="6" r="1.4"/><circle cx="9" cy="12" r="1.4"/><circle cx="9" cy="18" r="1.4"/><circle cx="15" cy="6" r="1.4"/><circle cx="15" cy="12" r="1.4"/><circle cx="15" cy="18" r="1.4"/></Icon>,
  edit: (p) => <Icon {...p}><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></Icon>,
  arrow: (p) => <Icon {...p}><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></Icon>,
  sun: (p) => <Icon {...p}><circle cx="12" cy="12" r="4"/><line x1="12" y1="2" x2="12" y2="4"/><line x1="12" y1="20" x2="12" y2="22"/><line x1="2" y1="12" x2="4" y2="12"/><line x1="20" y1="12" x2="22" y2="12"/><line x1="4.9" y1="4.9" x2="6.3" y2="6.3"/><line x1="17.7" y1="17.7" x2="19.1" y2="19.1"/><line x1="4.9" y1="19.1" x2="6.3" y2="17.7"/><line x1="17.7" y1="6.3" x2="19.1" y2="4.9"/></Icon>,
  moon: (p) => <Icon {...p}><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/></Icon>,
  bookmark: (p) => <Icon {...p}><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></Icon>,
  sort: (p) => <Icon {...p}><polyline points="6 4 12 4 18 4"/><polyline points="8 10 12 6 16 10"/><polyline points="8 14 12 18 16 14"/></Icon>,
  diamond: (p) => <Icon {...p} fill="currentColor" stroke="none"><polygon points="12 2 22 12 12 22 2 12"/></Icon>,
  dollar: (p) => <Icon {...p}><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></Icon>,
  trend: (p) => <Icon {...p}><polyline points="3 17 9 11 13 15 21 7"/><polyline points="14 7 21 7 21 14"/></Icon>,
  reset: (p) => <Icon {...p}><polyline points="1 4 1 10 7 10"/><path d="M3.5 15a9 9 0 1 0 2.1-9.4L1 10"/></Icon>,
  calendar: (p) => <Icon {...p}><rect x="3" y="4" width="18" height="18" rx="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"/></Icon>,
  video: (p) => <Icon {...p}><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2"/></Icon>,
  package: (p) => <Icon {...p}><path d="M16.5 9.4 7.5 4.21"/><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"/></Icon>,
  zap: (p) => <Icon {...p}><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></Icon>,
  arrowUp: (p) => <Icon {...p}><line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/></Icon>,
  arrowDown: (p) => <Icon {...p}><line x1="12" y1="5" x2="12" y2="19"/><polyline points="19 12 12 19 5 12"/></Icon>,
  copy: (p) => <Icon {...p}><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></Icon>,
  eye: (p) => <Icon {...p}><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"/></Icon>,
  minus: (p) => <Icon {...p} strokeWidth="3"><line x1="5" y1="12" x2="19" y2="12"/></Icon>,
  mail: (p) => <Icon {...p}><rect x="2" y="4" width="20" height="16" rx="2"/><polyline points="2,4 12,13 22,4"/></Icon>,
  kanban: (p) => <Icon {...p}><rect x="3" y="3" width="5" height="9" rx="1"/><rect x="3" y="15" width="5" height="6" rx="1"/><rect x="9.5" y="3" width="5" height="14" rx="1"/><rect x="16" y="3" width="5" height="6" rx="1"/><rect x="16" y="12" width="5" height="9" rx="1"/></Icon>,
  logout: (p) => <Icon {...p}><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></Icon>,
};

/* =====================================================================
   Atomic UI primitives
   ===================================================================== */
const Checkbox = ({ checked, indeterminate, onChange }) => (
  <span
    className="cbx"
    data-checked={checked ? "true" : "false"}
    data-indeterminate={indeterminate ? "true" : "false"}
    onClick={(e) => { e.stopPropagation(); onChange?.(!checked); }}
    role="checkbox"
    aria-checked={indeterminate ? "mixed" : checked}
  >
    {indeterminate ? <Icons.minus size={10}/> : <Icons.check size={10}/>}
  </span>
);

const Toggle = ({ on, onChange }) => (
  <span className="toggle" data-on={on ? "true" : "false"} onClick={() => onChange?.(!on)} />
);

const Field = ({ label, children }) => (
  <div className="field">
    <label className="field-label">{label}</label>
    {children}
  </div>
);

const Select = ({ value, onChange, options }) => (
  <select className="field-select" value={value} onChange={(e) => onChange?.(e.target.value)}>
    {options.map(o => <option key={o.value ?? o} value={o.value ?? o}>{o.label ?? o}</option>)}
  </select>
);

const NumPair = ({ values, onChange, placeholderA = "Min", placeholderB = "Max", suffix }) => (
  <div className="field-pair">
    <input
      type="text"
      className="field-input"
      placeholder={placeholderA}
      value={values?.[0] ?? ""}
      onChange={(e) => onChange?.([e.target.value, values?.[1] ?? ""])}
    />
    <input
      type="text"
      className="field-input"
      placeholder={placeholderB}
      value={values?.[1] ?? ""}
      onChange={(e) => onChange?.([values?.[0] ?? "", e.target.value])}
    />
  </div>
);

/* range slider for ratings (1-5) */
const RatingRange = ({ value, onChange }) => {
  // value: [min, max], 1..5 step 0.5
  const trackRef = useRef(null);
  const [dragging, setDragging] = useState(null); // 'a' | 'b' | null
  const min = 1, max = 5;
  const pct = (v) => ((v - min) / (max - min)) * 100;

  useEffect(() => {
    if (!dragging) return;
    const move = (e) => {
      const rect = trackRef.current.getBoundingClientRect();
      const x = (e.clientX ?? e.touches?.[0]?.clientX) - rect.left;
      const ratio = Math.min(1, Math.max(0, x / rect.width));
      const raw = min + ratio * (max - min);
      const snapped = Math.round(raw * 2) / 2;
      const next = [...value];
      if (dragging === 'a') next[0] = Math.min(snapped, value[1]);
      else next[1] = Math.max(snapped, value[0]);
      onChange?.(next);
    };
    const up = () => setDragging(null);
    window.addEventListener('mousemove', move);
    window.addEventListener('mouseup', up);
    return () => {
      window.removeEventListener('mousemove', move);
      window.removeEventListener('mouseup', up);
    };
  }, [dragging, value, onChange]);

  return (
    <div className="slider-wrap">
      <div className="slider-track" ref={trackRef} style={{ height: 6, marginTop: 14, marginBottom: 4 }}>
        <div
          className="slider-fill"
          style={{ left: `${pct(value[0])}%`, width: `${pct(value[1]) - pct(value[0])}%` }}
        />
        <div
          className="slider-handle"
          style={{ left: `${pct(value[0])}%` }}
          onMouseDown={() => setDragging('a')}
        />
        <div
          className="slider-handle"
          style={{ left: `${pct(value[1])}%` }}
          onMouseDown={() => setDragging('b')}
        />
      </div>
      <div className="slider-labels">
        <span>{value[0].toFixed(1)}★</span>
        <span style={{ color: 'var(--text-3)' }}>1.0 – 5.0</span>
        <span>{value[1].toFixed(1)}★</span>
      </div>
    </div>
  );
};

/* sparkline */
const Sparkline = ({ data, w = 90, h = 28, color = 'var(--accent)', glow = true }) => {
  const min = Math.min(...data), max = Math.max(...data);
  const range = max - min || 1;
  const stepX = w / (data.length - 1);
  const points = data.map((v, i) => `${i * stepX},${h - ((v - min) / range) * (h - 4) - 2}`).join(' ');
  const areaPoints = `0,${h} ${points} ${w},${h}`;
  const id = useMemo(() => `sg-${Math.random().toString(36).slice(2, 9)}`, []);
  return (
    <svg className="sparkline" width={w} height={h} viewBox={`0 0 ${w} ${h}`}>
      <defs>
        <linearGradient id={id} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.4" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      <polygon points={areaPoints} fill={`url(#${id})`} />
      <polyline
        points={points}
        fill="none"
        stroke={color}
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
        style={glow ? { filter: `drop-shadow(0 0 4px ${color})` } : null}
      />
    </svg>
  );
};

/* stars */
const Stars = ({ value, size = 12 }) => {
  const full = Math.floor(value);
  const half = value - full >= 0.25 && value - full < 0.75;
  const fillCount = half ? full : Math.round(value);
  return (
    <span className="stars">
      {[0,1,2,3,4].map(i => {
        const isFull = i < full;
        const isHalf = i === full && half;
        if (isFull) return <Icons.star key={i} size={size} />;
        if (isHalf) return (
          <span key={i} style={{ position: 'relative', display: 'inline-flex' }}>
            <Icons.starEmpty size={size} style={{ color: 'var(--text-3)' }} />
            <span style={{ position: 'absolute', inset: 0, width: '50%', overflow: 'hidden' }}>
              <Icons.star size={size} />
            </span>
          </span>
        );
        return <Icons.starEmpty key={i} size={size} style={{ color: 'var(--text-3)' }} />;
      })}
    </span>
  );
};

/* placeholder product image — a tinted gradient with item-specific glyph */
const ProductImage = ({ seed, label }) => {
  const hue = ((seed * 47) % 360);
  const initials = (label || "?").split(/[\s\-]/).filter(Boolean).slice(0, 2).map(s => s[0]).join('').toUpperCase();
  return (
    <div className="product-image" style={{
      background: `linear-gradient(140deg, oklch(0.55 0.16 ${hue}) 0%, oklch(0.32 0.10 ${(hue+30)%360}) 100%)`,
    }}>
      <span style={{ color: 'rgba(255,255,255,0.95)', fontSize: 11, fontWeight: 700, letterSpacing: '0.5px' }}>{initials}</span>
    </div>
  );
};

/* segmented control */
const Segmented = ({ value, onChange, options }) => (
  <div className="segmented">
    {options.map(o => (
      <button
        key={o.value}
        className={value === o.value ? "active" : ""}
        onClick={() => onChange?.(o.value)}
      >
        {o.icon ? <o.icon size={13} /> : null}
        {o.label}
      </button>
    ))}
  </div>
);

/* =====================================================================
   Sidebar
   ===================================================================== */
const Sidebar = ({ page, setPage, leadsCount, collapsed, setCollapsed }) => {
  const items = [
    { id: 'dashboard', icon: Icons.layout, label: 'Dashboard' },
    { id: 'leads', icon: Icons.bookmark, label: 'Leads', count: leadsCount },
    { id: 'flow', icon: Icons.kanban, label: 'Flow' },
    { id: 'search', icon: Icons.search2, label: 'Search', primary: true },
    { id: 'campaigns', icon: Icons.bolt, label: 'Campaigns' },
    { id: 'analytics', icon: Icons.chart, label: 'Analytics' },
    { id: 'connections', icon: Icons.users, label: 'Creator Connections' },
    { id: 'script', icon: Icons.video, label: 'Scripts' },
  ];
  const account = [
    { id: 'extension', icon: Icons.zap, label: 'Browser Extension' },
    { id: 'settings', icon: Icons.gear, label: 'Settings' },
  ];

  return (
    <aside className="sidebar" style={{ padding: collapsed ? '20px 8px' : undefined, overflow: 'hidden', transition: 'padding 0.2s' }}>
      {/* Brand row — logo + text + collapse toggle all inline */}
      <div className="brand" style={{ alignItems: 'center', marginBottom: 12, gap: collapsed ? 0 : undefined }}>
        <svg width="36" height="36" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ flexShrink: 0 }}>
          <defs>
            <linearGradient id="aip-logo-grad" x1="0" y1="0" x2="100" y2="100" gradientUnits="userSpaceOnUse">
              <stop offset="0%" stopColor="#62c3fc"/>
              <stop offset="100%" stopColor="#0069f4"/>
            </linearGradient>
          </defs>
          <circle cx="42" cy="42" r="30" stroke="url(#aip-logo-grad)" strokeWidth="9" fill="none"/>
          <rect x="26" y="26" width="9" height="9" rx="2" fill="url(#aip-logo-grad)"/>
          <rect x="37.5" y="26" width="9" height="9" rx="2" fill="url(#aip-logo-grad)"/>
          <rect x="49" y="26" width="9" height="9" rx="2" fill="url(#aip-logo-grad)"/>
          <rect x="26" y="37.5" width="9" height="9" rx="2" fill="url(#aip-logo-grad)"/>
          <rect x="37.5" y="37.5" width="9" height="9" rx="2" fill="url(#aip-logo-grad)"/>
          <rect x="49" y="37.5" width="9" height="9" rx="2" fill="url(#aip-logo-grad)"/>
          <rect x="26" y="49" width="9" height="9" rx="2" fill="url(#aip-logo-grad)"/>
          <rect x="37.5" y="49" width="9" height="9" rx="2" fill="url(#aip-logo-grad)"/>
          <rect x="49" y="49" width="9" height="9" rx="2" fill="url(#aip-logo-grad)"/>
          <line x1="64" y1="64" x2="88" y2="88" stroke="url(#aip-logo-grad)" strokeWidth="11" strokeLinecap="round"/>
        </svg>
        {!collapsed && (
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="brand-name">AIP Analyzer</div>
            <div className="brand-sub">v 0.4 · beta</div>
          </div>
        )}
        <button
          className="icon-btn"
          onClick={() => setCollapsed(c => !c)}
          title={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
          style={{ width: 26, height: 26, flexShrink: 0, marginLeft: collapsed ? 'auto' : 0 }}
        >
          {collapsed ? <Icons.chevRight size={12}/> : <Icons.chevLeft size={12}/>}
        </button>
      </div>

      {!collapsed && <div className="nav-section-label">Workspace</div>}
      {items.filter(it => !it.hidden).map(it => (
        <div
          key={it.id}
          className={`nav-item ${page === it.id ? 'active' : ''}`}
          onClick={() => setPage(it.id)}
          title={collapsed ? it.label : undefined}
          style={collapsed ? { justifyContent: 'center', padding: '9px 0' } : undefined}
        >
          <it.icon size={16} />
          {!collapsed && <span>{it.label}</span>}
          {!collapsed && it.count != null && <span className="nav-count">{it.count}</span>}
          {collapsed && it.count != null && it.count > 0 && (
            <span style={{ position: 'absolute', top: 4, right: 4, minWidth: 16, height: 16, borderRadius: 8, background: 'var(--accent)', color: '#000', fontSize: 9, fontWeight: 700, display: 'grid', placeItems: 'center' }}>{it.count}</span>
          )}
        </div>
      ))}

      {!collapsed && <div className="nav-section-label">Account</div>}
      {collapsed && <div style={{ height: 1, background: 'var(--line)', margin: '8px 4px' }}/>}
      {account.map(it => (
        <div
          key={it.id}
          className={`nav-item ${page === it.id ? 'active' : ''}`}
          onClick={() => setPage(it.id)}
          title={collapsed ? it.label : undefined}
          style={collapsed ? { justifyContent: 'center', padding: '9px 0' } : undefined}
        >
          <it.icon size={16} />
          {!collapsed && <span>{it.label}</span>}
        </div>
      ))}

      {!collapsed && (
        <div className="sidebar-footer">
          <div className="sidebar-footer-title">Chrome extension</div>
          <div className="sidebar-footer-text">Add products straight from Amazon. One‑click capture into any lead list.</div>
          <a className="sidebar-footer-cta" href="#"><Icons.download size={11}/> Install</a>
        </div>
      )}
    </aside>
  );
};

/* =====================================================================
   Topbar
   ===================================================================== */
const Topbar = ({ page, theme, setTheme, onSignOut }) => {
  const titles = {
    dashboard: ['Dashboard', 'Overview'],
    search: ['Workspace', 'Search'],
    leads: ['Workspace', 'Leads'],
    flow: ['Workspace', 'Flow'],
    campaigns: ['Workspace', 'Campaigns'],
    analytics: ['Workspace', 'Analytics'],
    connections: ['Workspace', 'Creator Connections'],
    import: ['Workspace', 'Import CC Data'],
    keepa: ['Workspace', 'Keepa Results'],
    extension: ['Account', 'Browser Extension'],
    settings: ['Account', 'Settings'],
  };
  const [parent, child] = titles[page] || ['Workspace', page];
  return (
    <div className="topbar">
      <div className="crumb">{parent} <span style={{ margin: '0 6px', color: 'var(--text-3)' }}>/</span> <b>{child}</b></div>

      <div className="search-global">
        <Icons.search size={14} />
        <input placeholder="Search anything — products, ASINs, lists, campaigns…" />
      </div>

      <button className="icon-btn" title="Toggle theme" onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}>
        {theme === 'dark' ? <Icons.sun size={16} /> : <Icons.moon size={16} />}
      </button>
      <button className="icon-btn" title="Notifications">
        <Icons.bell size={16} />
        <span className="dot" />
      </button>

      {onSignOut && (
        <button className="icon-btn" title="Sign out" onClick={onSignOut}>
          <Icons.logout size={16} />
        </button>
      )}

      <div className="user-chip">
        <div className="user-avatar">AIP</div>
        <div className="user-meta">
          <div className="name">My Account</div>
          <div className="role">Creator</div>
        </div>
      </div>
    </div>
  );
};

/* expose */
Object.assign(window, {
  Icons, Icon, Checkbox, Toggle, Field, Select, NumPair, RatingRange,
  Sparkline, Stars, ProductImage, Segmented, Sidebar, Topbar,
});
