// ─────────────────────────────────────────────────────────────
// PORTAL CORE — supabase client, auth hook, data + notification helpers
// ─────────────────────────────────────────────────────────────
const { SUPABASE_URL, SUPABASE_ANON_KEY } = window.ZENTRO_PORTAL_CONFIG;
const sb = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
window.sb = sb;

// ── Constants ──
window.PORTAL = {
  STATUSES: [
    { id: "todo",               label: "To Do",              color: "#797984" },
    { id: "in_progress",        label: "In Progress",        color: "#6E8BA8" },
    { id: "awaiting_review",    label: "Awaiting Review",    color: "#FBD028" },
    { id: "revision_requested", label: "Revision Requested", color: "#E5A13A" },
    { id: "completed",          label: "Completed",          color: "#3FB57A" },
  ],
  PRIORITIES: [
    { id: "low",    label: "Low",    color: "#797984" },
    { id: "medium", label: "Medium", color: "#6E8BA8" },
    { id: "high",   label: "High",   color: "#E5A13A" },
    { id: "urgent", label: "Urgent", color: "#E2492E" },
  ],
  statusOf:   (id) => window.PORTAL.STATUSES.find(s => s.id === id)   || window.PORTAL.STATUSES[0],
  priorityOf: (id) => window.PORTAL.PRIORITIES.find(p => p.id === id) || window.PORTAL.PRIORITIES[1],
  fmtDate: (d) => d ? new Date(d + (d.length === 10 ? "T00:00:00" : "")).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }) : "—",
  fmtTime: (d) => d ? new Date(d).toLocaleString("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" }) : "",
  timeAgo: (d) => {
    const s = Math.floor((Date.now() - new Date(d).getTime()) / 1000);
    if (s < 60) return "just now";
    if (s < 3600) return Math.floor(s / 60) + "m ago";
    if (s < 86400) return Math.floor(s / 3600) + "h ago";
    return Math.floor(s / 86400) + "d ago";
  },
};

// ── Auth hook ──
window.useAuth = function useAuth() {
  const [session, setSession] = React.useState(undefined); // undefined = loading
  const [profile, setProfile] = React.useState(null);

  React.useEffect(() => {
    sb.auth.getSession().then(({ data }) => setSession(data.session || null));
    const { data: sub } = sb.auth.onAuthStateChange((_e, s) => setSession(s || null));
    return () => sub.subscription.unsubscribe();
  }, []);

  React.useEffect(() => {
    if (!session) { setProfile(null); return; }
    sb.from("profiles").select("*").eq("id", session.user.id).single()
      .then(({ data }) => setProfile(data));
  }, [session]);

  return { session, profile, setProfile };
};

// ── Activity log ──
window.logActivity = async function (taskId, actorId, action) {
  await sb.from("activity_logs").insert({ task_id: taskId, actor_id: actorId, action });
};

// ── Notification fan-out ──
// Notifies: admins + the project's client login + assigned editor (minus the actor)
window.emitEvent = async function (type, { task, project, actor, title, body }) {
  try {
    const recipients = new Set();
    const { data: admins } = await sb.from("profiles").select("id").eq("role", "admin");
    (admins || []).forEach(a => recipients.add(a.id));
    if (task?.assigned_editor) recipients.add(task.assigned_editor);
    if (project?.client_id) {
      const { data: cl } = await sb.from("clients").select("profile_id").eq("id", project.client_id).single();
      if (cl?.profile_id) recipients.add(cl.profile_id);
    }
    recipients.delete(actor.id);
    if (!recipients.size) return;
    const rows = [...recipients].map(uid => ({
      user_id: uid, type, title, body: body || "", task_id: task?.id || null,
    }));
    await sb.from("notifications").insert(rows);
  } catch (e) { console.error("emitEvent failed", e); }
};
