/* Header · KPI strip · Platforms */

// Force-refetch all same-origin app files past the browser cache, then reload — a real "hard refresh"
// from a button (works because the Cloudflare edge serves fresh after a deploy/purge).
async function hardReloadApp(setBusy) {
  try {
    if (setBusy) setBusy(true);
    const urls = [].slice.call(document.querySelectorAll("script[src],link[href]"))
      .map(e => e.src || e.href).filter(u => u && u.indexOf(location.origin) === 0);
    urls.push(location.origin + "/index.html", location.origin + "/");
    await Promise.allSettled([...new Set(urls)].map(u => fetch(u, { cache: "reload" })));
  } catch (e) {}
  location.reload();
}

function Header({ mode, refreshing, onRefresh, P, refreshRange, setRefreshRange }) {
  const [hardBusy, setHardBusy] = React.useState(false);
  return (
    <div className="topbar">
      <div>
        <div className="brandmark">
          <LogoUnit />
          <div>
            <div className="eyebrow brand-eyebrow">ADORE&nbsp;&nbsp;HOMES</div>
          </div>
        </div>
        <h1 className="h-title">Google &amp; Meta Ads Control Center</h1>
        <div className="h-sub">
          <span>Generate <b>Higgsfield</b></span><span className="arr">→</span>
          <span>choose</span><span className="arr">→</span>
          <span>push to Meta <b>(paused)</b></span><span className="arr">→</span>
          <span>track performance</span>
        </div>
      </div>

      <div className="topbar-right">
        {setRefreshRange && (
          <select value={refreshRange} onChange={e => setRefreshRange(e.target.value)} disabled={refreshing}
            title="Time window for Meta ad performance"
            style={{ background: "var(--s2,#fff)", color: "var(--t1)", border: "1px solid var(--line,#d8d2c8)", borderRadius: 9, padding: "0 10px", height: 36, fontSize: 13, fontFamily: "inherit", cursor: "pointer" }}>
            <option value="7">Last 7 days</option>
            <option value="30">Last 30 days</option>
            <option value="90">Last 90 days</option>
            <option value="max">Lifetime</option>
          </select>
        )}
        <button className="btn btn-accent" onClick={() => onRefresh()} disabled={refreshing}>
          <Ico d={I.refresh} s={15} cls={refreshing ? "spin" : ""} />
          {refreshing ? "Refreshing…" : "Refresh from Meta"}
        </button>
        <button className="btn btn-ghost" onClick={() => hardReloadApp(setHardBusy)} disabled={hardBusy}
          title="Force-fetch the newest version of the app (bypasses cache)">
          <Ico d={I.refresh} s={15} cls={hardBusy ? "spin" : ""} />
          {hardBusy ? "Updating…" : "Get latest version"}
        </button>
        <div className={"mode-pill " + (mode === "live" ? "live" : "")}>
          <span className="dot"></span>{mode === "live" ? ("Live · " + ({ "7": "last 7 days", "30": "last 30 days", "90": "last 90 days", "max": "lifetime" }[refreshRange] || "from Meta")) : "Pipeline mode"}
        </div>
        <div className="meta-of-meta">
          acct <b>{P.account}</b><br />
          Target CPL <b>≤ ${P.target_cpl}</b> · data <b>{P.dataDate}</b>
        </div>
      </div>
    </div>
  );
}

function PlatformStrip({ mode, meta, P }) {
  const HS = window.__ADORE_HUBSPOT;   // real leads coming in (HubSpot form fills), by platform
  return (
    <div className="platforms">
      <div className="plat meta">
        <div className="glow"></div>
        <div className="plat-head"><span className="plat-badge">Meta Ads · ADORE ADU</span></div>
        <div className="plat-num">{fmt.money(meta.spend)} <small>· {HS ? HS.facebook.leads : meta.leads} leads</small></div>
        <div className="plat-sub">
          {HS
            ? <><b style={{ color: "var(--acc)" }}>{HS.facebook.leads} Facebook leads</b> in HubSpot · {HS.range} · {meta.creatives} creatives</>
            : (mode === "live"
              ? <>{meta.active} active · {meta.creatives} creatives · blended CPL <b style={{ color: "var(--t2)" }}>{fmt.cpl(meta.cpl)}</b></>
              : <>Click ⟳ Refresh from Meta · {meta.creatives} creatives</>)}
        </div>
      </div>
      <div className="plat google">
        <div className="glow"></div>
        <div className="plat-head"><span className="plat-badge">Google Ads · Last 30 days</span></div>
        <div className="plat-num">{fmt.money(P.google.spend)} <small>· {HS ? HS.google.leads : P.google.conversions} leads{HS && HS.google.cpl ? " · $" + HS.google.cpl + " CPL" : ""}</small></div>
        <div className="plat-sub">{HS ? <><b style={{ color: "var(--acc)" }}>{HS.google.leads} leads</b> in HubSpot · {P.google.conversions} Google-tracked conv · top: {P.google.top}</> : <>{P.google.enabled} · top: {P.google.top}</>}</div>
      </div>
    </div>
  );
}

function KpiStrip({ mode, k }) {
  const cplOver = mode === "live" && k.cpl != null && k.cpl > k.target;
  const HS = window.__ADORE_HUBSPOT;   // real leads coming in (HubSpot), overrides pixel/blended count
  return (
    <div className="kpis">
      <Kpi label="Creatives" val={k.creatives} foot={`${k.images} image · ${k.videos} video`} />
      <Kpi label="Selected to launch" val={k.selected} accent={k.selected > 0}
           foot={k.selected > 0 ? "ready to push (paused)" : "none selected"} />
      <Kpi label="Total spend" val={mode === "live" ? fmt.money(k.spend) : "$0"}
           foot={mode === "live" ? "across active ads" : "pipeline — no spend"} />
      <Kpi label="Leads" val={HS ? HS.total : (mode === "live" ? k.leads : 0)}
           accent={!!HS}
           foot={HS ? `${HS.facebook.leads} Facebook · ${HS.google.leads} Google · HubSpot ${HS.range.toLowerCase()}`
                    : (mode === "live" ? `${fmt.pct(k.ctr)} blended CTR` : "awaiting launch")} />
      <Kpi label="Blended CPL"
           val={mode === "live" ? (k.cpl != null ? fmt.cpl(k.cpl) : "—") : "—"}
           good={mode === "live" && k.cpl != null && !cplOver} bad={cplOver}
           foot={mode === "live" ? `target ≤ $${k.target}` : "target ≤ $" + k.target}
           spark={mode === "live" ? k.cplTrend : null} sparkColor={cplOver ? "var(--bad)" : "var(--ok)"} />
      <Kpi label="Active ads" val={mode === "live" ? k.active : 0}
           good={mode === "live" && k.active > 0}
           foot={mode === "live" ? `${k.fatigued} fatigued · ${k.under} under` : "all paused"} />
    </div>
  );
}

function Kpi({ label, val, foot, good, bad, accent, spark, sparkColor }) {
  return (
    <div className={"kpi" + (good ? " good" : "") + (bad ? " bad" : "") + (accent ? " accent" : "")}>
      <div className="kpi-label">{label}</div>
      <div className="kpi-val">{val}</div>
      <div className="kpi-foot">{foot}</div>
      {spark && <Spark vals={spark} color={sparkColor} />}
    </div>
  );
}

Object.assign(window, { Header, PlatformStrip, KpiStrip });
