// ============================================================
// Husky Paths — Supabase backend client
// ============================================================

(function () {
  const cfg = window.HUSKY_SUPABASE_CONFIG || {};
  const hasRealConfig =
    !!cfg.url &&
    !!cfg.anonKey &&
    !String(cfg.url).includes("YOUR_PROJECT_REF") &&
    !String(cfg.anonKey).includes("YOUR_SUPABASE");

  const client = hasRealConfig && window.supabase
    ? window.supabase.createClient(cfg.url, cfg.anonKey, {
        auth: {
          persistSession: true,
          autoRefreshToken: true,
          detectSessionInUrl: true,
        },
      })
    : null;

  const normalizeEmail = (email) => String(email || "").trim().toLowerCase();

  const assertUwEmail = (email) => {
    const normalized = normalizeEmail(email);
    if (!/^[^@]+@uw\.edu$/.test(normalized)) {
      throw new Error("Please use a valid @uw.edu email address.");
    }
    return normalized;
  };

  const findCity = (cityName) => {
    const city = (window.CITIES || []).find((c) => c.name === cityName);
    if (!city) {
      throw new Error(`Unknown city: ${cityName}`);
    }
    return city;
  };

  const fromDbProfile = (row, meta = {}) => ({
    id: row.id,
    userId: row.user_id,
    name: row.name || "Anonymous",
    email: row.email || "",
    major: row.major || "",
    year: String(row.grad_year || ""),
    pathType: row.path_type || "Industry",
    orgName: row.org_name || "",
    roleDetail: row.role_detail || "",
    city: row.city_name || "",
    lat: row.latitude,
    lng: row.longitude,
    note: row.note || "",
    openToConnect: !!row.open_to_connect,
    linkedin: row.linkedin_url || "",
    wechat: row.wechat_id || "",
    instagram: row.instagram_handle || "",
    createdAt: row.created_at,
    updatedAt: row.updated_at,
    isDemo: false,
    foundingRank: meta.foundingRank || null,
  });

  const toDbProfile = (profile, user) => {
    const city = findCity(profile.city);
    const email = assertUwEmail(user.email);
    const openToConnect = !!profile.openToConnect;

    return {
      profilePayload: {
        user_id: user.id,
        name: String(profile.name || "").trim() || "Anonymous",
        major: String(profile.major || "").trim(),
        grad_year: Number(profile.year),
        path_type: profile.pathType,
        org_name: String(profile.orgName || "").trim(),
        role_detail: String(profile.roleDetail || "").trim() || null,
        city_name: profile.city,
        latitude: city.coords[1],
        longitude: city.coords[0],
        note: String(profile.note || "").trim() || null,
        open_to_connect: openToConnect,
      },
      contactPayload: {
        user_id: user.id,
        email,
        linkedin_url: String(profile.linkedin || "").trim() || null,
        wechat_id: String(profile.wechat || "").trim() || null,
        instagram_handle: String(profile.instagram || "").trim() || null,
      },
    };
  };

  const requireClient = () => {
    if (!client) {
      throw new Error("Supabase is not configured yet.");
    }
    return client;
  };

  const HuskyBackend = {
    isConfigured() {
      return !!client;
    },

    getClient() {
      return client;
    },

    async getSession() {
      const supabaseClient = requireClient();
      const { data, error } = await supabaseClient.auth.getSession();
      if (error) throw error;
      return data.session;
    },

    onAuthStateChange(callback) {
      if (!client) return () => {};
      const { data } = client.auth.onAuthStateChange((_event, session) => callback(session));
      return () => data.subscription.unsubscribe();
    },

    async sendLoginLink(email) {
      const supabaseClient = requireClient();
      const normalized = assertUwEmail(email);
      const redirectUrl = window.location.href.split("#")[0].split("?")[0];
      const { error } = await supabaseClient.auth.signInWithOtp({
        email: normalized,
        options: {
          shouldCreateUser: true,
          emailRedirectTo: redirectUrl,
        },
      });
      if (error) throw error;
      return normalized;
    },

    async verifyOtp(email, token) {
      const supabaseClient = requireClient();
      const normalized = assertUwEmail(email);
      const cleanToken = String(token || "").trim();
      if (!cleanToken) {
        throw new Error("Enter the verification code from your UW email.");
      }
      const { data, error } = await supabaseClient.auth.verifyOtp({
        email: normalized,
        token: cleanToken,
        type: "email",
      });
      if (error) throw error;
      return data.session;
    },

    async signOut() {
      const supabaseClient = requireClient();
      const { error } = await supabaseClient.auth.signOut();
      if (error) throw error;
    },

    async fetchProfiles() {
      const supabaseClient = requireClient();
      // 按 created_at 升序拿，使最早提交者 index 0 → Founding Husky #1
      const { data, error } = await supabaseClient
        .from("public_profiles")
        .select("*")
        .order("created_at", { ascending: true });
      if (error) throw error;
      const rows = data || [];
      // Founding rank 锁定前 50 位提交者
      const ranked = rows.map((row, index) => fromDbProfile(row, {
        foundingRank: index < 50 ? index + 1 : null,
      }));
      // 展示按最新在前（spotlight/list 仍可自行按 year 排）
      return ranked.reverse();
    },

    // 审核通过的提交(在 Supabase 把 submissions.status 改成 'approved' 即自动上墙)
    async fetchApprovedSubmissions() {
      const supabaseClient = requireClient();
      const { data, error } = await supabaseClient
        .from("approved_submissions")
        .select("*")
        .order("created_at", { ascending: true });
      if (error) throw error;
      const cities = window.CITIES || [];
      return (data || []).map((row) => ({
        id: "sub-" + row.id,
        name: row.name || "Anonymous",
        major: row.major || "",
        year: String(row.grad_year || ""),
        pathType: row.path_type || "Industry",
        orgName: row.org_name || "",
        roleDetail: row.role_detail || "",
        city: row.city_name || "",
        note: row.note || "",
        email: "",
        linkedin: row.linkedin_url || "",
        wechat: row.wechat_id || "",
        instagram: row.instagram_handle || "",
        openToConnect: !!row.open_to_connect,
        isCommunity: true,
      })).filter((p) => cities.some((c) => c.name === p.city));  // 只保留城市能匹配上的(否则地图无坐标)
    },

    // ── /admin 后台:仅管理员邮箱(RLS 限定)可读全部 + 改状态 ──
    async fetchAllSubmissions() {
      const supabaseClient = requireClient();
      const { data, error } = await supabaseClient
        .from("submissions")
        .select("*")
        .order("created_at", { ascending: false });
      if (error) throw error;
      return data || [];
    },

    async setSubmissionStatus(id, status) {
      const supabaseClient = requireClient();
      const { error } = await supabaseClient
        .from("submissions")
        .update({ status })
        .eq("id", id);
      if (error) throw error;
      return true;
    },

    async getMyProfile() {
      const supabaseClient = requireClient();
      const { data, error } = await supabaseClient
        .from("my_profile")
        .select("*")
        .maybeSingle();
      if (error) throw error;
      return data ? fromDbProfile(data, { foundingRank: 1 }) : null;
    },

    async upsertProfile(profile) {
      const supabaseClient = requireClient();
      const session = await this.getSession();
      if (!session?.user) {
        throw new Error("Please verify your UW email before submitting.");
      }

      const formEmail = assertUwEmail(profile.email);
      const sessionEmail = assertUwEmail(session.user.email);
      if (formEmail !== sessionEmail) {
        throw new Error(`You are signed in as ${sessionEmail}. Use that UW email in the form.`);
      }

      const { profilePayload, contactPayload } = toDbProfile(profile, session.user);
      const { error: profileError } = await supabaseClient
        .from("profiles")
        .upsert(profilePayload, { onConflict: "user_id" });
      if (profileError) throw profileError;

      const { error: contactError } = await supabaseClient
        .from("profile_contacts")
        .upsert(contactPayload, { onConflict: "user_id" });
      if (contactError) throw contactError;

      return this.getMyProfile();
    },

    async submitForReview(profile) {
      const supabaseClient = requireClient();
      const org = String(profile.orgName || "").trim();
      const city = String(profile.city || "").trim();
      if (!org || !city) {
        throw new Error("Company/school and city are required. · 请填写机构和城市。");
      }
      const yr = parseInt(profile.year, 10);
      const lk = String(profile.linkedin || "").trim() || null;
      const wc = String(profile.wechat || "").trim() || null;
      const ig = String(profile.instagram || "").trim() || null;
      const hasHandle = !!(lk || wc || ig);
      const { error } = await supabaseClient.from("submissions").insert({
        name: String(profile.name || "").trim() || null,
        major: String(profile.major || "").trim() || null,
        grad_year: Number.isFinite(yr) ? yr : null,
        path_type: profile.pathType || "Industry",
        org_name: org,
        city_name: city,
        role_detail: String(profile.roleDetail || "").trim() || null,
        note: String(profile.note || "").trim() || null,
        contact_hint: String(profile.contactHint || "").trim() || null,
        open_to_connect: !!profile.openToConnect && hasHandle,   // 没留任何账号 → 不算开放,避免空联系卡
        linkedin_url: lk,
        wechat_id: wc,
        instagram_handle: ig,
      });
      if (error) throw error;
      return true;
    },

    async submitFeedback({ message, contact, page }) {
      const supabaseClient = requireClient();
      const text = String(message || "").trim();
      if (!text) throw new Error("Please write a message first. · 请先写点内容。");
      if (text.length > 5000) throw new Error("Message is too long (max 5000 chars).");
      const { error } = await supabaseClient.from("feedback").insert({
        message: text,
        contact: String(contact || "").trim() || null,
        page: String(page || "").slice(0, 300) || null,
      });
      if (error) throw error;
      return true;
    },

    async deleteMyProfile() {
      const supabaseClient = requireClient();
      const session = await this.getSession();
      if (!session?.user) {
        throw new Error("Please verify your UW email first.");
      }

      const { error: contactError } = await supabaseClient
        .from("profile_contacts")
        .delete()
        .eq("user_id", session.user.id);
      if (contactError) throw contactError;

      const { error: profileError } = await supabaseClient
        .from("profiles")
        .delete()
        .eq("user_id", session.user.id);
      if (profileError) throw profileError;

      return true;
    },
  };

  window.HuskyBackend = HuskyBackend;
})();
