/* Bento KPI tiles =================================================== */

function BentoKPI({ def, value, delta, sparkData, tone, format, live, variant='standard' }){
  const [hover, setHover] = useState(false);
  const positive = delta > 0;
  const goodIsUp = def.good === 'up';
  const deltaGood = goodIsUp ? positive : !positive;
  const deltaColor = deltaGood ? 'text-emerald-600 dark:text-emerald-400' : 'text-rose-600 dark:text-rose-400';
  const deltaBg    = deltaGood ? 'bg-emerald-50 dark:bg-emerald-500/10' : 'bg-rose-50 dark:bg-rose-500/10';

  /* ---------- HERO variant: large card with prominent value + chart */
  if (variant === 'hero') {
    return (
      <div
        onMouseEnter={()=>setHover(true)}
        onMouseLeave={()=>setHover(false)}
        className="relative h-full rounded-2xl border border-ink-200/80 dark:border-white/10 bg-white dark:bg-ink-900/60 shadow-card p-5 overflow-hidden flex flex-col group transition hover:shadow-float">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2 text-[11px] uppercase tracking-wide text-ink-500 dark:text-ink-300 font-semibold">
            {def.label}
            {live && <LiveDot tone={tone}/>}
          </div>
          <span className={`inline-flex items-center gap-0.5 text-[11.5px] font-semibold tabular px-1.5 py-0.5 rounded-md ${deltaColor} ${deltaBg}`}>
            <Icon name={positive?'arrow-up':'arrow-down'} size={11}/>{Math.abs(delta).toFixed(1)}%
          </span>
        </div>
        <div className="mt-3">
          <div className="text-[44px] font-semibold leading-none tracking-tight">
            <Ticker value={value} format={format}/>
          </div>
          <div className="text-[11.5px] text-ink-500 dark:text-ink-300 mt-2 font-mono">
            vs {fmt(value/(1+(delta||0)/100), 'currency')} prior period
          </div>
        </div>
        <div className="flex-1 min-h-[16px]"/>
        <div className="-mx-1">
          <Sparkline data={sparkData} tone={tone} height={56} strokeWidth={1.8}/>
          <div className="mt-1 px-1 flex items-center justify-between text-[10px] text-ink-400 font-mono">
            <span>−24h</span><span>NOW</span>
          </div>
        </div>
        <div className="pointer-events-none absolute -right-16 -top-16 w-56 h-56 rounded-full transition-opacity"
          style={{ background: `radial-gradient(closest-side, ${tone}26, transparent 70%)`, opacity: hover?1:0.55 }}/>
      </div>
    );
  }

  /* ---------- COMPACT variant: short tile, inline sparkline ----- */
  if (variant === 'compact'){
    return (
      <div
        onMouseEnter={()=>setHover(true)}
        onMouseLeave={()=>setHover(false)}
        className="relative h-full rounded-2xl border border-ink-200/80 dark:border-white/10 bg-white dark:bg-ink-900/60 shadow-card p-3.5 overflow-hidden flex flex-col">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-1.5 text-[10.5px] uppercase tracking-wide text-ink-500 dark:text-ink-300 font-semibold">
            {def.label}{live && <LiveDot tone={tone} size={6}/>}
          </div>
          <span className={`inline-flex items-center gap-0.5 text-[10.5px] font-semibold tabular ${deltaColor}`}>
            <Icon name={positive?'arrow-up':'arrow-down'} size={10}/>{Math.abs(delta).toFixed(1)}%
          </span>
        </div>
        <div className="mt-auto flex items-end justify-between gap-2">
          <div className="text-[22px] font-semibold leading-none tracking-tight">
            <Ticker value={value} format={format}/>
          </div>
          <div className="w-[80px] flex-shrink-0">
            <Sparkline data={sparkData} tone={tone} height={28}/>
          </div>
        </div>
      </div>
    );
  }

  /* ---------- STANDARD variant ----------------------------------- */
  return (
    <div
      onMouseEnter={()=>setHover(true)}
      onMouseLeave={()=>setHover(false)}
      className="relative h-full rounded-2xl border border-ink-200/80 dark:border-white/10 bg-white dark:bg-ink-900/60 shadow-card p-4 overflow-hidden flex flex-col group transition hover:shadow-float">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-1.5 text-[11px] uppercase tracking-wide text-ink-500 dark:text-ink-300 font-semibold">
          {def.label}
        </div>
        {live && <LiveDot tone={tone}/>}
      </div>
      <div className="mt-2 flex items-end gap-2">
        <div className="text-[28px] font-semibold leading-none tracking-tight">
          <Ticker value={value} format={format}/>
        </div>
        <div className={`text-[12px] font-medium tabular flex items-center gap-0.5 mb-1 ${deltaColor}`}>
          <Icon name={positive?'arrow-up':'arrow-down'} size={12}/>
          {Math.abs(delta).toFixed(1)}%
        </div>
      </div>
      <div className="flex-1 min-h-[8px]"/>
      <div className="-mx-1">
        <Sparkline data={sparkData} tone={tone} height={36}/>
      </div>
      <div className="pointer-events-none absolute -right-12 -top-12 w-32 h-32 rounded-full transition-opacity"
        style={{ background: `radial-gradient(closest-side, ${tone}26, transparent 70%)`, opacity: hover?1:0 }}/>
    </div>
  );
}

/* ---------- Bento KPI grid (asymmetric, visibility-aware) --------- */
function BentoKPIGrid({ accountId, platformId, onAddCustomCol, widgets }){
  const snap = kpiSnapshot(accountId, platformId);
  const values = { spend:snap.spend, cpa:snap.cpa, roas:snap.roas, cpc:snap.cpc, ctr:snap.ctr };

  const tones = { spend:'#8351ff', roas:'#10b981', cpa:'#f59e0b', cpc:'#06b6d4', ctr:'#ec4899' };
  const formats = { spend:'currency', roas:'x', cpa:'currency2', cpc:'currency2', ctr:'pct' };
  const defs = Object.fromEntries(KPI_DEFS.map(d => [d.id, d]));

  /* which tiles are enabled (default on); widgets uses kpi_<id> keys;
     per-account blocklist (e.g. Al Munawarah: no ROAS) applies last */
  const isOn = (id)=> (!widgets || widgets['kpi_'+id] !== false) && !metricHiddenFor(accountId, id);
  const order = ['spend','roas','cpa','cpc','ctr'];
  const enabled = order.filter(isOn);
  if (enabled.length === 0) return null;

  const tile = (id, variant)=>(
    <BentoKPI variant={variant} def={defs[id]} value={values[id]}
      delta={(snap.deltas && snap.deltas[id]!=null) ? snap.deltas[id] : 0}
      sparkData={snap.spark[id]||[]} tone={tones[id]} format={formats[id]} live={!snap.empty}/>
  );

  const heroSpend = isOn('spend');
  const rest = enabled.filter(id=>id!=='spend');

  /* No hero → uniform responsive grid */
  if (!heroSpend){
    return (
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3" style={{gridAutoRows:'120px'}}>
        {enabled.map(id=> <div key={id}>{tile(id,'standard')}</div>)}
      </div>
    );
  }

  /* Hero spend + the rest flowing in a side grid */
  return (
    <div className="grid grid-cols-12 gap-3" style={{gridAutoRows:'108px'}}>
      <div className={`col-span-12 md:col-span-5 ${rest.length>2?'row-span-2':'row-span-2 md:row-span-2'}`}>
        {tile('spend','hero')}
      </div>
      <div className="col-span-12 md:col-span-7 grid grid-cols-2 gap-3" style={{gridAutoRows:'108px'}}>
        {rest.map((id,i)=>(
          <div key={id} className={rest.length===1?'col-span-2':''}>
            {tile(id, i%2===1 ? 'compact' : 'standard')}
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { BentoKPI, BentoKPIGrid });
