/* global React, Icon, Button, Badge, Card, StatusDot, Backend */
// ============================================================
// Compte Instagram — tableau comptes D1 + GeeLark
// ============================================================
const { useState, useEffect, useCallback } = React;

const IG_BASE = (function() {
  const h = location.hostname;
  if (h === "localhost" || h === "127.0.0.1") return "";
  return "";
})();

function AdminInstagram() {
  const [accounts, setAccounts] = useState([]);
  const [stats, setStats] = useState({ total: 0, twofa_ok: 0, twofa_fail: 0, geelark: 0 });
  const [loading, setLoading] = useState(true);
  const [copied, setCopied] = useState(null);
  const [initDone, setInitDone] = useState(false);

  const initTable = useCallback(async () => {
    if (initDone) return;
    try { await fetch(IG_BASE + "/api/instagram/init", { method: "POST" }); setInitDone(true); } catch {}
  }, [initDone]);

  const fetchData = useCallback(async () => {
    try {
      const [accRes, statsRes] = await Promise.all([
        fetch(IG_BASE + "/api/instagram/accounts").then(r => r.json()).catch(() => ({ accounts: [] })),
        fetch(IG_BASE + "/api/instagram/stats").then(r => r.json()).catch(() => ({ total: 0, twofa_ok: 0, twofa_fail: 0, geelark: 0 }))
      ]);
      setAccounts(accRes.accounts || []);
      setStats(statsRes);
      setLoading(false);
    } catch { setLoading(false); }
  }, []);

  useEffect(() => {
    initTable().then(fetchData);
    const id = setInterval(fetchData, 5000);
    return () => clearInterval(id);
  }, [initTable, fetchData]);

  const copy = (text, id) => {
    navigator.clipboard.writeText(text);
    setCopied(id);
    setTimeout(() => setCopied(null), 1500);
  };

  return React.createElement("div", { style: { padding: "28px 32px", maxWidth: 1600 } },
    // Title
    React.createElement("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 24 } },
      React.createElement("h2", { className: "mono", style: { fontSize: 18, fontWeight: 700, color: "var(--text)" } }, "COMPTE INSTAGRAM"),
      React.createElement("button", {
        onClick: fetchData,
        style: { padding: "8px 14px", borderRadius: 8, border: "1px solid var(--border)", background: "var(--surface)", color: "var(--muted)", cursor: "pointer", fontSize: 13 }
      }, "Rafraichir")
    ),

    // Stats cards
    React.createElement("div", { style: { display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))", gap: 12, marginBottom: 24 } },
      statCard("Comptes", stats.total, "var(--accent)"),
      statCard("2FA OK", stats.twofa_ok, "#4caf50"),
      statCard("2FA Fail", stats.twofa_fail, "#f44336"),
      statCard("GeeLark", stats.geelark, "#e040fb")
    ),

    // Légende progression
    React.createElement("div", { style: { display: "flex", flexWrap: "wrap", gap: 12, marginBottom: 20, padding: "12px 16px", borderRadius: 10, border: "1px solid var(--border)", background: "var(--surface)" } },
      React.createElement("span", { className: "mono", style: { fontSize: 11, color: "var(--muted)", fontWeight: 700, marginRight: 4 } }, "Progression :"),
      legendItem("#f44336", "0%", "Pas de 2FA"),
      legendItem("#ff9800", "20%", "IG + 2FA"),
      legendItem("#ff9800", "40%", "GeeLark OK"),
      legendItem("#ffeb3b", "60%", "Jour 1 (1-2 reels)"),
      legendItem("#8bc34a", "80%", "Jour 2 (3-4 reels)"),
      legendItem("#4caf50", "100%", "Jour 3 (5+ reels)"),
      legendItem("#00e5ff", "💎", "50K+ vues")
    ),

    // Table
    loading
      ? React.createElement("div", { style: { textAlign: "center", padding: 48, color: "var(--faint)" } }, "Chargement...")
      : React.createElement("div", { style: { borderRadius: 12, border: "1px solid var(--border)", overflow: "hidden", background: "var(--surface)" } },
          React.createElement("div", { style: { overflowX: "auto" } },
            React.createElement("table", { style: { width: "100%", borderCollapse: "collapse" } },
              React.createElement("thead", null,
                React.createElement("tr", null,
                  th("Progression"), th("Date"), th("Nom"), th("Username"), th("Password"), th("Telephone"), th("Naissance"),
                  th("Code 2FA"), th("Vues"), th("Partages"), th("Commentaires"), th("Reposts"), th("GeeLark"), th("N°"), th("GeeLark ID"), th("Actions")
                )
              ),
              React.createElement("tbody", null,
                accounts.length === 0
                  ? React.createElement("tr", null, React.createElement("td", { colSpan: 13, style: { textAlign: "center", padding: 32, color: "var(--faint)", fontSize: 13 } }, "Aucun compte"))
                  : accounts.map((a, i) => {
                      const hasGL = !!a.geelark_id;
                      const glStatusColor = hasGL ? "#4caf50" : "var(--faint)";
                      const glStatusText = hasGL ? "Actif" : "-";
                      const has2FA = a.code_2fa && a.code_2fa !== "N/A" && a.code_2fa !== "FAILED";
                      const reels = a.reels_count || 0;
                      let progress = 0, progressLabel = "", progressColor = "";
                      if (!has2FA) { progress = 0; progressLabel = "Pas de 2FA"; progressColor = "#f44336"; }
                      else if (!hasGL) { progress = 20; progressLabel = "IG + 2FA"; progressColor = "#ff9800"; }
                      else if (reels < 1) { progress = 40; progressLabel = "GeeLark OK"; progressColor = "#ff9800"; }
                      else if (reels < 3) { progress = 60; progressLabel = "Jour 1 (" + reels + " reel" + (reels > 1 ? "s" : "") + ")"; progressColor = "#ffeb3b"; }
                      else if (reels < 5) { progress = 80; progressLabel = "Jour 2 (" + reels + " reels)"; progressColor = "#8bc34a"; }
                      else if (reels >= 5 && (a.total_views || 0) >= 50000) { progress = 100; progressLabel = "💎 " + (a.total_views/1000).toFixed(0) + "K vues"; progressColor = "#00e5ff"; }
                      else { progress = 100; progressLabel = "Jour 3 (" + reels + " reels)"; progressColor = "#4caf50"; }
                      return React.createElement("tr", { key: a.id || i, style: { borderTop: "1px solid var(--border)" } },
                        React.createElement("td", { style: { ...tdStyle, minWidth: 150 } },
                          React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 8 } },
                            React.createElement("div", { style: { flex: 1, height: 6, borderRadius: 3, background: "var(--surface-3)", overflow: "hidden" } },
                              React.createElement("div", { style: { width: progress + "%", height: "100%", borderRadius: 3, background: progressColor, transition: "width .3s" } })
                            ),
                            React.createElement("span", { className: "mono", style: { fontSize: 10, color: progressColor, whiteSpace: "nowrap", fontWeight: 700 } }, progress + "%")
                          ),
                          React.createElement("div", { className: "mono", style: { fontSize: 9, color: "var(--faint)", marginTop: 2 } }, progressLabel.split(" — ")[1] || "")
                        ),
                        td(a.date || ""),
                        td(a.nom || ""),
                        React.createElement("td", { style: tdStyle }, React.createElement("strong", null, a.username || "")),
                        React.createElement("td", { style: tdStyle },
                          React.createElement("span", { className: "mono", style: { fontSize: 11 } }, a.password || ""),
                          " ", copyBtn(a.password, "pw-" + i, copied, copy)
                        ),
                        td(a.phone || ""),
                        td(a.date_naissance || ""),
                        React.createElement("td", { style: { ...tdStyle, maxWidth: 160 } },
                          React.createElement("span", { className: "mono", style: { fontSize: 10, display: "inline-block", maxWidth: 120, overflow: "hidden", textOverflow: "ellipsis", verticalAlign: "middle" } }, a.code_2fa || "-"),
                          " ", a.code_2fa && a.code_2fa !== "N/A" && a.code_2fa !== "FAILED" ? copyBtn(a.code_2fa, "2fa-" + i, copied, copy) : null
                        ),
                        statTd(a.total_views),
                        statTd(a.total_shares),
                        statTd(a.total_comments),
                        statTd(a.total_reposts),
                        React.createElement("td", { style: tdStyle },
                          React.createElement("span", { style: { display: "inline-block", width: 7, height: 7, borderRadius: "50%", background: glStatusColor, marginRight: 6, verticalAlign: "middle" } }),
                          React.createElement("span", { style: { fontSize: 11 } }, glStatusText)
                        ),
                        td(a.geelark_serial ? "#" + a.geelark_serial : "-"),
                        React.createElement("td", { style: tdStyle },
                          hasGL ? React.createElement(React.Fragment, null,
                            React.createElement("span", { className: "mono", style: { fontSize: 10, display: "inline-block", maxWidth: 100, overflow: "hidden", textOverflow: "ellipsis", verticalAlign: "middle" } }, a.geelark_id),
                            " ", copyBtn(a.geelark_id, "gl-" + i, copied, copy)
                          ) : "-"
                        ),
                        React.createElement("td", { style: tdStyle },
                          copyBtn((a.username || "") + ":" + (a.password || ""), "up-" + i, copied, copy, "user:pass")
                        )
                      );
                    })
              )
            )
          )
        )
  );
}

const tdStyle = { padding: "9px 10px", fontSize: 12, whiteSpace: "nowrap", color: "var(--text)" };
function th(label) {
  return React.createElement("th", {
    className: "mono",
    style: { padding: "9px 10px", textAlign: "left", fontSize: 10, color: "var(--faint)", letterSpacing: ".08em", background: "var(--surface-2)", whiteSpace: "nowrap", fontWeight: 600 }
  }, label);
}
function td(val) { return React.createElement("td", { style: tdStyle }, val); }
function copyBtn(text, id, copied, copy, label) {
  return React.createElement("button", {
    onClick: () => copy(text, id),
    style: { background: "none", border: "1px solid " + (copied === id ? "#4caf50" : "var(--border)"), color: copied === id ? "#4caf50" : "var(--muted)", padding: "1px 7px", borderRadius: 4, fontSize: 10, cursor: "pointer", verticalAlign: "middle" }
  }, copied === id ? "OK" : (label || "Copier"));
}
function statCard(label, value, color) {
  return React.createElement("div", { style: { padding: "14px 16px", borderRadius: 10, border: "1px solid var(--border)", background: "var(--surface)" } },
    React.createElement("div", { className: "mono", style: { fontSize: 26, fontWeight: 700, color } }, value),
    React.createElement("div", { className: "mono", style: { fontSize: 10, color: "var(--faint)", letterSpacing: ".08em", marginTop: 2 } }, label)
  );
}
function legendItem(color, pct, label) {
  return React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 5 } },
    React.createElement("span", { style: { display: "inline-block", width: 8, height: 8, borderRadius: "50%", background: color } }),
    React.createElement("span", { className: "mono", style: { fontSize: 10, color, fontWeight: 700 } }, pct),
    React.createElement("span", { style: { fontSize: 11, color: "var(--muted)" } }, label)
  );
}
function statTd(val) {
  const n = val || 0;
  return React.createElement("td", { className: "mono", style: { ...tdStyle, textAlign: "center", fontSize: 12, color: n > 0 ? "var(--text)" : "var(--faint)" } }, n > 0 ? n.toLocaleString() : "-");
}
