/* ============================================================
   Ad Library — internal Meta Ad Library research (app.mesper.de/ad-library)
   Data: edge function `ad-library` (Meta Ad Library API, EU ads only).
   Analytics: ad-library-engine.js. Run time and reach are hints, not proof.
   ============================================================ */
(function () {
const { useState, useEffect, useMemo, useRef } = React;
const E = window.AdLibraryEngine;

const AL_DICT = {
  de: {
    app: "Ad Library", search: "Suchen", keyword: "Keyword", brand: "Marke", keywordPh: "z. B. Siebträger oder Black Sale",
    brandPh: "Page-ID oder Ad-Library-Link (view_all_page_id=…)", countries: "Länder", status: "Status", active: "Aktiv", inactive: "Inaktiv", all: "Alle",
    media: "Format", mediaAll: "Alle Formate", image: "Bild", video: "Video", meme: "Bild mit Text", none: "Nur Text",
    platform: "Plattform", platformAll: "Alle Plattformen", exact: "Exakte Phrase", since: "Läuft seit", addCountry: "Land hinzufügen",
    ads: "Ads", advertisers: "Werbetreibende", loaded: "geladen", more: "Weitere laden", openLibrary: "In der Ad Library öffnen",
    sortNewest: "Neueste zuerst", sortRuntime: "Längste Laufzeit", sortReach: "Höchste EU-Reichweite", sort: "Sortierung",
    days: "Tage", day: "Tag", reach: "EU-Reichweite", started: "Start", stopped: "Gestoppt", running: "läuft",
    openProfile: "Marken-Profil öffnen", back: "Zurück zur Suche", loadingProfile: "Alle Ads der Marke werden geladen …", searching: "Suche läuft …",
    emptyTitle: "Keine Ads gefunden", emptyText: "Für diese Filter liefert Meta keine Ads. Prüfe Land und Status oder nutze ein allgemeineres Keyword.",
    startTitle: "Meta Ad Library durchsuchen", startText: "Suche nach Keyword oder öffne eine Marke über ihre Page-ID. Meta liefert für kommerzielle Ads nur Daten aus der EU.",
    activeAds: "Aktive Ads", totalAds: "Ads gesamt", oldest: "Älteste aktive", median: "Median Laufzeit", lastLaunch: "Letzter Start", totalReach: "EU-Reichweite gesamt",
    runtime: "Laufzeit der aktiven Ads", batches: "Launch-Batches", batchesHint: "Tage mit mindestens drei neu angelegten Ads.",
    variants: "Varianten-Gruppen", variantsHint: "Aktive Ads mit gleichem Haupttext, meist Platzierungen oder Dynamic Creative.",
    platforms: "Plattformen", offers: "Signale im Ad-Text", domains: "Landing-Domains", demo: "Erreichte Zielgruppe (EU)", topReach: "Höchste EU-Reichweite",
    age: "Alter", gender: "Geschlecht", female: "Frauen", male: "Männer", unknownG: "Unbekannt", country: "Länder",
    spend: "Spend-Schätzung", spendText: "Meta meldet für kommerzielle Ads keinen Spend. Die Schätzung rechnet EU-Reichweite × Frequenz × CPM. Trage Annahmen aus eigenen Konten ein; ohne Annahmen gibt es keinen Wert.",
    cpmLow: "CPM von (€)", cpmHigh: "CPM bis (€)", freqLow: "Frequenz von", freqHigh: "Frequenz bis", spendResult: "Geschätzter Spend über alle geladenen Ads", spendBasis: "Basis",
    spendNone: "Annahmen eintragen, um eine Spanne zu sehen.", estimate: "Schätzung, unkalibriert",
    limits: "Was diese Daten nicht zeigen", limitsText: "Laufzeit und Reichweite belegen weder Spend noch ROAS noch Creative Fatigue. Eine lange laufende Ad ist ein Hinweis, kein Gewinnerbeweis. Bilder und Videos liefert die API nicht; die Creatives öffnest du über den Link zur Ad Library.",
    incomplete: "Nicht alle Ads geladen", incompleteText: "Die Marke hat mehr Ads, als in einem Abruf geladen werden. Die Auswertung basiert auf den ersten Seiten. Grenze die Suche über Land oder Zeitraum ein.",
    diagnostics: "Diagnose", fetchedAt: "Abgerufen", pages: "Seiten", complete: "Vollständig", yes: "ja", no: "nein", usage: "API-Auslastung",
    allAds: "Alle geladenen Ads", onlyActive: "Nur aktive", n_ads: "Ads",
    offer_discount: "Rabatt / Sale", offer_free_shipping: "Gratis-Versand", offer_bundle: "Set / Bundle", offer_new: "Neuheit", offer_urgency: "Dringlichkeit", offer_social_proof: "Social Proof",
    b_lt7: "unter 7 Tage", b_d7_30: "7 bis 30 Tage", b_d31_90: "31 bis 90 Tage", b_gt90: "über 90 Tage",
    setupTitle: "Meta-Zugang fehlt", setupText: "Auf dem Server ist noch kein Meta-Token für die Ad Library hinterlegt. Rene legt es als Supabase-Secret META_AD_LIBRARY_TOKEN an. Bis dahin funktioniert die Suche nicht.",
    tokenTitle: "Meta-Zugang ungültig", tokenText: "Das hinterlegte Meta-Token wurde abgelehnt oder ist abgelaufen. Es muss erneuert werden.",
    err_NOT_CONFIGURED: "Auf dem Server ist noch kein Meta-Token hinterlegt.", err_TOKEN_INVALID: "Das Meta-Token ist abgelaufen oder ungültig.",
    err_ACCESS_DENIED: "Meta verweigert den Zugriff. Meist fehlt die Identitätsbestätigung für die Ad Library API beim Token-Inhaber.",
    err_RATE_LIMITED: "Meta drosselt gerade die Anfragen. In ein paar Minuten erneut versuchen.", err_COUNTRY_NOT_EU: "Meta liefert kommerzielle Ads nur für EU-Länder.",
    err_COUNTRY_REQUIRED: "Mindestens ein Land wählen.", err_QUERY_LENGTH: "Das Keyword braucht 2 bis 100 Zeichen.", err_INVALID_PAGE_ID: "Das ist keine gültige Page-ID oder kein Ad-Library-Link mit view_all_page_id.",
    err_INVALID_DATE: "Das Datum ist ungültig.", err_META_UNAVAILABLE: "Meta ist gerade nicht erreichbar.", err_FORBIDDEN: "Dieses Tool ist nur für das interne Team.", err_generic: "Die Anfrage ist fehlgeschlagen.",
    errorCode: "Fehlercode", retry: "Erneut versuchen",
  },
  en: {
    app: "Ad Library", search: "Search", keyword: "Keyword", brand: "Brand", keywordPh: "e.g. espresso machine or Black Sale",
    brandPh: "Page ID or Ad Library link (view_all_page_id=…)", countries: "Countries", status: "Status", active: "Active", inactive: "Inactive", all: "All",
    media: "Format", mediaAll: "All formats", image: "Image", video: "Video", meme: "Image with text", none: "Text only",
    platform: "Platform", platformAll: "All platforms", exact: "Exact phrase", since: "Running since", addCountry: "Add country",
    ads: "Ads", advertisers: "Advertisers", loaded: "loaded", more: "Load more", openLibrary: "Open in Ad Library",
    sortNewest: "Newest first", sortRuntime: "Longest running", sortReach: "Highest EU reach", sort: "Sort",
    days: "days", day: "day", reach: "EU reach", started: "Start", stopped: "Stopped", running: "running",
    openProfile: "Open brand profile", back: "Back to search", loadingProfile: "Loading every ad of this brand …", searching: "Searching …",
    emptyTitle: "No ads found", emptyText: "Meta returns no ads for these filters. Check country and status or try a broader keyword.",
    startTitle: "Search the Meta Ad Library", startText: "Search by keyword or open a brand by its page ID. For commercial ads Meta only provides EU data.",
    activeAds: "Active ads", totalAds: "Total ads", oldest: "Oldest active", median: "Median run time", lastLaunch: "Last start", totalReach: "Total EU reach",
    runtime: "Run time of active ads", batches: "Launch batches", batchesHint: "Days with at least three newly created ads.",
    variants: "Variant groups", variantsHint: "Active ads sharing the same primary text, usually placements or dynamic creative.",
    platforms: "Platforms", offers: "Signals in ad copy", domains: "Landing domains", demo: "Audience reached (EU)", topReach: "Highest EU reach",
    age: "Age", gender: "Gender", female: "Women", male: "Men", unknownG: "Unknown", country: "Countries",
    spend: "Spend estimate", spendText: "Meta reports no spend for commercial ads. The estimate is EU reach × frequency × CPM. Enter assumptions from our own accounts; no assumptions, no number.",
    cpmLow: "CPM from (€)", cpmHigh: "CPM to (€)", freqLow: "Frequency from", freqHigh: "Frequency to", spendResult: "Estimated spend across all loaded ads", spendBasis: "Basis",
    spendNone: "Enter assumptions to see a range.", estimate: "Estimate, uncalibrated",
    limits: "What this data does not show", limitsText: "Run time and reach prove neither spend nor ROAS nor creative fatigue. A long-running ad is a hint, not proof of a winner. The API returns no images or videos; open creatives via the Ad Library link.",
    incomplete: "Not every ad loaded", incompleteText: "This brand has more ads than one request loads. The analysis covers the first pages. Narrow it down by country or date.",
    diagnostics: "Diagnostics", fetchedAt: "Fetched", pages: "Pages", complete: "Complete", yes: "yes", no: "no", usage: "API usage",
    allAds: "All loaded ads", onlyActive: "Active only", n_ads: "ads",
    offer_discount: "Discount / sale", offer_free_shipping: "Free shipping", offer_bundle: "Set / bundle", offer_new: "New product", offer_urgency: "Urgency", offer_social_proof: "Social proof",
    b_lt7: "under 7 days", b_d7_30: "7 to 30 days", b_d31_90: "31 to 90 days", b_gt90: "over 90 days",
    setupTitle: "Meta access missing", setupText: "No Meta token for the Ad Library is stored on the server yet. Rene adds it as the Supabase secret META_AD_LIBRARY_TOKEN. Search does not work until then.",
    tokenTitle: "Meta access invalid", tokenText: "Meta rejected the stored token or it expired. It needs to be renewed.",
    err_NOT_CONFIGURED: "No Meta token is stored on the server yet.", err_TOKEN_INVALID: "The Meta token expired or is invalid.",
    err_ACCESS_DENIED: "Meta denied access. Usually the token owner has not confirmed their identity for the Ad Library API.",
    err_RATE_LIMITED: "Meta is throttling requests. Try again in a few minutes.", err_COUNTRY_NOT_EU: "Meta only returns commercial ads for EU countries.",
    err_COUNTRY_REQUIRED: "Pick at least one country.", err_QUERY_LENGTH: "The keyword needs 2 to 100 characters.", err_INVALID_PAGE_ID: "That is not a valid page ID or Ad Library link with view_all_page_id.",
    err_INVALID_DATE: "The date is invalid.", err_META_UNAVAILABLE: "Meta is not reachable right now.", err_FORBIDDEN: "This tool is for the internal team only.", err_generic: "The request failed.",
    errorCode: "Error code", retry: "Try again",
  },
};

const EU = ["DE", "AT", "NL", "BE", "FR", "IT", "ES", "PL", "SE", "DK", "FI", "IE", "PT", "CZ", "SK", "SI", "HR", "HU", "RO", "BG", "GR", "LU", "LT", "LV", "EE", "CY", "MT"];
const PLATFORM_LABEL = { FACEBOOK: "Facebook", INSTAGRAM: "Instagram", AUDIENCE_NETWORK: "Audience Network", MESSENGER: "Messenger", THREADS: "Threads", WHATSAPP: "WhatsApp" };

// Search state survives navigation to a profile and back.
const memory = { form: null, result: null, sort: "newest", tab: "ads" };

async function callAdLibrary(body) {
  const { data, error } = await window.sb.functions.invoke("ad-library", { body });
  if (error) {
    let code = "generic";
    try { const j = await error.context.json(); code = (j && j.error && j.error.code) || code; } catch (_) {}
    const e = new Error(code); e.code = code; throw e;
  }
  if (!data || data.ok === false) { const e = new Error("generic"); e.code = (data && data.error && data.error.code) || "generic"; throw e; }
  return data;
}

const nf = (lang) => new Intl.NumberFormat(lang === "de" ? "de-DE" : "en-GB");
function fmtDate(s, lang) {
  const t = E.parseDay(s); if (t == null) return "–";
  return new Date(t).toLocaleDateString(lang === "de" ? "de-DE" : "en-GB", { day: "2-digit", month: "2-digit", year: "numeric", timeZone: "UTC" });
}
function pct(x) { return `${Math.round(x * 100)} %`; }

function useLang() {
  const [lang, setLangState] = useState(() => { try { return localStorage.getItem("mesper.lang") || "de"; } catch (_) { return "de"; } });
  const setLang = (l) => { setLangState(l); try { localStorage.setItem("mesper.lang", l); } catch (_) {} };
  const t = (k) => (AL_DICT[lang] && AL_DICT[lang][k]) || AL_DICT.en[k] || k;
  return { lang, setLang, t };
}

/* ---------- Small building blocks ---------- */
function Panel({ title, hint, children, className = "" }) {
  return (
    <section className={`al-panel ${className}`}>
      {title && <header className="al-panel-head"><h3>{title}</h3>{hint && <p>{hint}</p>}</header>}
      {children}
    </section>
  );
}

function Notice({ tone = "info", title, children, action }) {
  return (
    <div className={`al-notice al-notice-${tone}`} role={tone === "error" ? "alert" : "status"}>
      <Icon name="info" size={20} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="al-notice-title">{title}</div>
        <div className="al-notice-text">{children}</div>
      </div>
      {action}
    </div>
  );
}

function ErrorNotice({ code, t, onRetry }) {
  const key = `err_${code}`;
  const text = AL_DICT.de[key] ? t(key) : t("err_generic");
  return (
    <Notice tone="error" title={text} action={onRetry && <Button variant="outline" size="sm" onClick={onRetry}>{t("retry")}</Button>}>
      {t("errorCode")}: {code}
    </Notice>
  );
}

function Bars({ rows, format }) {
  const max = Math.max(1, ...rows.map((r) => r.value));
  return (
    <div className="al-bars">
      {rows.map((r) => (
        <div className="al-bar-row" key={r.key}>
          <span className="al-bar-label">{r.label}</span>
          <span className="al-bar-track"><span className="al-bar-fill" style={{ width: `${(r.value / max) * 100}%` }} /></span>
          <span className="al-bar-value">{format ? format(r.value) : r.value}</span>
        </div>
      ))}
    </div>
  );
}

function MetricsBar({ items }) {
  return (
    <div className="al-metrics" role="list">
      {items.map((m) => (
        <div className="al-metric" role="listitem" key={m.label}>
          <div className="al-metric-label">{m.label}</div>
          <div className="al-metric-value">{m.value}</div>
        </div>
      ))}
    </div>
  );
}

function AdRow({ ad, lang, t, onBrand, now }) {
  const days = E.runtimeDays(ad, now);
  const active = E.isActive(ad, now);
  const text = E.primaryText(ad);
  return (
    <article className="al-ad">
      <div className="al-ad-main">
        <div className="al-ad-meta">
          {onBrand && ad.pageId
            ? <button type="button" className="al-link-btn" onClick={() => onBrand(ad.pageId, ad.pageName)}>{ad.pageName || ad.pageId}</button>
            : <strong>{ad.pageName || ad.pageId}</strong>}
          <span>·</span>
          <span>{t("started")} {fmtDate(ad.startAt || ad.createdAt, lang)}</span>
          <span>·</span>
          <span className={active ? "al-state-on" : "al-state-off"}>
            {active ? `${t("running")} ${days != null ? `${days} ${days === 1 ? t("day") : t("days")}` : ""}` : `${t("stopped")} ${fmtDate(ad.stopAt, lang)}`}
          </span>
        </div>
        {ad.titles && ad.titles[0] && ad.titles[0] !== text && <div className="al-ad-title">{ad.titles[0]}</div>}
        {text && <p className="al-ad-text">{text}</p>}
        <div className="al-ad-foot">
          {(ad.platforms || []).map((p) => <span key={p}>{PLATFORM_LABEL[p] || p}</span>)}
          {ad.captions && ad.captions[0] && <span>{ad.captions[0]}</span>}
        </div>
      </div>
      <div className="al-ad-side">
        <div className="al-ad-reach">
          <div className="al-metric-label">{t("reach")}</div>
          <div>{ad.euReach != null ? nf(lang).format(ad.euReach) : "–"}</div>
        </div>
        <a className="al-open" href={ad.url} target="_blank" rel="noopener noreferrer"><Icon name="link" size={15} />{t("openLibrary")}</a>
      </div>
    </article>
  );
}

function sortAds(ads, sort, now) {
  const list = ads.slice();
  if (sort === "runtime") list.sort((a, b) => (E.runtimeDays(b, now) || 0) - (E.runtimeDays(a, now) || 0));
  else if (sort === "reach") list.sort((a, b) => (b.euReach || 0) - (a.euReach || 0));
  else list.sort((a, b) => (E.parseDay(b.startAt) || 0) - (E.parseDay(a.startAt) || 0));
  return list;
}

/* ---------- Search form ---------- */
const DEFAULT_FORM = { mode: "keyword", query: "", countries: ["DE"], status: "ACTIVE", mediaType: "ALL", platform: "", exact: false, dateMin: "" };

function SearchForm({ form, setForm, onSubmit, busy, t }) {
  const [adding, setAdding] = useState("");
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const removeCountry = (c) => set("countries", form.countries.filter((x) => x !== c));
  const chips = [
    ...form.countries.map((c) => ({ key: `c-${c}`, label: c, onRemove: form.countries.length > 1 ? () => removeCountry(c) : null })),
    form.status !== "ACTIVE" && { key: "status", label: form.status === "ALL" ? t("all") : t("inactive"), onRemove: () => set("status", "ACTIVE") },
    form.mediaType !== "ALL" && { key: "media", label: t({ IMAGE: "image", VIDEO: "video", MEME: "meme", NONE: "none" }[form.mediaType]), onRemove: () => set("mediaType", "ALL") },
    form.platform && { key: "platform", label: PLATFORM_LABEL[form.platform], onRemove: () => set("platform", "") },
    form.exact && form.mode === "keyword" && { key: "exact", label: t("exact"), onRemove: () => set("exact", false) },
    form.dateMin && { key: "date", label: `${t("since")} ${form.dateMin}`, onRemove: () => set("dateMin", "") },
  ].filter(Boolean);

  return (
    <form className="al-search" onSubmit={(e) => { e.preventDefault(); onSubmit(); }}>
      <div className="al-search-row">
        <div className="al-segment" role="radiogroup" aria-label={t("search")}>
          {["keyword", "page"].map((m) => (
            <button key={m} type="button" role="radio" aria-checked={form.mode === m} className={form.mode === m ? "is-on" : ""} onClick={() => set("mode", m)}>
              {m === "keyword" ? t("keyword") : t("brand")}
            </button>
          ))}
        </div>
        <label className="al-input-wrap">
          <Icon name="search" size={18} />
          <input value={form.query} onChange={(e) => set("query", e.target.value)} placeholder={form.mode === "keyword" ? t("keywordPh") : t("brandPh")} aria-label={form.mode === "keyword" ? t("keyword") : t("brand")} />
        </label>
        <Button type="submit" disabled={busy || form.query.trim().length < 2}>{busy ? t("searching") : t("search")}</Button>
      </div>
      <div className="al-filter-row">
        <label className="al-field"><span>{t("addCountry")}</span>
          <select value={adding} onChange={(e) => { const c = e.target.value; setAdding(""); if (c && !form.countries.includes(c) && form.countries.length < 10) set("countries", [...form.countries, c]); }}>
            <option value="">{t("countries")} …</option>
            {EU.filter((c) => !form.countries.includes(c)).map((c) => <option key={c} value={c}>{c}</option>)}
          </select>
        </label>
        <label className="al-field"><span>{t("status")}</span>
          <select value={form.status} onChange={(e) => set("status", e.target.value)}>
            <option value="ACTIVE">{t("active")}</option><option value="ALL">{t("all")}</option><option value="INACTIVE">{t("inactive")}</option>
          </select>
        </label>
        <label className="al-field"><span>{t("media")}</span>
          <select value={form.mediaType} onChange={(e) => set("mediaType", e.target.value)}>
            <option value="ALL">{t("mediaAll")}</option><option value="IMAGE">{t("image")}</option><option value="VIDEO">{t("video")}</option><option value="MEME">{t("meme")}</option><option value="NONE">{t("none")}</option>
          </select>
        </label>
        <label className="al-field"><span>{t("platform")}</span>
          <select value={form.platform} onChange={(e) => set("platform", e.target.value)}>
            <option value="">{t("platformAll")}</option>
            {Object.keys(PLATFORM_LABEL).map((p) => <option key={p} value={p}>{PLATFORM_LABEL[p]}</option>)}
          </select>
        </label>
        <label className="al-field"><span>{t("since")}</span>
          <input type="date" value={form.dateMin} onChange={(e) => set("dateMin", e.target.value)} />
        </label>
        {form.mode === "keyword" && (
          <label className="al-check"><input type="checkbox" checked={form.exact} onChange={(e) => set("exact", e.target.checked)} />{t("exact")}</label>
        )}
      </div>
      {chips.length > 0 && (
        <div className="al-chips">
          {chips.map((c) => (
            <span className="al-chip" key={c.key}>{c.label}
              {c.onRemove && <button type="button" aria-label={`${c.label} ×`} onClick={c.onRemove}><Icon name="x" size={13} stroke={2} /></button>}
            </span>
          ))}
        </div>
      )}
    </form>
  );
}

function toRequest(form, after) {
  const base = { countries: form.countries, status: form.status, mediaType: form.mediaType, platforms: form.platform ? [form.platform] : [], dateMin: form.dateMin || undefined };
  if (form.mode === "page") return { action: "search", mode: "page", pageIds: [form.query.trim()], ...base, after };
  return { action: "search", mode: "keyword", query: form.query.trim(), searchType: form.exact ? "KEYWORD_EXACT_PHRASE" : "KEYWORD_UNORDERED", ...base, after };
}

/* ---------- Search view ---------- */
function SearchView({ t, lang, navigate, status }) {
  const [form, setForm] = useState(memory.form || DEFAULT_FORM);
  const [result, setResult] = useState(memory.result);
  const [sort, setSort] = useState(memory.sort);
  const [tab, setTab] = useState(memory.tab);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState(null);
  const now = Date.now();
  useEffect(() => { memory.form = form; memory.result = result; memory.sort = sort; memory.tab = tab; }, [form, result, sort, tab]);

  async function run(after) {
    setBusy(true); setErr(null);
    try {
      const data = await callAdLibrary(toRequest(form, after));
      setResult((prev) => after && prev ? { ...data, ads: prev.ads.concat(data.ads) } : data);
      if (!after) setTab("ads");
    } catch (e) { setErr(e.code || "generic"); }
    finally { setBusy(false); }
  }
  const openBrand = (raw) => {
    const s = String(raw || "").trim();
    const id = /^\d{3,25}$/.test(s) ? s : ((s.match(/[?&](?:view_all_page_id|search_page_ids|page_id)=(\d{3,25})/) || [])[1]);
    if (!id) { setErr("INVALID_PAGE_ID"); return; }
    navigate(`/ad-library/p/${id}?c=${form.countries.join(",")}`);
  };
  const ads = useMemo(() => (result ? sortAds(result.ads, sort, now) : []), [result, sort]);
  const pages = useMemo(() => (result ? E.pages(result.ads) : []), [result]);

  return (
    <div className="al-stack">
      <StatusNotice status={status} t={t} />
      <SearchForm form={form} setForm={setForm} onSubmit={() => (form.mode === "page" ? openBrand(form.query.trim()) : run())} busy={busy} t={t} />
      {err && <ErrorNotice code={err} t={t} onRetry={() => run()} />}
      {!result && !err && (
        <div className="al-empty"><Icon name="search" size={26} /><h2>{t("startTitle")}</h2><p>{t("startText")}</p></div>
      )}
      {result && result.ads.length === 0 && (
        <div className="al-empty"><Icon name="search" size={26} /><h2>{t("emptyTitle")}</h2><p>{t("emptyText")}</p></div>
      )}
      {result && result.ads.length > 0 && (
        <>
          <div className="al-results-head">
            <div className="al-tabs" role="tablist">
              <button type="button" role="tab" aria-selected={tab === "ads"} className={tab === "ads" ? "is-on" : ""} onClick={() => setTab("ads")}>{t("ads")} <span>{result.ads.length}</span></button>
              <button type="button" role="tab" aria-selected={tab === "pages"} className={tab === "pages" ? "is-on" : ""} onClick={() => setTab("pages")}>{t("advertisers")} <span>{pages.length}</span></button>
            </div>
            {tab === "ads" && (
              <label className="al-field al-field-inline"><span>{t("sort")}</span>
                <select value={sort} onChange={(e) => setSort(e.target.value)}>
                  <option value="newest">{t("sortNewest")}</option><option value="runtime">{t("sortRuntime")}</option><option value="reach">{t("sortReach")}</option>
                </select>
              </label>
            )}
          </div>
          {tab === "ads" && <div className="al-list">{ads.map((ad) => <AdRow key={ad.id} ad={ad} lang={lang} t={t} onBrand={openBrand} now={now} />)}</div>}
          {tab === "pages" && (
            <div className="al-list">
              {pages.map((p) => (
                <button type="button" key={p.pageId} className="al-page-row" onClick={() => openBrand(p.pageId)}>
                  <span><strong>{p.pageName}</strong><small>Page-ID {p.pageId}</small></span>
                  <span>{p.count} {t("n_ads")} {t("loaded")}</span>
                  <Icon name="arrowRight" size={18} />
                </button>
              ))}
            </div>
          )}
          {result.next && <div className="al-more"><Button variant="outline" disabled={busy} onClick={() => run(result.next)}>{busy ? t("searching") : t("more")}</Button></div>}
        </>
      )}
    </div>
  );
}

function StatusNotice({ status, t }) {
  if (!status) return null;
  if (status.configured === false) return <Notice tone="warn" title={t("setupTitle")}>{t("setupText")}</Notice>;
  if (status.valid === false) return <Notice tone="error" title={t("tokenTitle")}>{t("tokenText")} {status.reason ? `(${status.reason})` : ""}</Notice>;
  return null;
}

/* ---------- Brand profile ---------- */
function SpendPanel({ reach, t, lang }) {
  const [a, setA] = useState(() => { try { return JSON.parse(localStorage.getItem("mesper.adlib.spend") || "{}"); } catch (_) { return {}; } });
  useEffect(() => { try { localStorage.setItem("mesper.adlib.spend", JSON.stringify(a)); } catch (_) {} }, [a]);
  const est = E.spendEstimate(reach, a);
  const money = (v) => new Intl.NumberFormat(lang === "de" ? "de-DE" : "en-GB", { style: "currency", currency: "EUR", maximumFractionDigits: 0 }).format(v);
  const field = (k) => (
    <label className="al-field" key={k}><span>{t(k)}</span>
      <input type="number" min="0" step="0.1" inputMode="decimal" value={a[k] ?? ""} onChange={(e) => setA((x) => ({ ...x, [k]: e.target.value }))} />
    </label>
  );
  return (
    <Panel title={t("spend")} hint={t("spendText")}>
      <div className="al-spend-grid">{["cpmLow", "cpmHigh", "freqLow", "freqHigh"].map(field)}</div>
      <div className="al-spend-result">
        {est
          ? <><div className="al-metric-label">{t("spendResult")} · {t("estimate")}</div><div className="al-spend-value">{money(est.low)} – {money(est.high)}</div>
              <div className="al-muted">{t("spendBasis")}: {nf(lang).format(reach)} {t("reach")}</div></>
          : <div className="al-muted">{t("spendNone")}</div>}
      </div>
    </Panel>
  );
}

function ProfileView({ t, lang, pageId, countries, navigate }) {
  const [state, setState] = useState({ loading: true });
  const [onlyActive, setOnlyActive] = useState(true);
  const [sort, setSort] = useState("runtime");
  const now = Date.now();
  async function load() {
    setState({ loading: true });
    try {
      const data = await callAdLibrary({ action: "profile", pageIds: [pageId], countries, status: "ALL" });
      setState({ data });
    } catch (e) { setState({ err: e.code || "generic" }); }
  }
  useEffect(() => { load(); }, [pageId, countries.join(",")]);

  const p = useMemo(() => (state.data ? E.profile(state.data.ads, now) : null), [state.data]);
  const list = useMemo(() => {
    if (!state.data) return [];
    const ads = onlyActive ? state.data.ads.filter((a) => E.isActive(a, now)) : state.data.ads;
    return sortAds(ads, sort, now);
  }, [state.data, onlyActive, sort]);
  const name = state.data && state.data.ads[0] ? state.data.ads[0].pageName : pageId;
  const n = nf(lang);

  return (
    <div className="al-stack">
      <div className="al-profile-head">
        <button type="button" className="al-back" onClick={() => navigate("/ad-library")}><Icon name="arrowLeft" size={16} />{t("back")}</button>
        <h1>{name}</h1>
        <div className="al-muted">Page-ID {pageId} · {countries.join(", ")} · <a href={`https://www.facebook.com/ads/library/?active_status=active&ad_type=all&country=${countries[0]}&view_all_page_id=${encodeURIComponent(pageId)}`} target="_blank" rel="noopener noreferrer">{t("openLibrary")}</a></div>
      </div>
      {state.loading && <div className="al-empty"><p>{t("loadingProfile")}</p></div>}
      {state.err && <ErrorNotice code={state.err} t={t} onRetry={load} />}
      {p && (
        <>
          {!state.data.complete && <Notice tone="warn" title={t("incomplete")}>{t("incompleteText")}</Notice>}
          <MetricsBar items={[
            { label: t("activeAds"), value: n.format(p.active) },
            { label: t("totalAds"), value: n.format(p.total) },
            { label: t("oldest"), value: p.oldestActiveDays != null ? `${p.oldestActiveDays} ${t("days")}` : "–" },
            { label: t("median"), value: p.medianActiveDays != null ? `${p.medianActiveDays} ${t("days")}` : "–" },
            { label: t("lastLaunch"), value: fmtDate(p.lastLaunch, lang) },
            { label: t("totalReach"), value: p.reach.withReach ? n.format(p.reach.total) : "–" },
          ]} />
          <div className="al-grid">
            <Panel title={t("runtime")}>
              <Bars rows={["lt7", "d7_30", "d31_90", "gt90"].map((k) => ({ key: k, label: t(`b_${k}`), value: p.buckets[k] }))} />
            </Panel>
            <Panel title={t("platforms")}>
              {p.platforms.length ? <Bars rows={p.platforms.map((x) => ({ key: x.key, label: PLATFORM_LABEL[x.key] || x.key, value: x.count }))} /> : <div className="al-muted">–</div>}
            </Panel>
            <Panel title={t("offers")}>
              <Bars rows={Object.keys(p.offers).map((k) => ({ key: k, label: t(`offer_${k}`), value: p.offers[k] }))} />
            </Panel>
            <Panel title={t("domains")}>
              {p.domains.length ? <Bars rows={p.domains.slice(0, 6).map((x) => ({ key: x.key, label: x.key, value: x.count }))} /> : <div className="al-muted">–</div>}
            </Panel>
          </div>
          <div className="al-grid al-grid-2">
            <Panel title={t("batches")} hint={t("batchesHint")}>
              {p.batches.length ? (
                <ul className="al-rows">{p.batches.slice(0, 8).map((b) => (
                  <li key={b.day}><span className="al-row-key">{fmtDate(b.day, lang)}</span><span className="al-row-text">{b.headline || "–"}</span><span className="al-row-num">{b.count}</span></li>
                ))}</ul>
              ) : <div className="al-muted">–</div>}
            </Panel>
            <Panel title={t("variants")} hint={t("variantsHint")}>
              {p.variants.length ? (
                <ul className="al-rows">{p.variants.slice(0, 8).map((g) => (
                  <li key={g.key}><span className="al-row-text">{g.text}</span><span className="al-row-num">{g.ads.length}</span></li>
                ))}</ul>
              ) : <div className="al-muted">–</div>}
            </Panel>
          </div>
          {p.demographics.total > 0 && (
            <Panel title={t("demo")}>
              <div className="al-grid al-grid-3">
                <div><div className="al-sub">{t("age")}</div><Bars rows={p.demographics.age.map((x) => ({ key: x.key, label: x.key, value: x.share }))} format={pct} /></div>
                <div><div className="al-sub">{t("gender")}</div><Bars rows={[
                  { key: "f", label: t("female"), value: p.demographics.gender.female },
                  { key: "m", label: t("male"), value: p.demographics.gender.male },
                  { key: "u", label: t("unknownG"), value: p.demographics.gender.unknown },
                ]} format={pct} /></div>
                <div><div className="al-sub">{t("country")}</div><Bars rows={p.demographics.country.slice(0, 6).map((x) => ({ key: x.key, label: x.key, value: x.share }))} format={pct} /></div>
              </div>
            </Panel>
          )}
          {p.reach.withReach > 0 && <SpendPanel reach={p.reach.total} t={t} lang={lang} />}
          <Notice tone="info" title={t("limits")}>{t("limitsText")}</Notice>
          <div className="al-results-head">
            <h2 className="al-h2">{t("allAds")} <span className="al-muted">{list.length}</span></h2>
            <div style={{ display: "flex", gap: 14, alignItems: "center", flexWrap: "wrap" }}>
              <label className="al-check"><input type="checkbox" checked={onlyActive} onChange={(e) => setOnlyActive(e.target.checked)} />{t("onlyActive")}</label>
              <label className="al-field al-field-inline"><span>{t("sort")}</span>
                <select value={sort} onChange={(e) => setSort(e.target.value)}>
                  <option value="runtime">{t("sortRuntime")}</option><option value="newest">{t("sortNewest")}</option><option value="reach">{t("sortReach")}</option>
                </select>
              </label>
            </div>
          </div>
          <div className="al-list">{list.slice(0, 200).map((ad) => <AdRow key={ad.id} ad={ad} lang={lang} t={t} now={now} />)}</div>
          <details className="al-diag">
            <summary>{t("diagnostics")}</summary>
            <dl>
              <dt>{t("fetchedAt")}</dt><dd>{new Date(state.data.fetchedAt).toLocaleString(lang === "de" ? "de-DE" : "en-GB")}</dd>
              <dt>{t("pages")}</dt><dd>{state.data.pages}</dd>
              <dt>{t("complete")}</dt><dd>{state.data.complete ? t("yes") : t("no")}</dd>
              <dt>{t("usage")}</dt><dd><code>{JSON.stringify(state.data.usage)}</code></dd>
            </dl>
          </details>
        </>
      )}
    </div>
  );
}

/* ---------- App shell ---------- */
function AdLibraryApp({ user, onHome, path, navigate }) {
  const { lang, setLang, t } = useLang();
  const narrow = useIsNarrow(820);
  const [status, setStatus] = useState(null);
  useEffect(() => { callAdLibrary({ action: "status" }).then(setStatus).catch((e) => setStatus({ configured: true, valid: false, reason: e.code })); }, []);

  const sub = (path || "").replace(/^\/ad-library\/?/, "");
  const profileMatch = sub.match(/^p\/([^/?#]+)/);
  const params = new URLSearchParams(window.location.search);
  const countries = (params.get("c") || "DE").split(",").map((c) => c.trim().toUpperCase()).filter((c) => EU.includes(c)).slice(0, 10);

  return (
    <div className="work-app-shell al-scope" style={{ height: "100vh", display: "flex", flexDirection: "column" }}>
      <WorkAppHeader app="Ad Library" user={user} onHome={onHome} navigate={navigate}>
        <div className="al-lang">
          {["de", "en"].map((l) => <button key={l} type="button" className={lang === l ? "is-on" : ""} onClick={() => setLang(l)}>{l.toUpperCase()}</button>)}
        </div>
      </WorkAppHeader>
      <main style={{ flex: 1, minWidth: 0, overflowY: "auto", padding: narrow ? "16px 16px 60px" : "24px 28px 60px" }}>
        <div className="al-container">
          {profileMatch
            ? <ProfileView key={profileMatch[1] + countries.join(",")} t={t} lang={lang} pageId={decodeURIComponent(profileMatch[1])} countries={countries.length ? countries : ["DE"]} navigate={navigate} />
            : <SearchView t={t} lang={lang} navigate={navigate} status={status} />}
        </div>
      </main>
    </div>
  );
}

Object.assign(window, { AdLibraryApp });
})();
