/* global React, window, I, S, M */
// PushToProduction - floating button (bottom-right of admin portal).
// Visible only when PAMP_CONFIG.IS_BETA && CAN_PUSH_TO_PROD.
// On click, opens a modal showing what commits will be deployed.
// On confirm, calls /api/push-to-production which merges beta into main.
// Vercel auto-deploys main to app.trypamp.com.

function PushToProduction() {
  const cfg = window.PAMP_CONFIG;
  const toast = window.useToast();
  const [open, setOpen] = React.useState(false);
  const [diff, setDiff] = React.useState(null);
  const [loadingDiff, setLoadingDiff] = React.useState(false);
  const [busy, setBusy] = React.useState(false);

  if (!cfg?.IS_BETA || !cfg?.CAN_PUSH_TO_PROD) return null;

  const openModal = async () => {
    setOpen(true);
    setDiff(null);
    setLoadingDiff(true);
    try {
      const res = await fetch("/api/compare-branches");
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Compare failed");
      setDiff(data);
    } catch (err) {
      toast.error(err.message || "Couldn't fetch branch comparison");
      setOpen(false);
    } finally {
      setLoadingDiff(false);
    }
  };

  const confirmPush = async () => {
    setBusy(true);
    try {
      const res = await fetch("/api/push-to-production", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          commit_message: `Deploy beta to production (${new Date().toISOString().slice(0, 10)})`,
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Merge failed");
      if (data.nothing_to_merge) {
        toast.success("Beta is already in sync with main — nothing to deploy.");
      } else {
        toast.success("Deployed. Production is building on Vercel now.");
      }
      setOpen(false);
    } catch (err) {
      toast.error(err.message || "Deploy failed");
    } finally {
      setBusy(false);
    }
  };

  return (
    <>
      <button
        onClick={openModal}
        title="Merge beta into main and deploy to production"
        style={{
          position: "fixed",
          bottom: 20,
          right: 20,
          zIndex: 120,
          display: "inline-flex",
          alignItems: "center",
          gap: 8,
          padding: "11px 18px",
          borderRadius: 999,
          background: "var(--accent)",
          color: "var(--accent-ink)",
          border: "1px solid color-mix(in oklch, var(--accent) 80%, var(--ink))",
          fontWeight: 500,
          fontSize: 13,
          cursor: "pointer",
          boxShadow: "0 8px 24px oklch(0% 0 0 / 0.18), 0 2px 4px oklch(0% 0 0 / 0.12)",
        }}
      >
        <I.upload size={14} />
        Push to Production
      </button>

      <window.M.Modal
        open={open}
        onClose={() => !busy && setOpen(false)}
        size="lg"
        icon={<I.upload />}
        title="Push beta to production?"
        subtitle="This merges the beta branch into main. Vercel auto-deploys production from main."
        footer={
          <>
            <S.Btn variant="ghost" onClick={() => setOpen(false)} disabled={busy}>
              Cancel
            </S.Btn>
            <S.Btn
              variant="primary"
              icon={<I.upload size={14} />}
              onClick={confirmPush}
              disabled={busy || loadingDiff || (diff && diff.ahead_by === 0)}
            >
              {busy ? "Deploying…" : "Confirm & deploy"}
            </S.Btn>
          </>
        }
      >
        {loadingDiff ? (
          <div className="loading-state">
            <div className="spin" />
            <div>Comparing beta against main…</div>
          </div>
        ) : !diff ? null : diff.ahead_by === 0 ? (
          <div style={{ padding: "20px 0", textAlign: "center" }}>
            <div style={{ marginBottom: 8, fontSize: 14 }}>
              Beta is already in sync with main.
            </div>
            <div className="muted tiny">Nothing new to deploy.</div>
          </div>
        ) : (
          <>
            <div className="row between" style={{ marginBottom: 14 }}>
              <div>
                <div className="eyebrow">Pending deploy</div>
                <div className="h3" style={{ marginTop: 2 }}>
                  {diff.ahead_by} commit{diff.ahead_by === 1 ? "" : "s"} ahead of main
                </div>
              </div>
              {diff.behind_by > 0 && (
                <S.Chip tone="warn">main is {diff.behind_by} commits ahead</S.Chip>
              )}
            </div>

            <div className="card card-flush" style={{ marginBottom: 6 }}>
              <table className="tbl">
                <thead>
                  <tr>
                    <th style={{ width: 78 }}>SHA</th>
                    <th>Commit</th>
                    <th style={{ width: 130 }}>Author</th>
                  </tr>
                </thead>
                <tbody>
                  {diff.commits.map((c) => (
                    <tr key={c.sha}>
                      <td className="mono tiny muted">{c.sha}</td>
                      <td style={{ whiteSpace: "normal" }}>{c.message}</td>
                      <td className="tiny muted">{c.author}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {diff.behind_by > 0 && (
              <div
                className="tiny"
                style={{
                  marginTop: 14,
                  padding: 12,
                  borderRadius: 8,
                  background: "color-mix(in oklch, var(--warn) 10%, transparent)",
                  color: "var(--warn)",
                  border: "1px solid color-mix(in oklch, var(--warn) 30%, transparent)",
                }}
              >
                Heads-up: main has {diff.behind_by} commit
                {diff.behind_by === 1 ? "" : "s"} that beta doesn't have. The
                merge will preserve those. If they conflict with beta, GitHub
                will reject the merge and you'll need to resolve manually.
              </div>
            )}
          </>
        )}
      </window.M.Modal>
    </>
  );
}

window.PushToProduction = PushToProduction;
