/* Creative Preview =================================================== */

const CREATIVE_FORMATS = [
  { id:'image',    label:'Image'    },
  { id:'video',    label:'Video'    },
  { id:'carousel', label:'Carousel' },
  { id:'story',    label:'Story'    },
];

const CREATIVE_OBJECTIVES = [
  { id:'conversions', label:'Conversions' },
  { id:'traffic',     label:'Traffic'     },
  { id:'awareness',   label:'Awareness'   },
  { id:'installs',    label:'App Installs'},
  { id:'leads',       label:'Leads'       },
  { id:'engagement',  label:'Engagement'  },
];

const CREATIVE_STATUSES = [
  { id:'active',    label:'Active',     tone:'good'    },
  { id:'paused',    label:'Paused',     tone:'neutral' },
  { id:'review',    label:'In Review',  tone:'warn'    },
  { id:'learning',  label:'Learning',   tone:'info'    },
  { id:'rejected',  label:'Rejected',   tone:'bad'     },
];

const CREATIVE_SORTS = [
  { id:'spend_desc',  label:'Spend — highest first' },
  { id:'spend_asc',   label:'Spend — lowest first'  },
  { id:'roas_desc',   label:'ROAS — highest first', metric:'roas' },
  { id:'ctr_desc',    label:'CTR — highest first'   },
  { id:'imp_desc',    label:'Impressions — highest' },
  { id:'recent',      label:'Most recently updated' },
];
/* sorts visible for the active account (per-account metric blocklist) */
const creativeSorts = ()=> CREATIVE_SORTS.filter(s=>!s.metric ||
  !(typeof metricHiddenHere==='function' && metricHiddenHere(s.metric)));
const _crGrid = ()=> (typeof metricHiddenHere==='function' && metricHiddenHere('roas'))
  ? '56px 1fr 100px 110px 110px 90px 90px 90px'
  : '56px 1fr 100px 110px 110px 90px 90px 90px 90px';

/* ---------- Map live creatives → card shape ----------------------- */
/* Metrics are real (from the warehouse); only presentational props
   (aspect ratio, placeholder pattern) are derived for rendering. */
function buildCreatives(accountId, platformId){
  const list = getCreatives(accountId, platformId || 'overview');
  const aspects = { image:'4/5', video:'1/1', carousel:'1/1', story:'9/16' };
  return list.map((c, i) => ({
    id: c.id,
    name: c.name,
    platform: c.platform,
    format: c.format,
    aspect: aspects[c.format] || '1/1',
    objective: c.objective || 'conversions',
    status: c.status,
    headline: c.name,
    cta: 'Learn more',
    bodyText: '',
    spend: c.spend, ctr: c.ctr, cpm: c.cpm, imp: c.impressions,
    clicks: c.clicks, conv: c.conv, cpa: c.cpa, roas: c.roas,
    updated: '',
    pattern: ['blob','grid','rings','diag','dots','bars'][i % 6],
    hue: (i*37) % 360,
    thumb: c.thumb,
  }));
}

function mulberryFor(seed){
  let s = (typeof seed === 'string') ? seed.split('').reduce((a,c)=>a + c.charCodeAt(0), 0) * 91 : seed;
  return function(){
    s = (s + 0x6D2B79F5) | 0;
    let t = Math.imul(s ^ (s >>> 15), s | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

/* ---------- Creative Thumbnail SVG (placeholder ad rendering) ----- */
function CreativeThumb({ c, status }){
  const tone = (PLATFORMS.find(p=>p.id===c.platform)||PLATFORMS[0]).tone;
  const isDimmed = status === 'paused' || status === 'rejected';
  const id = useMemo(()=>'cr'+Math.random().toString(36).slice(2,8), []);

  // 6 distinct visual treatments to differentiate creatives
  const PatternBg = ({ kind }) => {
    if (kind==='blob') return (
      <>
        <circle cx="30%" cy="35%" r="42%" fill={tone} opacity="0.92"/>
        <circle cx="80%" cy="80%" r="30%" fill="white" opacity="0.18"/>
      </>
    );
    if (kind==='grid') return (
      <>
        <pattern id={id+'p'} width="14" height="14" patternUnits="userSpaceOnUse">
          <path d="M14 0H0V14" fill="none" stroke="white" strokeOpacity="0.15"/>
        </pattern>
        <rect width="100%" height="100%" fill={tone}/>
        <rect width="100%" height="100%" fill={`url(#${id+'p'})`}/>
      </>
    );
    if (kind==='rings') return (
      <>
        <rect width="100%" height="100%" fill={tone}/>
        <circle cx="100%" cy="0" r="60%" fill="none" stroke="white" strokeOpacity="0.18" strokeWidth="14"/>
        <circle cx="100%" cy="0" r="42%" fill="none" stroke="white" strokeOpacity="0.22" strokeWidth="10"/>
        <circle cx="100%" cy="0" r="22%" fill="white" opacity="0.18"/>
      </>
    );
    if (kind==='diag') return (
      <>
        <linearGradient id={id+'g'} x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" stopColor={tone} stopOpacity="1"/>
          <stop offset="100%" stopColor="#111" stopOpacity="0.85"/>
        </linearGradient>
        <rect width="100%" height="100%" fill={`url(#${id+'g'})`}/>
        <path d="M0,70 L100,30 L100,100 L0,100 Z" transform="scale(1,1)" fill="white" opacity="0.08"/>
      </>
    );
    if (kind==='dots') return (
      <>
        <rect width="100%" height="100%" fill={tone}/>
        <pattern id={id+'d'} x="0" y="0" width="12" height="12" patternUnits="userSpaceOnUse">
          <circle cx="6" cy="6" r="1.4" fill="white" fillOpacity="0.28"/>
        </pattern>
        <rect width="100%" height="100%" fill={`url(#${id+'d'})`}/>
      </>
    );
    /* bars */
    return (
      <>
        <rect width="100%" height="100%" fill={tone}/>
        {Array.from({length:6}).map((_,i)=>(
          <rect key={i} x={`${i*20-10}%`} y="-10%" width="6%" height="160%" fill="white" opacity="0.10" transform={`rotate(15 ${i*20} 50)`} />
        ))}
      </>
    );
  };

  return (
    <div className="relative w-full overflow-hidden rounded-xl bg-ink-100 dark:bg-ink-800 group/thumb" style={{aspectRatio:c.aspect}}>
      {c.thumb
        ? <img src={c.thumb} alt={c.name} className="absolute inset-0 w-full h-full object-cover"/>
        : <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid slice" className="absolute inset-0 w-full h-full">
            <defs></defs>
            <PatternBg kind={c.pattern}/>
          </svg>}

      {/* placeholder marker (subtle) */}
      <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
        <span className="text-white/30 font-mono text-[10px] uppercase tracking-[0.3em]">creative · {c.format}</span>
      </div>

      {/* Top row: format chip + status */}
      <div className="absolute top-2 left-2 right-2 flex items-start justify-between">
        <div className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md bg-black/35 backdrop-blur text-white text-[10px] font-mono uppercase tracking-wide">
          {c.format==='video' && <Icon name="play" size={9}/>}
          {c.format==='carousel' && <Icon name="columns" size={9}/>}
          {c.format==='story' && <Icon name="eye" size={9}/>}
          {c.format==='image' && <Icon name="dot" size={6}/>}
          {c.format}
        </div>
        <PlatformChip p={c.platform} size={20}/>
      </div>

      {/* Headline (ad copy) */}
      <div className="absolute left-2.5 right-2.5 bottom-12 text-white drop-shadow-[0_1px_4px_rgba(0,0,0,0.45)]">
        <div className="text-[13.5px] font-bold leading-tight">{c.headline}</div>
      </div>

      {/* CTA + brand */}
      <div className="absolute bottom-2 left-2 right-2 flex items-center justify-between">
        <span className="px-2.5 py-1 bg-white text-ink-900 text-[10.5px] font-bold rounded-full shadow-sm">{c.cta} →</span>
        <span className="text-[9px] font-mono text-white/80 uppercase">sponsored</span>
      </div>

      {/* Dim overlay if paused/rejected */}
      {isDimmed && <div className="absolute inset-0 bg-black/40 backdrop-blur-[1px]"/>}
    </div>
  );
}

/* ---------- Filter pill with active count ------------------------- */
function FilterPill({ label, count, onClick, active, icon }){
  return (
    <button onClick={onClick}
      className={`inline-flex items-center gap-1.5 h-8 px-2.5 rounded-lg border text-[12px] font-medium transition
        ${active
          ? 'bg-accent-50 border-accent-300 text-accent-700 dark:bg-accent-500/15 dark:border-accent-500/40 dark:text-accent-200'
          : 'border-ink-200 hover:bg-ink-100 dark:border-white/10 dark:hover:bg-white/5 text-ink-700 dark:text-ink-200'}`}>
      {icon && <Icon name={icon} size={12}/>}
      {label}
      {count > 0 && (
        <span className={`inline-flex items-center justify-center min-w-[16px] h-[16px] px-1 rounded text-[10px] font-mono font-bold
          ${active ? 'bg-accent-200 text-accent-800 dark:bg-accent-500/40 dark:text-accent-100' : 'bg-ink-100 dark:bg-white/10'}`}>{count}</span>
      )}
      <Icon name="chev-down" size={10} className="opacity-50"/>
    </button>
  );
}

/* Multi-select dropdown content */
function MultiOptionList({ options, selected, onToggle, allLabel='All' }){
  return (
    <div className="py-1">
      {options.map(opt => {
        const checked = selected.includes(opt.id);
        return (
          <button key={opt.id} onClick={()=>onToggle(opt.id)}
            className="w-full flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-ink-100 dark:hover:bg-white/5 text-[12.5px]">
            <span className={`w-3.5 h-3.5 rounded border flex items-center justify-center transition
              ${checked?'bg-accent-500 border-accent-500':'border-ink-300 dark:border-white/20'}`}>
              {checked && <Icon name="check" size={10} className="text-white"/>}
            </span>
            <span className="flex-1 text-left">{opt.label}</span>
          </button>
        );
      })}
    </div>
  );
}

/* ---------- Creative card ----------------------------------------- */
function CreativeCard({ c, selectable, selected, onToggleSelect }){
  const status = CREATIVE_STATUSES.find(s=>s.id===c.status) || { label:c.status, tone:'neutral' };
  return (
    <div className={`group relative rounded-2xl border bg-white dark:bg-ink-900/60 overflow-hidden shadow-card hover:shadow-float transition flex flex-col
      ${selected ? 'border-accent-400 dark:border-accent-500/60 ring-2 ring-accent-100 dark:ring-accent-500/20' : 'border-ink-200 dark:border-white/10'}`}>
      {/* Select checkbox */}
      {selectable && (
        <button onClick={(e)=>{e.stopPropagation(); onToggleSelect();}}
          className={`absolute top-3 left-3 z-10 w-5 h-5 rounded-md border-2 grid place-items-center transition
            ${selected
              ? 'bg-accent-500 border-accent-500 text-white'
              : 'bg-white/85 backdrop-blur border-white/80 dark:bg-black/30 dark:border-white/40 opacity-0 group-hover:opacity-100 hover:border-accent-400'}`}>
          {selected && <Icon name="check" size={12}/>}
        </button>
      )}
      <div className="p-2 cursor-pointer" onClick={()=>selectable && onToggleSelect()}>
        <CreativeThumb c={c} status={c.status}/>
      </div>
      <div className="px-3 pb-3 pt-1 flex-1 flex flex-col">
        <div className="flex items-center justify-between gap-2">
          <div className="text-[12px] font-mono text-ink-400 truncate">{c.name}</div>
          <Pill tone={status.tone}>
            {c.status==='active' && <LiveDot tone="#10b981" size={6}/>}
            {status.label}
          </Pill>
        </div>
        <div className="mt-1.5 flex items-center gap-2 text-[10.5px] text-ink-500 dark:text-ink-300 font-mono uppercase">
          <span>{(CREATIVE_OBJECTIVES.find(o=>o.id===c.objective)||{label:c.objective}).label}</span>
          <span className="text-ink-300">·</span>
          <span>{c.updated}</span>
        </div>
        <div className="mt-3 grid grid-cols-4 gap-2 text-[11px]">
          <div>
            <div className="text-ink-400 dark:text-ink-400 text-[10px] uppercase font-semibold tracking-wide">Spend</div>
            <div className="font-mono tabular font-semibold mt-0.5">{curPrefix()}{(c.spend/1000).toFixed(1)}k</div>
          </div>
          <div>
            <div className="text-ink-400 dark:text-ink-400 text-[10px] uppercase font-semibold tracking-wide">CTR</div>
            <div className="font-mono tabular font-semibold mt-0.5">{c.ctr}%</div>
          </div>
          <div>
            <div className="text-ink-400 dark:text-ink-400 text-[10px] uppercase font-semibold tracking-wide">CPM</div>
            <div className="font-mono tabular font-semibold mt-0.5">{curPrefix()}{c.cpm}</div>
          </div>
          {!(typeof metricHiddenHere==='function' && metricHiddenHere('roas')) && (
          <div>
            <div className="text-ink-400 dark:text-ink-400 text-[10px] uppercase font-semibold tracking-wide">ROAS</div>
            <div className={`font-mono tabular font-semibold mt-0.5 ${c.roas>=2.5?'text-emerald-600 dark:text-emerald-400':c.roas<1.5?'text-rose-600 dark:text-rose-400':''}`}>{c.roas}×</div>
          </div>
          )}
        </div>
        <div className="mt-3 pt-3 border-t border-ink-100 dark:border-white/5 flex items-center justify-between">
          <div className="text-[10.5px] text-ink-400 font-mono">{(c.imp/1000).toFixed(0)}k imp · {c.conv} conv</div>
          <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition">
            <button className="h-6 w-6 grid place-items-center rounded hover:bg-ink-100 dark:hover:bg-white/10 text-ink-500" title="View"><Icon name="eye" size={12}/></button>
            <button className="h-6 w-6 grid place-items-center rounded hover:bg-ink-100 dark:hover:bg-white/10 text-ink-500" title="More"><Icon name="menu-dots" size={12}/></button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- Creative row (list view) ------------------------------ */
function CreativeRow({ c }){
  const status = CREATIVE_STATUSES.find(s=>s.id===c.status) || { label:c.status, tone:'neutral' };
  return (
    <div className="grid items-center gap-3 px-3 py-2.5 border-t border-ink-100 dark:border-white/5 hover:bg-ink-50 dark:hover:bg-white/[0.03] transition text-[13px]"
      style={{ gridTemplateColumns:_crGrid() }}>
      <div className="w-14"><CreativeThumb c={{...c, aspect:'1/1'}} status={c.status}/></div>
      <div>
        <div className="font-medium truncate">{c.headline}</div>
        <div className="text-[10.5px] text-ink-500 font-mono uppercase">{c.name} · {c.format}</div>
      </div>
      <div><PlatformChip p={c.platform}/></div>
      <div className="text-[11.5px]">{(CREATIVE_OBJECTIVES.find(o=>o.id===c.objective)||{label:c.objective}).label}</div>
      <div><Pill tone={status.tone}>{status.label}</Pill></div>
      <div className="text-right tabular font-mono">{fmt(c.spend,'currency')}</div>
      <div className="text-right tabular font-mono">{c.ctr}%</div>
      {!(typeof metricHiddenHere==='function' && metricHiddenHere('roas')) &&
        <div className="text-right tabular font-mono">{c.roas}×</div>}
      <div className="text-right tabular font-mono">{(c.imp/1000).toFixed(0)}k</div>
    </div>
  );
}

/* ---------- Filter dropdown popover ------------------------------ */
function FilterDropdown({ label, options, selected, onChange, icon }){
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useOutsideClick(ref, ()=>setOpen(false));
  const toggle = (id) => {
    onChange(selected.includes(id) ? selected.filter(x=>x!==id) : [...selected, id]);
  };
  return (
    <div className="relative" ref={ref}>
      <div onClick={()=>setOpen(o=>!o)}>
        <FilterPill label={label} count={selected.length} active={selected.length>0} icon={icon}/>
      </div>
      {open && (
        <div className="absolute z-30 mt-1.5 left-0 w-56 origin-top-left rounded-xl border border-ink-200 dark:border-white/10 bg-white dark:bg-ink-800 shadow-float p-1 animate-dropin">
          <MultiOptionList options={options} selected={selected} onToggle={toggle}/>
          <div className="border-t border-ink-100 dark:border-white/5 mt-1 pt-1 flex items-center justify-between px-1.5">
            <button onClick={()=>onChange([])} className="text-[11px] text-ink-500 hover:text-ink-900 dark:hover:text-white">Clear</button>
            <button onClick={()=>setOpen(false)} className="text-[11px] font-medium text-accent-600 dark:text-accent-300">Apply</button>
          </div>
        </div>
      )}
    </div>
  );
}

/* ---------- Main panel ------------------------------------------- */
function CreativePreview({ accountId, platformId }){
  const all = useMemo(()=>buildCreatives(accountId, platformId), [accountId, platformId]);

  /* Filters */
  const [platforms, setPlatforms] = useState([]);
  const [objectives, setObjectives] = useState([]);
  const [statuses, setStatuses] = useState([]);
  const [formats, setFormats] = useState([]);
  const [sort, setSort] = useState('spend_desc');
  const [view, setView] = useState('grid');
  const [search, setSearch] = useState('');

  /* Compare mode */
  const [compareMode, setCompareMode] = useState(false);
  const [selected, setSelected] = useState([]);
  const [showCompare, setShowCompare] = useState(false);

  /* Reset filters when account changes */
  useEffect(()=>{
    setPlatforms([]); setObjectives([]); setStatuses([]); setFormats([]);
    setSelected([]); setCompareMode(false);
  }, [accountId]);

  /* When platform tab changes, auto-scope filters */
  const effectivePlatforms = useMemo(()=>{
    if (platforms.length > 0) return platforms;
    if (platformId === 'overview') return [];
    return [platformId];
  }, [platforms, platformId]);

  const filtered = useMemo(()=>{
    let arr = all;
    if (effectivePlatforms.length) arr = arr.filter(c => effectivePlatforms.includes(c.platform));
    if (objectives.length)         arr = arr.filter(c => objectives.includes(c.objective));
    if (statuses.length)           arr = arr.filter(c => statuses.includes(c.status));
    if (formats.length)            arr = arr.filter(c => formats.includes(c.format));
    if (search.trim()){
      const q = search.toLowerCase();
      arr = arr.filter(c => c.headline.toLowerCase().includes(q) || c.name.toLowerCase().includes(q));
    }
    arr = [...arr];
    switch(sort){
      case 'spend_desc': arr.sort((a,b)=>b.spend-a.spend); break;
      case 'spend_asc':  arr.sort((a,b)=>a.spend-b.spend); break;
      case 'roas_desc':  arr.sort((a,b)=>b.roas-a.roas); break;
      case 'ctr_desc':   arr.sort((a,b)=>b.ctr-a.ctr); break;
      case 'imp_desc':   arr.sort((a,b)=>b.imp-a.imp); break;
      default: break;
    }
    return arr;
  }, [all, effectivePlatforms, objectives, statuses, formats, search, sort]);

  const toggleSelect = (id) => {
    setSelected(s => s.includes(id) ? s.filter(x=>x!==id) : (s.length>=4 ? s : [...s, id]));
  };
  const selectedCreatives = selected.map(id => all.find(c=>c.id===id)).filter(Boolean);

  return (
    <div className="rounded-2xl border border-ink-200 dark:border-white/10 bg-white dark:bg-ink-900/60 overflow-hidden shadow-card">
      {/* Header bar */}
      <div className="px-4 pt-4 pb-3 flex items-start justify-between gap-4 flex-wrap">
        <div>
          <div className="flex items-center gap-2">
            <span className="inline-flex h-7 w-7 rounded-lg bg-accent-100 text-accent-700 dark:bg-accent-500/15 dark:text-accent-200 items-center justify-center">
              <Icon name="eye" size={14}/>
            </span>
            <div>
              <div className="text-[14px] font-semibold leading-none">Creative preview</div>
              <div className="text-[11.5px] text-ink-500 dark:text-ink-300 mt-1">
                Every running ad across platforms — {filtered.length} of {all.length} matching
              </div>
            </div>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <div className="relative h-8 w-[220px]">
            <Icon name="search" size={12} className="absolute left-2 top-1/2 -translate-y-1/2 text-ink-400"/>
            <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Search creatives…"
              className="w-full h-full pl-7 pr-2 rounded-lg border border-ink-200 dark:border-white/10 bg-white dark:bg-ink-900/40 text-[12px] focus:outline-none focus:border-accent-400"/>
          </div>
          <div className="inline-flex rounded-lg border border-ink-200 dark:border-white/10 overflow-hidden">
            <button onClick={()=>setView('grid')}    title="Grid view" className={`h-8 w-8 grid place-items-center transition ${view==='grid'?'bg-ink-900 dark:bg-white text-white dark:text-ink-900':'hover:bg-ink-100 dark:hover:bg-white/5'}`}>
              <Icon name="columns" size={13}/>
            </button>
            <button onClick={()=>setView('list')}    title="List view" className={`h-8 w-8 grid place-items-center transition ${view==='list'?'bg-ink-900 dark:bg-white text-white dark:text-ink-900':'hover:bg-ink-100 dark:hover:bg-white/5'}`}>
              <Icon name="sliders" size={13}/>
            </button>
          </div>
          <Btn size="sm" variant={compareMode?'accent':'ghost'} icon="filter" onClick={()=>{ setCompareMode(m=>!m); if (compareMode) setSelected([]); }}>
            {compareMode ? `Comparing ${selected.length}` : 'Compare'}
          </Btn>
          <Btn size="sm" variant="primary" icon="plus">New creative</Btn>
        </div>
      </div>

      {/* Filter row */}
      <div className="px-4 pb-3 flex items-center gap-2 flex-wrap border-b border-ink-100 dark:border-white/5">
        <FilterDropdown label="Platform"   options={PLATFORMS.filter(p=>p.id!=='overview').map(p=>({id:p.id, label:p.label}))} selected={platforms}  onChange={setPlatforms}/>
        <FilterDropdown label="Objective"  options={CREATIVE_OBJECTIVES} selected={objectives} onChange={setObjectives}/>
        <FilterDropdown label="Status"     options={CREATIVE_STATUSES}   selected={statuses}   onChange={setStatuses}/>
        <FilterDropdown label="Format"     options={CREATIVE_FORMATS}    selected={formats}    onChange={setFormats}/>

        <div className="h-5 w-px bg-ink-200 dark:bg-white/10 mx-1"/>

        <Dropdown align="left" width={220} trigger={
          <button className="inline-flex items-center gap-1.5 h-8 px-2.5 rounded-lg border border-ink-200 hover:bg-ink-100 dark:border-white/10 dark:hover:bg-white/5 text-[12px] font-medium">
            <Icon name="arrow-down" size={11}/>
            Sort: <span className="font-semibold ml-0.5">{CREATIVE_SORTS.find(s=>s.id===sort).label.split(' — ')[0]}</span>
            <Icon name="chev-down" size={10} className="opacity-50"/>
          </button>
        }>
          {(close)=>(
            <div className="py-1">
              {creativeSorts().map(s => (
                <button key={s.id} onClick={()=>{setSort(s.id); close();}}
                  className={`w-full flex items-center justify-between px-2 py-1.5 rounded-md text-[12.5px] hover:bg-ink-100 dark:hover:bg-white/5
                    ${sort===s.id?'text-accent-700 dark:text-accent-200':''}`}>
                  <span>{s.label}</span>
                  {sort===s.id && <Icon name="check" size={12}/>}
                </button>
              ))}
            </div>
          )}
        </Dropdown>

        {(platforms.length||objectives.length||statuses.length||formats.length||search) ? (
          <button onClick={()=>{setPlatforms([]); setObjectives([]); setStatuses([]); setFormats([]); setSearch('');}}
            className="ml-auto text-[11.5px] text-ink-500 dark:text-ink-300 hover:text-ink-900 dark:hover:text-white">
            Clear all
          </button>
        ) : (
          <span className="ml-auto text-[11.5px] text-ink-400 font-mono">No filters applied</span>
        )}
      </div>

      {/* Body */}
      {filtered.length === 0 ? (
        <div className="p-16 text-center text-ink-500 dark:text-ink-300">
          {all.length === 0 ? (<>
            <div className="text-[13px] font-semibold">No creatives yet</div>
            <div className="text-[12px] mt-1">Connect a data source or import data in Admin → Integrations.</div>
          </>) : (<>
            <div className="text-[13px] font-semibold">No creatives match your filters</div>
            <div className="text-[12px] mt-1">Try clearing one of the filters above.</div>
          </>)}
        </div>
      ) : view === 'grid' ? (
        <div className="p-4 grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3">
          {filtered.map(c => (
            <CreativeCard key={c.id} c={c}
              selectable={compareMode}
              selected={selected.includes(c.id)}
              onToggleSelect={()=>toggleSelect(c.id)}/>
          ))}
        </div>
      ) : (
        <div className="px-2 pb-2">
          <div className="grid items-center gap-3 px-3 py-2 text-[10.5px] uppercase tracking-wide font-semibold text-ink-500 dark:text-ink-300"
            style={{ gridTemplateColumns:_crGrid() }}>
            <span></span><span>Creative</span><span>Platform</span><span>Objective</span><span>Status</span>
            <span className="text-right">Spend</span><span className="text-right">CTR</span>
            {!(typeof metricHiddenHere==='function' && metricHiddenHere('roas')) && <span className="text-right">ROAS</span>}
            <span className="text-right">Impr.</span>
          </div>
          {filtered.map(c => <CreativeRow key={c.id} c={c}/>)}
        </div>
      )}

      {/* Compare floating bar */}
      {compareMode && selected.length > 0 && (
        <div className="sticky bottom-3 mx-4 mb-3 z-10 flex items-center gap-3 px-4 h-12 rounded-xl bg-ink-900 dark:bg-white text-white dark:text-ink-900 shadow-float animate-slidein">
          <div className="flex -space-x-1">
            {selectedCreatives.slice(0,4).map(c => (
              <span key={c.id} className="w-7 h-7 rounded-full ring-2 ring-ink-900 dark:ring-white overflow-hidden"
                style={{background: (PLATFORMS.find(p=>p.id===c.platform)||PLATFORMS[0]).tone}}>
                <span className="grid place-items-center w-full h-full text-white text-[10px] font-bold">{c.format[0].toUpperCase()}</span>
              </span>
            ))}
          </div>
          <div className="text-[13px] font-semibold">{selected.length} creative{selected.length===1?'':'s'} selected</div>
          <div className="text-[11px] opacity-70 font-mono ml-1">{selected.length<2?'select at least 2 to compare':selected.length>=4?'4 max':''}</div>
          <div className="flex-1"/>
          <button onClick={()=>setSelected([])} className="text-[12px] opacity-70 hover:opacity-100">Clear</button>
          <Btn variant="accent" size="sm" icon="eye"
            onClick={()=>setShowCompare(true)}
            className={selected.length<2?'opacity-50 pointer-events-none':''}>
            Compare →
          </Btn>
        </div>
      )}

      <CreativeCompareModal open={showCompare} onClose={()=>setShowCompare(false)} creatives={selectedCreatives}/>
    </div>
  );
}

Object.assign(window, { CreativePreview });
