/* Relay — Integrations screen */
function IntegrationsScreen() {
  const { PLATFORMS, INTEGRATIONS } = window.RelayData;
  const [conns, setConns] = React.useState(() => INTEGRATIONS.map((c) => ({ ...c })));
  const [connecting, setConnecting] = React.useState(null); // platform id mid-connect
  const [modal, setModal] = React.useState(null); // platform being connected

  const connectedCount = conns.filter((c) => c.connected).length;

  function startConnect(id) { setModal(id); }
  function confirmConnect(id, account) {
    setModal(null);
    setConnecting(id);
    setTimeout(() => {
      setConns((prev) => prev.map((c) => c.id === id ? { ...c, connected: true, account: account || (PLATFORMS[id].short.toLowerCase() + "-store-01"), synced: 0 } : c));
      setConnecting(null);
      window.__relayToast && window.__relayToast(`${PLATFORMS[id].name} bağlandı — siparişler eşitleniyor.`);
    }, 1400);
  }
  function disconnect(id) {
    setConns((prev) => prev.map((c) => c.id === id ? { ...c, connected: false, account: null, synced: null } : c));
  }

  return (
    <Scroller>
      <PageHeader title="Entegrasyonlar" icon={<I.integrations size={18} />} subtitle={`${conns.length} kanaldan ${connectedCount} tanesi bağlı ve gerçek zamanlı olarak eşitleniyor.`} />

      {/* status banner */}
      <div style={{ display: "flex", alignItems: "center", gap: 12, background: "var(--ready-bg)", border: "1px solid #c4e7cf", borderRadius: "var(--radius)", padding: "12px 16px", marginBottom: 20 }}>
        <span style={{ width: 9, height: 9, borderRadius: 999, background: "var(--ready)", animation: "liveDot 1.6s infinite", flexShrink: 0 }} />
        <span style={{ fontSize: 13, fontWeight: 600, color: "#15803d" }}>Bağlı tüm kanallar eşitleniyor.</span>
        <span style={{ fontSize: 12.5, color: "#3f9b5e" }}>Yeni siparişler otomatik olarak canlı panoda görünür.</span>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(320px, 1fr))", gap: 14 }}>
        {conns.map((c) => {
          const p = PLATFORMS[c.id];
          const isConnecting = connecting === c.id;
          return (
            <div key={c.id} style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--radius)", padding: 18, boxShadow: "var(--shadow-sm)", display: "flex", flexDirection: "column", gap: 14 }}>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
                <span style={{ width: 44, height: 44, borderRadius: 11, background: p.color, color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--mono)", fontWeight: 600, fontSize: 17, flexShrink: 0 }}>{p.short}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 600, fontSize: 15 }}>{p.name}</div>
                  <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 3 }}>
                    <span style={{ fontSize: 11, fontWeight: 600, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".04em" }}>{p.type === "food" ? "Yemek teslimatı" : "E-ticaret"}</span>
                    <span style={{ color: "var(--border-strong)" }}>·</span>
                    <span style={{ fontSize: 11, color: "var(--text-3)" }}>{c.auth === "oauth" ? "OAuth" : "API anahtarı"}</span>
                  </div>
                </div>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11.5, fontWeight: 600, color: c.connected ? "var(--ready)" : "var(--text-3)", background: c.connected ? "var(--ready-bg)" : "var(--surface-3)", padding: "4px 9px", borderRadius: 999 }}>
                  <span style={{ width: 6, height: 6, borderRadius: 999, background: c.connected ? "var(--ready)" : "var(--text-3)" }} />
                  {c.connected ? "Bağlı" : "Bağlı değil"}
                </span>
              </div>

              {c.connected ? (
                <div style={{ display: "flex", flexDirection: "column", gap: 7, fontSize: 12.5, background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: 8, padding: "10px 12px" }}>
                  <Row k="Hesap" v={<span className="mono">{c.account}</span>} />
                  <Row k="Son eşitleme" v={c.synced === 0 ? "şimdi" : `${c.synced} dk önce`} />
                  <Row k="Otomatik eşitleme" v={<span style={{ color: "var(--ready)", fontWeight: 600 }}>Gerçek zamanlı</span>} />
                </div>
              ) : (
                <div style={{ fontSize: 12.5, color: "var(--text-3)", lineHeight: 1.5, padding: "4px 0" }}>
                  Birleştirilmiş panonuzda {p.name} siparişlerini görmek için bağlanın. {c.auth === "oauth" ? "güvenli giriş" : "bir API anahtarı"} ile birkaç tıklamada tamamlanır.
                </div>
              )}

              <div style={{ display: "flex", gap: 8, marginTop: "auto" }}>
                {c.connected ? (
                  <>
                    <Btn kind="default" small full title="Ayarlar"><I.settings size={14} />Yönet</Btn>
                    <Btn kind="reject" small onClick={() => disconnect(c.id)}>Bağlantıyı Kes</Btn>
                  </>
                ) : (
                  <Btn kind="primary" small full onClick={() => startConnect(c.id)}>
                    {isConnecting ? <><span style={{ width: 13, height: 13, border: "2px solid rgba(255,255,255,.4)", borderTopColor: "#fff", borderRadius: 999, animation: "spin .7s linear infinite", display: "inline-block" }} />Bağlanıyor…</> : <><I.plus size={14} />Bağlan</>}
                  </Btn>
                )}
              </div>
            </div>
          );
        })}
      </div>

      {/* connect modal */}
      {modal && <ConnectModal pid={modal} onCancel={() => setModal(null)} onConfirm={confirmConnect} />}
    </Scroller>
  );
}

function Row({ k, v }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10 }}>
      <span style={{ color: "var(--text-3)", whiteSpace: "nowrap", flexShrink: 0 }}>{k}</span>
      <span style={{ color: "var(--text)", fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", textAlign: "right" }}>{v}</span>
    </div>
  );
}

function ConnectModal({ pid, onCancel, onConfirm }) {
  const { PLATFORMS, INTEGRATIONS } = window.RelayData;
  const p = PLATFORMS[pid];
  const auth = (INTEGRATIONS.find((i) => i.id === pid) || {}).auth || "oauth";
  const [key, setKey] = React.useState("");
  return (
    <>
      <div onClick={onCancel} style={{ position: "fixed", inset: 0, background: "rgba(20,24,29,.4)", zIndex: 90 }} />
      <div style={{ position: "fixed", top: "50%", left: "50%", transform: "translate(-50%,-50%)", width: 400, background: "var(--surface)", borderRadius: "var(--radius)", boxShadow: "var(--shadow-lg)", zIndex: 91, padding: 24, animation: "dropIn .2s" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16 }}>
          <span style={{ width: 44, height: 44, borderRadius: 11, background: p.color, color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--mono)", fontWeight: 600, fontSize: 17 }}>{p.short}</span>
          <div>
            <div style={{ fontWeight: 700, fontSize: 16 }}>{p.name} Bağla</div>
            <div style={{ fontSize: 12.5, color: "var(--text-3)" }}>{auth === "oauth" ? "Güvenli giriş ile yetkilendirin" : "API kimlik bilgilerinizi girin"}</div>
          </div>
        </div>
        {auth === "oauth" ? (
          <div style={{ fontSize: 13, color: "var(--text-2)", lineHeight: 1.6, background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: 8, padding: "12px 14px", marginBottom: 18 }}>
            Relay'e siparişleriniz için okuma erişimi vermek üzere {p.name} sayfasına yönlendirileceksiniz. Hiçbir şifre kaydedilmez.
          </div>
        ) : (
          <div style={{ marginBottom: 18 }}>
            <label style={{ fontSize: 11.5, fontWeight: 600, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".04em" }}>API anahtarı</label>
            <input value={key} onChange={(e) => setKey(e.target.value)} placeholder={`${pid}_live_xxxxxxxxxxxx`} className="mono" style={{ width: "100%", marginTop: 6, padding: "10px 12px", borderRadius: "var(--radius-sm)", border: "1px solid var(--border-strong)", fontSize: 13, outline: "none" }} />
          </div>
        )}
        <div style={{ display: "flex", gap: 10 }}>
          <Btn kind="default" full onClick={onCancel}>İptal</Btn>
          <Btn kind="primary" full onClick={() => onConfirm(pid, auth === "apikey" && key ? p.short.toLowerCase() + "_live_•••" : null)}>
            {auth === "oauth" ? "Yetkilendir" : "Bağlan"}<I.arrowRight size={15} />
          </Btn>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { IntegrationsScreen });
