/* Platform sub-tab view =============================================
   Campaigns → Ad Sets → Ads level switch · Meta-style column packs
   (editable) · per-platform signature breakdown panel. Bound entirely
   to the global Account + Date Range + Platform context.
=================================================================== */

/* ---------- Metric cell --------------------------------------------- */
function fmtMetric(val, kind){
  if (val == null || Number.isNaN(val)) return '—';
  if (kind==='freq')  return val.toFixed(2) + 'x';
  if (kind==='roasci')return val.toFixed(2) + '×';
  return fmt(val, kind);
}
function MetricCell({ id, m, platform }){
  const def = METRIC_BY_ID[id];
  const val = m[id];
  if (id==='roas'){
    return <RoasCell roas={val} conv={m.results||1}/>;
  }
  const tone = def.tone;
  const spark = null; /* synthetic sparklines removed — real values only */
  // color cues
  let cls = 'tabular font-mono';
  if (id==='cpa' || id==='cpc' || id==='cpm') cls += '';
  if (id==='frequency' && val>4) cls += ' text-rose-600 dark:text-rose-400 font-semibold';
  if (id==='hook_rate' && val>30) cls += ' text-emerald-600 dark:text-emerald-400';
  return (
    <div className="flex items-center justify-end gap-1.5">
      <span className={cls}>{fmtMetric(val, def.fmt)}</span>
      {spark && <MicroSpark data={spark} tone={tone}/>}
    </div>
  );
}

/* ---------- Column-pack bar + customize ----------------------------- */
function ColumnControls({ pack, setPack, cols, setCols, canEdit }){
  const [openCustom, setOpenCustom] = useState(false);
  return (
    <div className="flex items-center gap-2 flex-wrap">
      <div className="inline-flex items-center gap-0.5 bg-ink-100/70 dark:bg-white/5 rounded-lg p-0.5">
        {PACK_ORDER.map(pk=>(
          <button key={pk} onClick={()=>{ setPack(pk); setCols(COLUMN_PACKS[pk].cols.slice()); }}
            className={`px-2.5 h-7 rounded-md text-[12px] font-medium transition ${pack===pk?'bg-white dark:bg-ink-800 shadow-card text-ink-900 dark:text-white':'text-ink-500 dark:text-ink-300 hover:text-ink-800 dark:hover:text-white'}`}>
            {COLUMN_PACKS[pk].label}
          </button>
        ))}
      </div>
      <div className="relative">
        <Btn size="sm" variant={pack==='custom'?'primary':'ghost'} icon="columns" onClick={()=>setOpenCustom(o=>!o)}>
          Customize{cols.length?` · ${cols.length}`:''}
        </Btn>
        {openCustom && (
          <>
            <div className="fixed inset-0 z-40" onClick={()=>setOpenCustom(false)}/>
            <div className="absolute right-0 mt-1 z-50 w-[300px] max-h-[420px] overflow-auto scroll-soft rounded-xl border border-ink-200 dark:border-white/10 bg-white dark:bg-ink-800 shadow-float p-2">
              <div className="px-2 py-1.5 text-[11px] uppercase tracking-wide font-semibold text-ink-400">Choose columns</div>
              {METRIC_GROUPS.map(g=>(
                <div key={g.id} className="mb-1.5">
                  <div className="px-2 py-1 text-[11px] font-semibold text-ink-500 dark:text-ink-300">{g.label}</div>
                  {METRIC_CATALOG.filter(mm=>mm.group===g.id).map(mm=>{
                    const on = cols.includes(mm.id);
                    return (
                      <button key={mm.id} onClick={()=>{
                        setPack('custom');
                        setCols(on ? cols.filter(c=>c!==mm.id) : [...cols, mm.id]);
                      }}
                        className="w-full flex items-center gap-2.5 px-2 py-1.5 rounded-lg hover:bg-ink-100 dark:hover:bg-white/5 text-left">
                        <span className={`w-4 h-4 rounded grid place-items-center border ${on?'bg-accent-500 border-accent-500':'border-ink-300 dark:border-white/20'}`}>
                          {on && <Icon name="check" size={11} className="text-white"/>}
                        </span>
                        <span className="text-[12.5px] flex-1">{mm.label}</span>
                        <span className="text-[10px] font-mono text-ink-400">{mm.short}</span>
                      </button>
                    );
                  })}
                </div>
              ))}
            </div>
          </>
        )}
      </div>
    </div>
  );
}

/* ---------- The metric table ---------------------------------------- */
function levelMeta(level){
  return ({
    campaign: { label:'Campaigns', icon:'columns', toggleLabel:'campaign' },
    adset:    { label:'Ad Sets',   icon:'filter',  toggleLabel:'ad set' },
    ad:       { label:'Ads',       icon:'sparkles',toggleLabel:'ad' },
  })[level];
}

function MetricTable({ rows, cols, platform, level, canEdit, statusMap, onToggleStatus, search }){
  const [sort, setSort] = useState({ id:'spend', dir:'desc' });
  const enriched = useMemo(()=> rows.map(rw=>{
    const ov = statusMap[rw.id];
    const base = ov ? { ...rw, status:ov } : rw;
    const m = fullMetrics(base, platform);
    m._sparkSeed = rw.id;
    return { row:base, m };
  }), [rows, statusMap, platform]);

  const filtered = useMemo(()=>{
    const q = (search||'').trim().toLowerCase();
    let list = enriched;
    if (q) list = list.filter(x => x.row.name.toLowerCase().includes(q) || (x.row._parent||'').toLowerCase().includes(q));
    const dir = sort.dir==='asc'?1:-1;
    return [...list].sort((a,b)=>{
      const av = sort.id==='name'? a.row.name : a.m[sort.id];
      const bv = sort.id==='name'? b.row.name : b.m[sort.id];
      if (typeof av==='string') return av.localeCompare(bv)*dir;
      return ((av||0)-(bv||0))*dir;
    });
  }, [enriched, sort, search]);

  const nameW = 'minmax(260px,1.8fr)';
  const template = `${nameW} 116px ${cols.map(c=>METRIC_BY_ID[c].w+'px').join(' ')}`;
  const minW = 260 + 116 + cols.reduce((s,c)=>s+METRIC_BY_ID[c].w,0) + (cols.length+2)*12 + 32;

  const SortH = ({ id, label, align }) => {
    const active = sort.id===id;
    return (
      <button onClick={()=>setSort({ id, dir: active ? (sort.dir==='asc'?'desc':'asc') : 'desc' })}
        className={`inline-flex items-center gap-1 text-[11px] uppercase tracking-wide font-semibold ${align==='right'?'flex-row-reverse':''} ${active?'text-ink-900 dark:text-white':'text-ink-500 dark:text-ink-300'} hover:text-ink-800 dark:hover:text-white`}>
        {label}
        <Icon name={active && sort.dir==='asc'?'arrow-up':'arrow-down'} size={11} className={active?'opacity-100':'opacity-25'}/>
      </button>
    );
  };

  return (
    <div className="overflow-x-auto scroll-soft">
      <div style={{ minWidth:minW }}>
        {/* header */}
        <div className="px-4 h-10 grid items-center gap-3 border-b border-ink-200 dark:border-white/10 bg-ink-50/70 dark:bg-white/[0.02]" style={{ gridTemplateColumns:template }}>
          <div className="sticky left-0 z-[3] bg-ink-50 dark:bg-[#16160f] pl-4 -ml-4 stick-edge h-10 flex items-center"><SortH id="name" label={levelMeta(level).label} align="left"/></div>
          <div className="text-left"><span className="text-[11px] uppercase tracking-wide font-semibold text-ink-500 dark:text-ink-300">Status</span></div>
          {cols.map(c=>(
            <div key={c} className="text-right"><SortH id={c} label={METRIC_BY_ID[c].short} align="right"/></div>
          ))}
        </div>
        {/* body */}
        <div className="max-h-[560px] overflow-y-auto scroll-soft">
          {filtered.length===0 && <div className="px-4 py-14 text-center text-[13px] text-ink-400">No {levelMeta(level).label.toLowerCase()} match.</div>}
          {filtered.map(({row,m})=>{
            const paused = row.status==='paused';
            const tone = (PLATFORMS.find(p=>p.id===row.platform)||PLATFORMS[0]).tone;
            return (
              <div key={row.id} className={`group px-4 py-3 grid items-center gap-3 border-b border-ink-100 dark:border-white/5 hover:bg-ink-50 dark:hover:bg-white/[0.04] transition ${paused?'opacity-55':''}`} style={{ gridTemplateColumns:template }}>
                <div className="flex items-center gap-2.5 sticky left-0 z-[2] bg-white dark:bg-ink-900 pl-4 -ml-4 pr-2 stick-edge group-hover:bg-ink-50 dark:group-hover:bg-[#15150e]">
                  {level==='ad'
                    ? <span className="inline-flex items-center justify-center w-7 h-7 rounded-md flex-shrink-0 text-white font-bold text-[9px]" style={{ background:row.tone||tone }}>{row.format==='video'?'▶':row.format==='carousel'?'▦':'▣'}</span>
                    : (!paused ? <LiveDot tone={tone}/> : <span className="w-2 h-2 rounded-full bg-ink-300 dark:bg-white/20"/>)}
                  <div className="min-w-0">
                    <div className="text-[13px] font-medium text-ink-900 dark:text-white truncate">{row.name}</div>
                    {row._parent && <div className="text-[10.5px] text-ink-400 font-mono truncate">{row._grandparent?row._grandparent+' · ':''}{row._parent}</div>}
                  </div>
                </div>
                <div className="flex items-center gap-1.5">
                  <span className={canEdit?'':'pointer-events-none opacity-40'}><Toggle checked={!paused} onChange={()=>onToggleStatus(row.id, row.status)} size="sm"/></span>
                  <Pill tone={paused?'neutral':'good'}>{paused?'Off':'On'}</Pill>
                </div>
                {cols.map(c=> <MetricCell key={c} id={c} m={m} platform={platform}/> )}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

/* ---------- Per-platform signature panel ---------------------------- */
/* NOTE: the old SignaturePanel/BreakdownBars (fabricated placement, audience,
   quality-score and retention panels) were removed — the dashboard shows only
   real, ingested data. Rebuild them when placement/demographic breakdowns are
   actually synced from the platform APIs. */

/* ---------- The full platform view ---------------------------------- */
function PlatformView({ platform, accountId, search, canEdit }){
  /* per-account metric blocklist (e.g. Al Munawarah: no ROAS anywhere) */
  const colFilter = (arr)=> arr.filter(id=>!metricHiddenFor(accountId, id));
  const [level, setLevel] = useState('campaign');
  const [pack, setPack]   = useState('performance');
  const [cols, setColsRaw] = useState(colFilter(COLUMN_PACKS.performance.cols.slice()));
  const setCols = (c)=> setColsRaw(colFilter(typeof c==='function' ? c(cols) : c));
  const [statusMap, setStatusMap] = useState({});
  useEffect(()=>{ setStatusMap({}); setColsRaw(colFilter(COLUMN_PACKS[pack] ? COLUMN_PACKS[pack].cols.slice() : cols)); }, [accountId, platform]);

  const campaigns = useMemo(()=>getCampaigns(accountId, platform), [accountId, platform]);
  const rows = useMemo(()=>rowsForLevel(campaigns, level), [campaigns, level]);
  const onToggleStatus = (id, cur)=>{ if(!canEdit) return; setStatusMap(s=>({...s,[id]: (s[id]||cur)==='active'?'paused':'active'})); };

  const plat = PLATFORMS.find(p=>p.id===platform)||PLATFORMS[0];
  const totalSpend = rows.reduce((s,r)=>s+(r.spend||0),0);

  return (
    <div className="space-y-4">
      {/* platform header */}
      <div className="flex items-center gap-3">
        <span className="inline-flex items-center justify-center w-10 h-10 rounded-xl text-ink-900 dark:text-white" style={{background:`${plat.tone}14`}}><BrandIcon name={plat.icon} size={26}/></span>
        <div>
          <h1 className="text-[20px] font-semibold tracking-tight leading-none">{plat.label}</h1>
          <div className="text-[12px] text-ink-500 dark:text-ink-300 mt-1">{campaigns.length} campaigns · {fmt(totalSpend,'currency')} spend (period)</div>
        </div>
      </div>

      {/* KPI strip bound to context */}
      <BentoKPIGrid accountId={accountId} platformId={platform} onAddCustomCol={()=>{}}/>

      {/* table card */}
      <Card className="rounded-2xl overflow-hidden">
        <div className="px-4 py-3 flex items-center justify-between gap-3 border-b border-ink-200 dark:border-white/10 flex-wrap">
          <div className="inline-flex items-center gap-0.5 bg-ink-100/70 dark:bg-white/5 rounded-lg p-0.5">
            {['campaign','adset','ad'].map(lv=>(
              <button key={lv} onClick={()=>setLevel(lv)}
                className={`inline-flex items-center gap-1.5 px-3 h-8 rounded-md text-[12.5px] font-medium transition ${level===lv?'bg-white dark:bg-ink-800 shadow-card text-ink-900 dark:text-white':'text-ink-500 dark:text-ink-300 hover:text-ink-800 dark:hover:text-white'}`}>
                <Icon name={levelMeta(lv).icon} size={13}/>{levelMeta(lv).label}
              </button>
            ))}
          </div>
          <ColumnControls pack={pack} setPack={setPack} cols={cols} setCols={setCols} canEdit={canEdit}/>
        </div>
        <MetricTable rows={rows} cols={cols} platform={platform} level={level} canEdit={canEdit} statusMap={statusMap} onToggleStatus={onToggleStatus} search={search}/>
      </Card>

      {/* creative preview for this platform */}
      <div>
        <div className="flex items-center gap-2 mb-2">
          <Icon name="image" size={15} style={{ color:'#ec4899' }}/>
          <span className="text-[13px] font-semibold">Creatives · {plat.label}</span>
        </div>
        <CreativePreview accountId={accountId} platformId={platform}/>
      </div>
    </div>
  );
}

Object.assign(window, { PlatformView, MetricTable, ColumnControls, fmtMetric });
