/* global React */
// Terminal LatAm — Connect screen (platform integrations)

const TC_T = window.T_THEME;
const TC_FM = window.T_FM;
const TC_FS = window.T_FS;
const TC_S = window.TerminalSectionLabel;
const TC_B = window.TerminalBtn;

const StatusDot = ({ s }) => {
  const c = s === "ok" ? TC_T.green : s === "warn" ? TC_T.amber : s === "off" ? TC_T.muteDim : TC_T.red;
  return <span style={{ display: "inline-block", width: 8, height: 8, borderRadius: 99, background: c, marginRight: 8 }} />;
};

const PlatformCard = ({ p }) => {
  const off = p.status === "off";
  return (
    <div style={{
      border: `1px solid ${off ? TC_T.line : p.status === "warn" ? TC_T.amber : TC_T.line}`,
      borderLeft: `3px solid ${off ? TC_T.muteDim : p.status === "warn" ? TC_T.amber : TC_T.green}`,
      background: TC_T.surface, padding: "16px 18px", opacity: off ? 0.6 : 1,
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
        <div style={{ width: 36, height: 36, background: p.color, color: "#000", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: TC_FS, fontWeight: 700, fontSize: 18, borderRadius: 0 }}>
          {p.icon}
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: TC_FS, fontSize: 14, fontWeight: 600, color: TC_T.ink }}>{p.name}</div>
          <div style={{ fontSize: 10, color: TC_T.muteDim, marginTop: 2 }}>{p.oauth}</div>
        </div>
        <StatusDot s={p.status} />
      </div>

      {!off ? (
        <>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 12, fontSize: 10 }}>
            <div><span style={{ color: TC_T.muteDim }}>last sync · </span><span style={{ color: TC_T.ink, fontFamily: TC_FM }}>{p.lastSync}</span></div>
            <div><span style={{ color: TC_T.muteDim }}>events 24h · </span><span style={{ color: TC_T.cyan, fontFamily: TC_FM }}>{p.events24h.toLocaleString()}</span></div>
            <div><span style={{ color: TC_T.muteDim }}>EMQ · </span><span style={{ color: p.emq >= 8 ? TC_T.green : p.emq >= 7 ? TC_T.amber : TC_T.red, fontFamily: TC_FM }}>{p.emq ?? "—"}</span></div>
            <div><span style={{ color: TC_T.muteDim }}>cuentas · </span><span style={{ color: TC_T.ink, fontFamily: TC_FM }}>{p.accounts.length}</span></div>
          </div>
          <div style={{ padding: "8px 10px", background: TC_T.bg, fontSize: 9, color: TC_T.muteDim, fontFamily: TC_FM, marginBottom: 10, lineHeight: 1.5 }}>
            scope · {p.scope}
          </div>
          {p.note && (
            <div style={{ padding: "8px 10px", background: TC_T.bg, border: `1px solid ${TC_T.amber}`, fontSize: 10, color: TC_T.amber, marginBottom: 10 }}>! {p.note}</div>
          )}
          <div style={{ display: "flex", gap: 6 }}>
            <TC_B>SYNC NOW</TC_B>
            <TC_B>VER CUENTAS · {p.accounts.length}</TC_B>
            <TC_B>RE-AUTH</TC_B>
          </div>
        </>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          <div style={{ fontSize: 10, color: TC_T.muteDim, padding: "16px 0" }}>No conectado</div>
          <TC_B kind="amber">CONECTAR</TC_B>
        </div>
      )}
    </div>
  );
};

const Strip = ({ title, items, cols, render }) => (
  <div>
    <TC_S text={title} />
    <div style={{ marginTop: 12, display: "grid", gridTemplateColumns: `repeat(${cols},1fr)`, gap: 12 }}>
      {items.map((it,i) => render(it,i))}
    </div>
  </div>
);

const ConnectScreen = () => {
  const D = window.MA_DATA.connections;
  const totalEvents = D.adPlatforms.reduce((s,p) => s+p.events24h, 0);

  return (
    <div className="ma-pad" style={{ padding: "20px 24px", display: "flex", flexDirection: "column", gap: 24 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end" }}>
        <div>
          <div style={{ fontSize: 10, color: TC_T.mute, letterSpacing: "0.18em", marginBottom: 6 }}>// CONNECT · integraciones</div>
          <div style={{ fontFamily: TC_FS, fontSize: 26, fontWeight: 600, color: TC_T.ink }}>Conexiones · 4 plataformas activas · <span style={{ color: TC_T.cyan }}>{(totalEvents/1e6).toFixed(1)}M eventos/24h</span></div>
          <div style={{ fontSize: 11, color: TC_T.mute, marginTop: 4 }}>OAuth scopes mínimos · CAPI server-side · CRM round-trip · MMM nightly · Consent Mode v2</div>
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          <TC_B kind="amber">+ AÑADIR PLATAFORMA</TC_B>
          <TC_B>RE-VALIDATE ALL</TC_B>
          <TC_B>EXPORT CONFIG</TC_B>
        </div>
      </div>

      {/* AD PLATFORMS */}
      <Strip
        title="AD PLATFORMS"
        items={D.adPlatforms} cols={3}
        render={(p) => <PlatformCard key={p.id} p={p} />}
      />

      {/* CAPI / EVENTS API */}
      <Strip
        title="CAPI · server-side events"
        items={D.capi} cols={3}
        render={(c,i) => (
          <div key={i} style={{ border: `1px solid ${TC_T.line}`, padding: "14px 16px", background: TC_T.surface }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
              <span style={{ color: TC_T.ink, fontSize: 12, fontFamily: TC_FS, fontWeight: 500 }}>{c.name}</span>
              <StatusDot s={c.status} />
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10, fontSize: 10 }}>
              <div><div style={{ color: TC_T.muteDim }}>events</div><div style={{ color: TC_T.cyan, fontFamily: TC_FM, marginTop: 3 }}>{(c.events24h/1000).toFixed(0)}k</div></div>
              <div><div style={{ color: TC_T.muteDim }}>dedupe</div><div style={{ color: c.dedupe > 0.95 ? TC_T.green : TC_T.amber, fontFamily: TC_FM, marginTop: 3 }}>{(c.dedupe*100).toFixed(1)}%</div></div>
              <div><div style={{ color: TC_T.muteDim }}>latency</div><div style={{ color: TC_T.ink, fontFamily: TC_FM, marginTop: 3 }}>{c.lat}</div></div>
            </div>
          </div>
        )}
      />

      {/* CRM + MEASUREMENT + WEB */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16 }}>
        <div>
          <TC_S text="CRM" />
          <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 10 }}>
            {D.crm.map((c,i) => (
              <div key={i} style={{ border: `1px solid ${TC_T.line}`, padding: "12px 14px", background: TC_T.surface }}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                  <span style={{ color: c.status === "off" ? TC_T.muteDim : TC_T.ink, fontSize: 12, fontFamily: TC_FS, fontWeight: 500 }}>{c.name}</span>
                  <StatusDot s={c.status} />
                </div>
                <div style={{ fontSize: 10, color: TC_T.muteDim }}>{c.account} · last backfill {c.lastBackfill}</div>
                <div style={{ fontSize: 10, color: TC_T.mute, marginTop: 4 }}>{c.note}</div>
              </div>
            ))}
          </div>
        </div>
        <div>
          <TC_S text="MEASUREMENT" />
          <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 10 }}>
            {D.measurement.map((m,i) => (
              <div key={i} style={{ border: `1px solid ${TC_T.line}`, padding: "12px 14px", background: TC_T.surface }}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                  <span style={{ color: TC_T.ink, fontSize: 12, fontFamily: TC_FS, fontWeight: 500 }}>{m.name}</span>
                  <StatusDot s={m.status} />
                </div>
                <div style={{ fontSize: 10, color: TC_T.muteDim }}>
                  {m.lastBuild ? `last build ${m.lastBuild}` : ""}
                  {m.running != null ? `${m.running} running · ${m.queued||0} queued` : ""}
                  {m.n ? `n=${m.n} · ${m.freq}` : ""}
                </div>
                {m.autoTrigger && <div style={{ fontSize: 10, color: TC_T.cyan, marginTop: 4 }}>auto · {m.autoTrigger}</div>}
              </div>
            ))}
          </div>
        </div>
        <div>
          <TC_S text="WEB · TAG / GA4 / CONSENT" />
          <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 10 }}>
            {D.web.map((w,i) => (
              <div key={i} style={{ border: `1px solid ${TC_T.line}`, padding: "12px 14px", background: TC_T.surface }}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                  <span style={{ color: TC_T.ink, fontSize: 12, fontFamily: TC_FS, fontWeight: 500 }}>{w.name}</span>
                  <StatusDot s={w.status} />
                </div>
                <div style={{ fontSize: 10, color: TC_T.muteDim, fontFamily: TC_FM }}>{w.containers || w.properties || w.coverage}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* WEBHOOKS */}
      <div>
        <TC_S text="WEBHOOKS · alertas + sincronización" right={<TC_B>+ NUEVO WEBHOOK</TC_B>} />
        <div style={{ marginTop: 12, border: `1px solid ${TC_T.line}` }}>
          <div style={{ display: "grid", gridTemplateColumns: "200px 1fr 100px 100px 24px", padding: "10px 14px", background: TC_T.surfaceHi, fontSize: 10, color: TC_T.muteDim, letterSpacing: "0.12em", borderBottom: `1px solid ${TC_T.line}` }}>
            <span>NOMBRE</span><span>ENDPOINT</span><span style={{ textAlign: "right" }}>EVENTS 24H</span><span style={{ textAlign: "right" }}>STATUS</span><span></span>
          </div>
          {D.webhooks.map((w,i) => (
            <div key={i} style={{ display: "grid", gridTemplateColumns: "200px 1fr 100px 100px 24px", padding: "10px 14px", borderBottom: i<D.webhooks.length-1?`1px solid ${TC_T.line}`:"none", background: TC_T.surface, fontSize: 11, alignItems: "center" }}>
              <span style={{ color: TC_T.ink, fontFamily: TC_FS, fontWeight: 500 }}>{w.name}</span>
              <span style={{ color: TC_T.muteDim, fontFamily: TC_FM, fontSize: 10 }}>{w.url}</span>
              <span style={{ color: TC_T.cyan, textAlign: "right", fontFamily: TC_FM }}>{w.events24h.toLocaleString()}</span>
              <span style={{ textAlign: "right" }}><StatusDot s={w.status} /><span style={{ color: w.status === "ok" ? TC_T.green : TC_T.amber, fontSize: 10 }}>{w.status.toUpperCase()}</span></span>
              <span style={{ color: TC_T.muteDim, textAlign: "right" }}>⋯</span>
            </div>
          ))}
        </div>
      </div>

      {/* COMPLIANCE FOOTER */}
      <div style={{ padding: "14px 18px", border: `1px solid ${TC_T.cyan}`, borderLeftWidth: 3, background: TC_T.surface }}>
        <div style={{ fontSize: 10, color: TC_T.cyan, letterSpacing: "0.16em", marginBottom: 8 }}>OAUTH · least privilege · audit-ready</div>
        <div style={{ fontSize: 11, color: TC_T.ink, lineHeight: 1.6 }}>
          MediaAgent solicita el scope mínimo necesario · ningún token sale del browser sin pasar por nuestro proxy · todos los tokens rotan cada 90 días · acceso revocable desde aquí en 1 click.
          <br/>Cumplimos SOC 2 Type II · ISO 27001 · auditados por <b>Crowe LATAM</b> last audit Mar 2026.
        </div>
      </div>
    </div>
  );
};

window.ConnectScreen = ConnectScreen;
