import { showToast } from "../components/toast.js";

let csrfToken = "";
let telegramAuthConfig = { enabled: false, botUsername: "", widgetDomain: "" };

export function getTelegramAuthConfig() {
  return telegramAuthConfig;
}

export function apiUrl(file) {
  const name = String(file || "").replace(/^\/+/, "");
  const manual =
    typeof globalThis.__SITE_BASE__ === "string" ? globalThis.__SITE_BASE__.trim().replace(/\/+$/, "") : "";
  const path =
    manual !== ""
      ? `${manual}/api/${name}`.replace(/\/{2,}/g, "/")
      : `/api/${name}`;
  return new URL(path, window.location.origin).href;
}

const JSON_HEADERS = { "Content-Type": "application/json" };

function jsonHeadersWithCsrf() {
  const h = { ...JSON_HEADERS };
  if (csrfToken) h["X-CSRF-Token"] = csrfToken;
  return h;
}

async function ensureCsrf() {
  if (csrfToken) return;
  await fetchSessionUser();
  if (csrfToken) return;
  try {
    const r = await fetch(apiUrl("user_me.php"), { credentials: "include", cache: "no-store" });
    const data = await r.json().catch(() => ({}));
    if (typeof data.csrfToken === "string" && data.csrfToken.length > 0) {
      csrfToken = data.csrfToken;
    }
  } catch {

  }
}

export async function fetchSessionUser() {
  try {
    const r = await fetch(apiUrl("user_me.php"), { credentials: "include", cache: "no-store" });
    const data = await r.json().catch(() => ({}));
    if (typeof data.csrfToken === "string" && data.csrfToken.length > 0) {
      csrfToken = data.csrfToken;
    }
    if (data.telegramAuth && typeof data.telegramAuth === "object") {
      telegramAuthConfig = {
        enabled: !!data.telegramAuth.enabled,
        botUsername: String(data.telegramAuth.botUsername || "").replace(/^@/, ""),
        widgetDomain: String(data.telegramAuth.widgetDomain || "").trim(),
      };
    }
    if (!r.ok || !data.ok) {
      return null;
    }
    if (!data.authenticated || !data.user) {
      return null;
    }
    return {
      ...data.user,
      needsProfileCompletion: !!data.needsProfileCompletion || !!data.user.needsProfileCompletion,
      needsPasswordChange: !!data.needsPasswordChange || !!data.user.needsPasswordChange,
    };
  } catch {
    return null;
  }
}

export async function postRegister(body) {
  await ensureCsrf();
  const r = await fetch(apiUrl("user_register.php"), {
    method: "POST",
    credentials: "include",
    headers: jsonHeadersWithCsrf(),
    body: JSON.stringify(body),
  });
  const data = await r.json().catch(() => ({}));
  return { ok: r.ok && data.ok === true, status: r.status, data };
}

export async function postLogin(body) {
  await ensureCsrf();
  const r = await fetch(apiUrl("user_login.php"), {
    method: "POST",
    credentials: "include",
    headers: jsonHeadersWithCsrf(),
    body: JSON.stringify(body),
  });
  const data = await r.json().catch(() => ({}));
  const loginOk = data.ok === true && (data.requires2fa === true || r.ok);
  return { ok: loginOk, status: r.status, data };
}

export async function fetchUser2fa() {
  try {
    const r = await fetch(apiUrl("user_2fa.php"), { credentials: "include", cache: "no-store" });
    const data = await r.json().catch(() => ({}));
    return { ok: r.ok && data.ok === true, status: r.status, data };
  } catch {
    return { ok: false, status: 0, data: {} };
  }
}

export async function postUser2fa(body) {
  await ensureCsrf();
  try {
    const r = await fetch(apiUrl("user_2fa.php"), {
      method: "POST",
      credentials: "include",
      headers: jsonHeadersWithCsrf(),
      body: JSON.stringify(body),
    });
    const data = await r.json().catch(() => ({}));
    if (typeof data.csrfToken === "string" && data.csrfToken.length > 0) {
      csrfToken = data.csrfToken;
    }
    return { ok: r.ok && data.ok === true, status: r.status, data };
  } catch {
    return { ok: false, status: 0, data: {} };
  }
}

export async function postTelegramAuth(payload) {
  await ensureCsrf();
  const r = await fetch(apiUrl("user_telegram_auth.php"), {
    method: "POST",
    credentials: "include",
    headers: jsonHeadersWithCsrf(),
    body: JSON.stringify(payload),
    cache: "no-store",
  });
  const data = await r.json().catch(() => ({}));
  if (typeof data.csrfToken === "string" && data.csrfToken.length > 0) {
    csrfToken = data.csrfToken;
  }
  return { ok: r.ok && data.ok === true, status: r.status, data };
}

export async function postTelegramAuthStart(mode) {
  await ensureCsrf();
  const r = await fetch(apiUrl("telegram_auth_start.php"), {
    method: "POST",
    credentials: "include",
    headers: jsonHeadersWithCsrf(),
    body: JSON.stringify({ mode }),
    cache: "no-store",
  });
  const data = await r.json().catch(() => ({}));
  return { ok: r.ok && data.ok === true, status: r.status, data };
}

export async function pollTelegramAuth(token) {
  const q = new URLSearchParams({ token });
  const r = await fetch(`${apiUrl("telegram_auth_poll.php")}?${q}`, {
    credentials: "include",
    cache: "no-store",
  });
  const data = await r.json().catch(() => ({}));
  if (typeof data.csrfToken === "string" && data.csrfToken.length > 0) {
    csrfToken = data.csrfToken;
  }
  return { ok: r.ok && data.ok === true, status: r.status, data };
}

export async function postProfileComplete(body) {
  await ensureCsrf();
  const r = await fetch(apiUrl("user_profile_complete.php"), {
    method: "POST",
    credentials: "include",
    headers: jsonHeadersWithCsrf(),
    body: JSON.stringify(body),
  });
  const data = await r.json().catch(() => ({}));
  return { ok: r.ok && data.ok === true, status: r.status, data };
}

export async function postPasswordChange(body) {
  await ensureCsrf();
  const r = await fetch(apiUrl("user_password_change.php"), {
    method: "POST",
    credentials: "include",
    headers: jsonHeadersWithCsrf(),
    body: JSON.stringify(body),
  });
  const data = await r.json().catch(() => ({}));
  return { ok: r.ok && data.ok === true, status: r.status, data };
}

export async function postLogout() {
  try {
    await ensureCsrf();
    await fetch(apiUrl("user_logout.php"), {
      method: "POST",
      credentials: "include",
      headers: jsonHeadersWithCsrf(),
    });
  } catch {

  }
}

export async function postMarketPurchase(itemId) {
  await ensureCsrf();
  const r = await fetch(apiUrl("market_purchase.php"), {
    method: "POST",
    credentials: "include",
    headers: jsonHeadersWithCsrf(),
    body: JSON.stringify({ itemId }),
  });
  const data = await r.json().catch(() => ({}));
  return { ok: r.ok && data.ok === true, status: r.status, data };
}

export async function postUserComplaint(body) {
  try {
    await ensureCsrf();
    const r = await fetch(apiUrl("user_complaint.php"), {
      method: "POST",
      credentials: "include",
      headers: jsonHeadersWithCsrf(),
      body: JSON.stringify(body),
    });
    const data = await r.json().catch(() => ({}));
    const ok = data && data.ok === true;
    return { ok, status: r.status, data };
  } catch {
    return { ok: false, status: 0, data: {} };
  }
}

export async function postTicketRequest(body) {
  try {
    await ensureCsrf();
    const r = await fetch(apiUrl("ticket_request.php"), {
      method: "POST",
      credentials: "include",
      headers: jsonHeadersWithCsrf(),
      body: JSON.stringify(body),
    });
    const data = await r.json().catch(() => ({}));
    return { ok: r.ok && data.ok === true, status: r.status, data };
  } catch {
    return { ok: false, status: 0, data: {} };
  }
}

export async function postEventRequest(body) {
  try {
    await ensureCsrf();
    const r = await fetch(apiUrl("event_request.php"), {
      method: "POST",
      credentials: "include",
      headers: jsonHeadersWithCsrf(),
      body: JSON.stringify(body),
    });
    const data = await r.json().catch(() => ({}));
    return { ok: r.ok && data.ok === true, status: r.status, data };
  } catch {
    return { ok: false, status: 0, data: {} };
  }
}

export async function postUserAffiliateRequest(body) {
  try {
    await ensureCsrf();
    const r = await fetch(apiUrl("user_affiliate_request.php"), {
      method: "POST",
      credentials: "include",
      headers: jsonHeadersWithCsrf(),
      body: JSON.stringify(body),
    });
    const raw = await r.text();
    let data = {};
    try {
      data = raw ? JSON.parse(raw) : {};
    } catch {
      data = { error: "bad_json" };
    }
    const ok = data && data.ok === true;
    return { ok, status: r.status, data };
  } catch {
    return { ok: false, status: 0, data: {} };
  }
}

export async function fetchWheelStatus() {
  const r = await fetch(apiUrl("wheel.php"), { credentials: "include" });
  const data = await r.json().catch(() => ({}));
  return { ok: r.ok && data.ok === true, status: r.status, data };
}

export async function postWheelSpin() {
  await ensureCsrf();
  const r = await fetch(apiUrl("wheel.php"), {
    method: "POST",
    credentials: "include",
    headers: csrfToken ? { "X-CSRF-Token": csrfToken } : {},
  });
  const data = await r.json().catch(() => ({}));
  return { ok: r.ok && data.ok === true, status: r.status, data };
}

export async function fetchDailyBonusStatus() {
  try {
    const r = await fetch(apiUrl("user_daily_bonus.php"), { credentials: "include", cache: "no-store" });
    const data = await r.json().catch(() => ({}));
    return { ok: r.ok && data.ok === true, status: r.status, data };
  } catch {
    return { ok: false, status: 0, data: {} };
  }
}

export async function postDailyBonusClaim() {
  await ensureCsrf();
  const r = await fetch(apiUrl("user_daily_bonus.php"), {
    method: "POST",
    credentials: "include",
    headers: jsonHeadersWithCsrf(),
    body: JSON.stringify({}),
  });
  const data = await r.json().catch(() => ({}));
  return { ok: r.ok && data.ok === true, status: r.status, data };
}

export async function fetchChatMessages(afterId) {
  try {
    const q = afterId === undefined ? "" : `?after=${Math.floor(Number(afterId))}`;
    const r = await fetch(apiUrl(`chat_messages.php${q}`), {
      credentials: "include",
      cache: "no-store",
    });
    const data = await r.json().catch(() => ({}));
    if (typeof data.csrfToken === "string" && data.csrfToken.length > 0) {
      csrfToken = data.csrfToken;
    }
    return { ok: r.ok && data.ok === true, status: r.status, data };
  } catch {
    return { ok: false, status: 0, data: {} };
  }
}

export async function postChatMessage(body) {
  await ensureCsrf();
  try {
    const r = await fetch(apiUrl("chat_messages.php"), {
      method: "POST",
      credentials: "include",
      headers: jsonHeadersWithCsrf(),
      body: JSON.stringify({ body: String(body || "").trim() }),
    });
    const raw = await r.text();
    let data = {};
    try {
      data = raw ? JSON.parse(raw) : {};
    } catch {
      data = {};
    }
    if (typeof data.csrfToken === "string" && data.csrfToken.length > 0) {
      csrfToken = data.csrfToken;
    }
    return { ok: r.ok && data.ok === true, status: r.status, data };
  } catch {
    return { ok: false, status: 0, data: {} };
  }
}

export async function fetchBlackjackState() {
  const r = await fetch(apiUrl("game_blackjack.php"), { credentials: "include" });
  const data = await r.json().catch(() => ({}));
  const ok = r.ok && data.ok === true && data.authenticated !== false;
  return { ok, status: r.status, data };
}

export async function postBlackjackAction(body) {
  await ensureCsrf();
  const r = await fetch(apiUrl("game_blackjack.php"), {
    method: "POST",
    credentials: "include",
    headers: jsonHeadersWithCsrf(),
    body: JSON.stringify(body),
  });
  const data = await r.json().catch(() => ({}));
  return { ok: data.ok === true, status: r.status, data };
}

export async function fetchSlotState() {
  const r = await fetch(apiUrl("game_slot.php"), { credentials: "include" });
  const data = await r.json().catch(() => ({}));
  const ok = r.ok && data.ok === true && data.authenticated !== false;
  return { ok, status: r.status, data };
}

export async function postSlotSpin(body) {
  await ensureCsrf();
  const r = await fetch(apiUrl("game_slot.php"), {
    method: "POST",
    credentials: "include",
    headers: jsonHeadersWithCsrf(),
    body: JSON.stringify(body),
  });
  const data = await r.json().catch(() => ({}));
  return { ok: data.ok === true, status: r.status, data };
}

export async function fetchRouletteState() {
  const r = await fetch(apiUrl("game_roulette.php"), { credentials: "include" });
  const data = await r.json().catch(() => ({}));
  const ok = r.ok && data.ok === true && data.authenticated !== false;
  return { ok, status: r.status, data };
}

export async function postRouletteSpin(body) {
  await ensureCsrf();
  const r = await fetch(apiUrl("game_roulette.php"), {
    method: "POST",
    credentials: "include",
    headers: jsonHeadersWithCsrf(),
    body: JSON.stringify(body),
  });
  const data = await r.json().catch(() => ({}));
  return { ok: data.ok === true, status: r.status, data };
}

export async function postUserCrypto(fields) {
  await ensureCsrf();
  const r = await fetch(apiUrl("user_crypto_save.php"), {
    method: "POST",
    credentials: "include",
    headers: jsonHeadersWithCsrf(),
    body: JSON.stringify(fields),
  });
  const data = await r.json().catch(() => ({}));
  return { ok: r.ok && data.ok === true, status: r.status, data };
}

export async function postUserSponsorAccounts(entries) {
  await ensureCsrf();
  const r = await fetch(apiUrl("user_sponsor_accounts.php"), {
    method: "POST",
    credentials: "include",
    headers: jsonHeadersWithCsrf(),
    body: JSON.stringify({ entries }),
  });
  const data = await r.json().catch(() => ({}));
  return { ok: r.ok && data.ok === true, status: r.status, data };
}

export async function postTelegramLink() {
  await ensureCsrf();
  const r = await fetch(apiUrl("telegram_link.php"), {
    method: "POST",
    credentials: "include",
    headers: jsonHeadersWithCsrf(),
    body: JSON.stringify({}),
  });
  const data = await r.json().catch(() => ({}));
  return { ok: r.ok && data.ok === true, status: r.status, data };
}

export async function fetchTelegramInvite() {
  try {
    const r = await fetch(apiUrl("user_telegram_invite.php"), {
      credentials: "include",
      cache: "no-store",
    });
    const data = await r.json().catch(() => ({}));
    if (typeof data.csrfToken === "string" && data.csrfToken.length > 0) {
      csrfToken = data.csrfToken;
    }
    return { ok: r.ok && data.ok === true, status: r.status, data };
  } catch {
    return { ok: false, status: 0, data: {} };
  }
}

export async function postTelegramInviteLink() {
  await ensureCsrf();
  try {
    const r = await fetch(apiUrl("user_telegram_invite.php"), {
      method: "POST",
      credentials: "include",
      headers: jsonHeadersWithCsrf(),
      body: JSON.stringify({ action: "create_link" }),
    });
    const data = await r.json().catch(() => ({}));
    if (typeof data.csrfToken === "string" && data.csrfToken.length > 0) {
      csrfToken = data.csrfToken;
    }
    return { ok: r.ok && data.ok === true, status: r.status, data };
  } catch {
    return { ok: false, status: 0, data: {} };
  }
}

export async function fetchUserProfile() {
  try {
    const r = await fetch(apiUrl("user_profile.php"), { credentials: "include" });
    const data = await r.json().catch(() => ({}));
    if (r.status === 401) {
      return { ok: false, error: "auth" };
    }
    if (r.status === 503 || data?.error === "db") {
      return { ok: false, error: "db" };
    }
    if (!r.ok || !data.ok) {
      return null;
    }
    return data;
  } catch {
    return null;
  }
}

export async function fetchSpecialOddsPublic() {
  try {
    const r = await fetch(apiUrl("special_odds_public.php"), { credentials: "omit", cache: "no-store" });
    const data = await r.json().catch(() => ({}));
    return { ok: r.ok && data.ok === true, status: r.status, data };
  } catch {
    return { ok: false, status: 0, data: {} };
  }
}

export async function fetchSpecialOddsMyBets() {
  try {
    const r = await fetch(apiUrl("special_odds_my_bets.php"), { credentials: "include", cache: "no-store" });
    const data = await r.json().catch(() => ({}));
    if (typeof data.csrfToken === "string" && data.csrfToken.length > 0) {
      csrfToken = data.csrfToken;
    }
    return { ok: r.ok && data.ok === true, status: r.status, data };
  } catch {
    return { ok: false, status: 0, data: {} };
  }
}

export async function postTicketJoin(body) {
  await ensureCsrf();
  try {
    const r = await fetch(apiUrl("ticket_join.php"), {
      method: "POST",
      credentials: "include",
      headers: jsonHeadersWithCsrf(),
      body: JSON.stringify(body),
    });
    const data = await r.json().catch(() => ({}));
    if (typeof data.csrfToken === "string" && data.csrfToken.length > 0) {
      csrfToken = data.csrfToken;
    }
    return { ok: r.ok && data.ok === true, status: r.status, data };
  } catch {
    return { ok: false, status: 0, data: {} };
  }
}

export async function postSpecialOddsBet(body) {
  await ensureCsrf();
  try {
    const r = await fetch(apiUrl("special_odds_bet.php"), {
      method: "POST",
      credentials: "include",
      headers: jsonHeadersWithCsrf(),
      body: JSON.stringify(body),
    });
    const data = await r.json().catch(() => ({}));
    if (typeof data.csrfToken === "string" && data.csrfToken.length > 0) {
      csrfToken = data.csrfToken;
    }
    return { ok: r.ok && data.ok === true, status: r.status, data };
  } catch {
    return { ok: false, status: 0, data: {} };
  }
}

export async function fetchUserNotifications() {
  try {
    await ensureCsrf();
    const r = await fetch(apiUrl("user_notifications.php"), {
      credentials: "include",
      cache: "no-store",
    });
    const data = await r.json().catch(() => ({}));
    return { ok: r.ok && data.ok === true, status: r.status, data };
  } catch {
    return { ok: false, status: 0, data: {} };
  }
}

export async function postUserNotificationsMarkRead(body) {
  try {
    await ensureCsrf();
    const r = await fetch(apiUrl("user_notifications.php"), {
      method: "POST",
      credentials: "include",
      headers: jsonHeadersWithCsrf(),
      body: JSON.stringify({ action: "mark_read", ...body }),
    });
    const data = await r.json().catch(() => ({}));
    return { ok: r.ok && data.ok === true, status: r.status, data };
  } catch {
    return { ok: false, status: 0, data: {} };
  }
}

const API_FAIL_MSG =
  "Sunucuya ulaşılamadı (ağ hatası veya adres yanlış). Proje kökünde: php -S localhost:8080 — adres: http://localhost:8080/";

const DB_FAIL_MSG =
  "Veritabanı açılamıyor. PHP’de SQLite açık olmalı: php.ini içinde extension=pdo_sqlite ve extension=sqlite3 satırlarının başındaki ; kaldır, Apache/PHP’yi yeniden başlat.";

export function notifyApiFailure() {
  showToast(API_FAIL_MSG, "error");
}

export function notifyDbFailure() {
  showToast(DB_FAIL_MSG, "error");
}
