// Vanday — Clerk Organizations widgets (Phase 2 team workspaces).
//
// Thin React wrappers around Clerk's hosted UI components. We mount them
// into refs after Clerk has finished loading (signalled by the
// `clerk-ready` window event set in Vanday.html). Unmount on cleanup so
// React state changes don't double-mount.

function useClerkReady() {
  const [ready, setReady] = React.useState(window.__clerkReady === true);
  React.useEffect(() => {
    if (ready) return;
    const onReady = () => setReady(true);
    window.addEventListener("clerk-ready", onReady);
    return () => window.removeEventListener("clerk-ready", onReady);
  }, [ready]);
  return ready;
}

// Switcher: dropdown showing the user's personal account + every org they
// belong to. Mount in the Rail or app header.
//
// "Create organization" is intentionally HIDDEN — multiple workspaces is a
// Pro-plan feature and we don't have plan upgrades shipped yet. When
// upgrades land, swap the hide rules for a gated upsell flow.
function ClerkOrgSwitcher({ appearance }) {
  const ref = React.useRef(null);
  const ready = useClerkReady();
  React.useEffect(() => {
    if (!ready || !ref.current || !window.Clerk) return;
    const node = ref.current;
    // Merge the caller's appearance with the create-org hide rules so we
    // don't clobber styling passed in from above.
    const mergedAppearance = {
      ...(appearance || {}),
      elements: {
        // Pop-over "Create organization" CTA + the empty-state "Create one"
        // button that shows when the user has zero orgs. Both classes ship
        // from Clerk; cover the documented variants so a future rename in
        // either spot doesn't silently re-expose the button.
        organizationSwitcherPopoverActionButton__createOrganization: { display: "none" },
        organizationSwitcherPopoverActionButton__createOrganizationContainer: { display: "none" },
        organizationSwitcherPopoverActions__createOrganization: { display: "none" },
        ...((appearance && appearance.elements) || {}),
      },
    };
    window.Clerk.mountOrganizationSwitcher(node, {
      hidePersonal: false,
      // Even with the button hidden, force navigation mode (instead of the
      // default modal) so any stray click can't open the create flow.
      createOrganizationMode: "navigation",
      createOrganizationUrl: undefined,
      // After picking an org from the switcher, reload so all API calls
      // pick up the new orgId from the Clerk session token.
      afterSelectPersonalUrl: window.location.pathname,
      afterSelectOrganizationUrl: window.location.pathname,
      appearance: mergedAppearance,
    });
    return () => { try { window.Clerk.unmountOrganizationSwitcher(node); } catch {} };
  }, [ready, appearance]);
  return <div ref={ref} style={{ minHeight: 32 }} />;
}

// Full org-management panel: rename, members, invites, leave/delete.
// Embed in Settings → Workspace.
function ClerkOrgProfile({ appearance }) {
  const ref = React.useRef(null);
  const ready = useClerkReady();
  React.useEffect(() => {
    if (!ready || !ref.current || !window.Clerk) return;
    const node = ref.current;
    try {
      window.Clerk.mountOrganizationProfile(node, { appearance });
    } catch (err) {
      // Mostly fires when user has no active org — they need to create one
      // first via the switcher. Render a friendly hint in that case.
      console.warn("[org-profile] mount failed:", err.message);
    }
    return () => { try { window.Clerk.unmountOrganizationProfile(node); } catch {} };
  }, [ready, appearance]);

  // If Clerk reports no active org, OrganizationProfile won't render — show
  // a Pro-plan teaser instead. Team workspaces (multiple orgs, invites,
  // shared libraries) are a Pro feature; upgrade flow ships later.
  const hasActiveOrg = !!(window.Clerk && window.Clerk.organization);
  if (ready && !hasActiveOrg) {
    return (
      <div style={{
        padding: 24,
        background: "var(--surface-sunken)",
        border: "1px solid var(--border)",
        borderRadius: 10,
        fontSize: 14,
        color: "var(--text-muted)",
        textAlign: "center",
      }}>
        <div style={{ fontSize: 16, color: "var(--text)", fontWeight: 500, marginBottom: 6 }}>
          You're in your personal workspace
        </div>
        <div style={{ marginBottom: 4 }}>
          Team workspaces — invite teammates, share a library, and
          collaborate on social posting — are part of the Pro plan.
        </div>
        <div style={{ fontSize: 12, color: "var(--text-faint)" }}>
          Coming soon. We'll let you know when upgrades open up.
        </div>
      </div>
    );
  }

  return <div ref={ref} style={{ minHeight: 320 }} />;
}

// Full personal-account panel: name, avatar, email addresses, password,
// two-factor, connected accounts, active devices. Embed in Settings →
// Profile. This is Clerk's hosted UserProfile — every control is live, so
// "Change password", "Add email", "Enable 2FA" etc. all actually work.
function ClerkUserProfile({ appearance }) {
  const ref = React.useRef(null);
  const ready = useClerkReady();
  React.useEffect(() => {
    if (!ready || !ref.current || !window.Clerk) return;
    const node = ref.current;
    try {
      window.Clerk.mountUserProfile(node, { appearance });
    } catch (err) {
      console.warn("[user-profile] mount failed:", err.message);
    }
    return () => { try { window.Clerk.unmountUserProfile(node); } catch {} };
  }, [ready, appearance]);

  if (!ready) {
    return <div style={{ color: "var(--text-muted)", fontSize: 14 }}>Loading…</div>;
  }
  return <div ref={ref} style={{ minHeight: 320 }} />;
}

// --- Vanday workspace identity ---------------------------------------------
// We deliberately don't surface Clerk's OrganizationSwitcher in the beta
// (multiple workspaces is a future paid feature, and its built-in "Personal
// account" label reads oddly for a solo studio). Instead we show the
// workspace's own name — set by the user at signup and editable in Settings.

// Initials for the workspace avatar: first letter of the first two words.
function workspaceInitials(name) {
  const parts = String(name || "").trim().split(/\s+/).filter(Boolean);
  if (!parts.length) return "V";
  const a = parts[0][0] || "";
  const b = parts.length > 1 ? (parts[parts.length - 1][0] || "") : "";
  return (a + b).toUpperCase();
}

// Just the workspace name as text, for the breadcrumb. Falls back gracefully
// while /api/me is still loading.
function WorkspaceName({ fallback = "My Workspace" }) {
  const me = (typeof window.useVandayMe === "function") ? window.useVandayMe() : null;
  return <>{(me && me.org && me.org.name) || fallback}</>;
}

// Avatar + name block for the top of the sidebar (replaces the Clerk switcher).
function WorkspaceBadge() {
  const me = (typeof window.useVandayMe === "function") ? window.useVandayMe() : null;
  const name = (me && me.org && me.org.name) || "My Workspace";
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10, minWidth: 0 }}>
      <div style={{
        width: 28, height: 28, borderRadius: 8, flexShrink: 0,
        background: "var(--accent, #c8553d)", color: "white",
        display: "grid", placeItems: "center",
        fontWeight: 700, fontSize: 12, letterSpacing: 0.2,
      }}>{workspaceInitials(name)}</div>
      <div style={{ minWidth: 0 }}>
        <div style={{
          fontWeight: 600, fontSize: 14, lineHeight: 1.2,
          whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
        }}>{name}</div>
        <div style={{ fontSize: 11, color: "var(--text-muted)", lineHeight: 1.2 }}>Free Beta</div>
      </div>
    </div>
  );
}

window.ClerkOrgSwitcher = ClerkOrgSwitcher;
window.ClerkOrgProfile = ClerkOrgProfile;
window.ClerkUserProfile = ClerkUserProfile;
window.WorkspaceName = WorkspaceName;
window.WorkspaceBadge = WorkspaceBadge;
