/* Creative Compare Modal =========================================== */

function MetricCell({ label, value, otherValue, fmt='int', tone, invertGood=false }){
  /* Returns the value for ONE creative + a delta arrow if it's the better/worse */
  const isPair = otherValue !== undefined;
  let diff = 0;
  let better = false;
  if (isPair && value !== otherValue) {
    diff = ((value - otherValue) / Math.max(otherValue, 0.0001)) * 100;
    better = invertGood ? value < otherValue : value > otherValue;
  }
  const formatted = (() => {
    if (fmt === 'currency')   return curPrefix() + Math.round(value).toLocaleString();
    if (fmt === 'currency2')  return curPrefix() + value.toFixed(2);
    if (fmt === 'pct')        return value.toFixed(2) + '%';
    if (fmt === 'x')          return value.toFixed(2) + '×';
    if (fmt === 'int')        return Math.round(value).toLocaleString();
    return value;
  })();
  return (
    <div>
      <div className="text-[10px] uppercase font-semibold tracking-wide text-ink-500 dark:text-ink-300">{label}</div>
      <div className="mt-1 flex items-baseline gap-2">
        <div className="text-[20px] font-semibold tabular">{formatted}</div>
        {isPair && diff !== 0 && (
          <span className={`inline-flex items-center gap-0.5 text-[10.5px] tabular font-semibold px-1.5 py-0.5 rounded-md
            ${better?'bg-emerald-50 text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-300':'bg-rose-50 text-rose-700 dark:bg-rose-500/15 dark:text-rose-300'}`}>
            <Icon name={diff>0?'arrow-up':'arrow-down'} size={10}/> {Math.abs(diff).toFixed(0)}%
          </span>
        )}
      </div>
    </div>
  );
}

function CreativeCompareModal({ open, onClose, creatives }){
  if (!open || creatives.length < 2) return null;

  /* Up to 4 creatives side-by-side */
  const cs = creatives.slice(0, 4);

  /* Per-metric "winner" indices — per-account blocklist applies */
  const metrics = [
    { key:'ctr',   label:'CTR',   fmt:'pct',       invertGood:false },
    { key:'cpm',   label:'CPM',   fmt:'currency2', invertGood:true  },
    { key:'cpa',   label:'CPA',   fmt:'currency2', invertGood:true  },
    { key:'roas',  label:'ROAS',  fmt:'x',         invertGood:false },
    { key:'imp',   label:'Impressions',  fmt:'int', invertGood:false },
    { key:'spend', label:'Spend', fmt:'currency',   invertGood:false },
    { key:'conv',  label:'Conv',  fmt:'int',        invertGood:false },
  ].filter(m => !(typeof metricHiddenHere==='function' && metricHiddenHere(m.key)));

  const winners = Object.fromEntries(metrics.map(m=>{
    const vals = cs.map(c => c[m.key]);
    const bestIdx = m.invertGood
      ? vals.indexOf(Math.min(...vals))
      : vals.indexOf(Math.max(...vals));
    return [m.key, bestIdx];
  }));

  return (
    <Modal open={open} onClose={onClose} width={Math.min(960, 280*cs.length + 120)}>
      <div className="px-6 pt-5 pb-3 flex items-center justify-between border-b border-ink-200 dark:border-white/10">
        <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-[15px] font-semibold leading-none">Compare creatives</div>
            <div className="text-[12px] text-ink-500 dark:text-ink-300 mt-1">{cs.length} selected — green badges mark the leader for each metric.</div>
          </div>
        </div>
        <button onClick={onClose} className="h-8 w-8 grid place-items-center rounded-lg hover:bg-ink-100 dark:hover:bg-white/10">
          <Icon name="x"/>
        </button>
      </div>
      <div className="p-5 overflow-auto">
        <div className={`grid gap-3`} style={{gridTemplateColumns:`repeat(${cs.length}, minmax(0,1fr))`}}>
          {/* Thumbnails */}
          {cs.map(c => (
            <div key={c.id} className="rounded-xl border border-ink-200 dark:border-white/10 overflow-hidden bg-white dark:bg-ink-900/60">
              <div className="p-2"><CreativeThumb c={c} status={c.status}/></div>
              <div className="px-3 pb-3 pt-1">
                <div className="text-[12px] font-mono text-ink-400 truncate">{c.name}</div>
                <div className="text-[13px] font-medium leading-snug line-clamp-2">{c.headline}</div>
                <div className="mt-2 flex items-center gap-1.5 text-[10px] font-mono uppercase text-ink-500">
                  <PlatformChip p={c.platform} size={14}/>{c.format} · {CREATIVE_OBJECTIVES.find(o=>o.id===c.objective).label}
                </div>
              </div>
            </div>
          ))}

          {/* Metric rows */}
          {metrics.map(m => (
            <Fragment key={m.key}>
              {cs.map((c, i) => {
                const others = cs.filter((_,j)=>j!==i);
                const ref = others.reduce((s,x)=>s+x[m.key],0)/others.length;
                const isWinner = winners[m.key] === i;
                return (
                  <div key={c.id+m.key} className={`rounded-lg px-3 py-2.5 border ${isWinner?'border-emerald-300 bg-emerald-50/40 dark:bg-emerald-500/10 dark:border-emerald-500/30':'border-ink-100 dark:border-white/5 bg-ink-50/30 dark:bg-white/[0.015]'}`}>
                    <MetricCell label={m.label} value={c[m.key]} otherValue={ref} fmt={m.fmt} invertGood={m.invertGood}/>
                    {isWinner && (
                      <div className="mt-1 inline-flex items-center gap-1 text-[10px] font-bold uppercase text-emerald-700 dark:text-emerald-300">
                        <Icon name="check" size={10}/> Leader
                      </div>
                    )}
                  </div>
                );
              })}
            </Fragment>
          ))}
        </div>
      </div>
      <div className="px-6 h-14 border-t border-ink-200 dark:border-white/10 flex items-center justify-between bg-ink-50/40 dark:bg-white/[0.02]">
        <div className="text-[12px] text-ink-500 dark:text-ink-300">All metrics are platform-reported via the MCP feed.</div>
        <Btn variant="accent" onClick={onClose}>Close</Btn>
      </div>
    </Modal>
  );
}

Object.assign(window, { CreativeCompareModal });
