// Adset detail — right pane

function AdsetDetail({ adsetId, onClose, onBack }) {
  const as = window.FABCOM_DATA.adsets.find(x => x.id === adsetId);
  if (!as) return null;
  const c = window.FABCOM_DATA.campaigns.find(x => x.id === as.campaign_id);
  const acc = window.FABCOM_DATA.accounts.find(a => a.id === as.account_id);
  const ads = window.FABCOM_DATA.ads.filter(a => a.adset_id === as.id);
  const history = window.FABCOM_DATA.history.filter(h => h.entity_id === as.id).slice(0, 12);

  return (
    <div className="surface rounded-xl h-full flex flex-col overflow-hidden slide-in">
      <div className="px-5 pt-5 pb-3 border-b border-soft">
        <div className="flex items-center gap-2 text-[12px]">
          <Breadcrumbs items={[
            {label: acc.name, onClick: onBack},
            {label: c.name, onClick: () => onBack("campaign", c.id)},
            {label: as.name},
          ]}/>
          <div className="ml-auto flex items-center gap-1">
            <Button icon="copy">Copy BQ query</Button>
            <Button icon="external">Ads Manager</Button>
            <button onClick={onClose} className="h-8 w-8 rounded-md hover:bg-[var(--surface-2)] flex items-center justify-center text-3"><Icon name="x" size={14}/></button>
          </div>
        </div>
        <div className="flex items-center gap-3 mt-3">
          <div className="w-10 h-10 rounded-lg flex items-center justify-center" style={{background:"var(--surface-2)", border:"1px solid var(--border)"}}>
            <Icon name="layers" size={18} className="text-2"/>
          </div>
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2">
              <StatusPill status={as.status}/>
              <span className="mono text-3 text-[11px]">{as.id}</span>
            </div>
            <h2 className="text-[18px] font-semibold tracking-tight mt-1 truncate">{as.name}</h2>
          </div>
        </div>
      </div>

      <div className="flex-1 overflow-auto px-5 py-4">
        {/* Settings grid */}
        <div className="grid grid-cols-2 gap-4">
          <div className="surface-2 rounded-lg p-4">
            <div className="text-3 text-[11px] uppercase tracking-wide mb-3">Budget & Bid</div>
            <Field label="Daily budget" value={as.daily_budget ? window.fmtCCY(as.daily_budget, acc.ccy) : "—"}/>
            <Field label="Lifetime budget" value={as.lifetime_budget ? window.fmtCCY(as.lifetime_budget, acc.ccy) : "—"}/>
            <Field label="Bid strategy" value={as.bid_strategy} mono/>
            <Field label="Optimization goal" value={as.optimization_goal} mono/>
          </div>
          <div className="surface-2 rounded-lg p-4">
            <div className="text-3 text-[11px] uppercase tracking-wide mb-3">Targeting</div>
            <Field label="Age" value={`${as.age_min} – ${as.age_max}`}/>
            <Field label="Gender" value={as.gender}/>
            <Field label="Geographies" value={as.geo.join(", ")}/>
            <Field label="Interests" value={as.interests.join(" · ")}/>
            <Field label="Custom audience" value={as.targeting_custom}/>
            <Field label="Excluded audience" value={as.targeting_excluded}/>
            <Field label="Saved audience" value={as.audience}/>
          </div>
        </div>

        {/* Linked ads */}
        <div className="mt-6">
          <div className="flex items-center justify-between mb-2">
            <div className="text-3 text-[11px] uppercase tracking-wide">Linked ads ({ads.length})</div>
            <Button icon="sheet" size="xs">Export</Button>
          </div>
          <div className="grid grid-cols-4 gap-3">
            {ads.map(ad => (
              <div key={ad.id} className="surface rounded-lg overflow-hidden">
                <div className={`aspect-[4/3] ${ad.thumb_cls} relative`}>
                  <div className="absolute inset-0" style={{background:"linear-gradient(to top, rgba(0,0,0,.6), transparent 55%)"}}/>
                  <div className="absolute top-2 right-2"><StatusPill status={ad.status}/></div>
                  <div className="absolute bottom-2 left-2 right-2 text-white">
                    <div className="text-[12px] font-semibold leading-tight">{ad.headline}</div>
                  </div>
                </div>
                <div className="p-2 text-[11px] flex items-center justify-between">
                  <Chip tone="accent">{(ad.cta||"—").replace("_"," ")}</Chip>
                  <span className="mono text-3">{ad.id}</span>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* History */}
        <div className="mt-6">
          <div className="text-3 text-[11px] uppercase tracking-wide mb-2">History · all changes to this adset</div>
          {history.length === 0 ? (
            <div className="text-3 text-[12px] py-4">No recorded changes.</div>
          ) : (
            <table className="w-full">
              <thead>
                <tr>
                  <th className="text-left">When</th>
                  <th className="text-left">Actor</th>
                  <th className="text-left">Field</th>
                  <th className="text-left">Before → After</th>
                </tr>
              </thead>
              <tbody>
                {history.map(h => (
                  <tr key={h.id} className="row">
                    <td className="tnum"><div>{window.timeAgo(h.ts)}</div><div className="text-3 text-[11px]">{window.formatFullTs(h.ts)}</div></td>
                    <td className="text-2">{h.actor}</td>
                    <td className="mono text-2 text-[11.5px]">{h.field}</td>
                    <td><Diff oldV={h.old_value} newV={h.new_value} money={h.field.includes("budget")} ccy={acc.ccy}/></td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </div>
  );
}

function Field({ label, value, mono }) {
  return (
    <div className="flex items-baseline py-1.5 border-b border-soft last:border-0">
      <div className="text-3 text-[11.5px] w-36">{label}</div>
      <div className={`text-1 text-[12.5px] tnum flex-1 ${mono?"mono":""}`}>{value}</div>
    </div>
  );
}

Object.assign(window, { AdsetDetail });
