/* === Supabase client + data layer ===
   - Initializes the Supabase JS client (CDN-loaded from portfolio.html)
   - Exposes window.SB with helpers used by app.jsx
*/

const SUPABASE_URL = "https://eukfofwhokanvjvxvvhx.supabase.co";
const SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImV1a2ZvZndob2thbnZqdnh2dmh4Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3Nzg3MzAwNTMsImV4cCI6MjA5NDMwNjA1M30.-yp_plNejM4LRHQaimdSLa9QpNqMsTQot5yqmKssZAc";
const BUCKET = "portfolio-images";

const supabaseClient = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
  auth: { persistSession: true, autoRefreshToken: true },
});

// DB column is `description` (SQL reserved word avoidance) but client model uses `desc`.
function postFromDb(row) {
  if (!row) return null;
  return {
    id: row.id,
    title: row.title || { ko: "", en: "" },
    category: row.category || "web",
    desc: row.description || { ko: "", en: "" },
    tools: row.tools || [],
    period: row.period || "",
    link: row.link || "",
    thumb: row.thumb || "",
    thumb_focus: row.thumb_focus || "50% 50%",
    extras: row.extras || [],
    palette: row.palette || 0,
    sort_order: row.sort_order || 0,
  };
}

function postToDb(p) {
  const row = {
    id: p.id,
    title: p.title || { ko: "", en: "" },
    category: p.category || "web",
    description: p.desc || { ko: "", en: "" },
    tools: p.tools || [],
    period: p.period || "",
    link: p.link || "",
    thumb: p.thumb || "",
    thumb_focus: p.thumb_focus || "50% 50%",
    extras: p.extras || [],
    palette: p.palette || 0,
  };
  if (typeof p.sort_order === "number") row.sort_order = p.sort_order;
  return row;
}

window.SB = {
  client: supabaseClient,
  bucket: BUCKET,

  async fetchPosts() {
    const { data, error } = await supabaseClient
      .from("posts")
      .select("*")
      .order("created_at", { ascending: false });
    if (error) throw error;
    return (data || []).map(postFromDb);
  },

  async upsertPost(post) {
    const { data, error } = await supabaseClient
      .from("posts")
      .upsert(postToDb(post))
      .select()
      .single();
    if (error) throw error;
    return postFromDb(data);
  },

  async deletePost(post) {
    // Best-effort cleanup of any images stored under {postId}/
    try {
      const { data: files } = await supabaseClient.storage.from(BUCKET).list(post.id);
      if (files && files.length) {
        const paths = files.map((f) => `${post.id}/${f.name}`);
        await supabaseClient.storage.from(BUCKET).remove(paths);
      }
    } catch (e) {
      // ignore storage cleanup errors; the row delete below is the source of truth
    }
    const { error } = await supabaseClient.from("posts").delete().eq("id", post.id);
    if (error) throw error;
  },

  async uploadImage(file, postId) {
    const rawExt = (file.name.split(".").pop() || "jpg").toLowerCase();
    const ext = rawExt.replace(/[^a-z0-9]/g, "") || "jpg";
    const path = `${postId}/${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`;
    const { error } = await supabaseClient.storage.from(BUCKET).upload(path, file, {
      cacheControl: "31536000",
      contentType: file.type || undefined,
      upsert: false,
    });
    if (error) throw error;
    const { data } = supabaseClient.storage.from(BUCKET).getPublicUrl(path);
    return data.publicUrl;
  },

  async seedInitial(seedPosts) {
    const now = Date.now();
    // Backdate seed rows so SEED_POSTS[0] is newest — preserves visual order.
    const rows = seedPosts.map((p, i) => ({
      ...postToDb(p),
      created_at: new Date(now - (i + 1) * 1000).toISOString(),
    }));
    const { error } = await supabaseClient.from("posts").upsert(rows);
    if (error) throw error;
  },

  async signIn(email, password) {
    const { data, error } = await supabaseClient.auth.signInWithPassword({ email, password });
    if (error) throw error;
    return data.session;
  },

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

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

  onAuthChange(cb) {
    const { data } = supabaseClient.auth.onAuthStateChange((_event, session) => cb(session));
    return data.subscription;
  },
};
