/**
 * app/settings/team/page.js — Team & organization (server component).
 *
 * The single home for everything team-related, consolidating what used to be
 * split across /settings/account (Supabase connect + org card) and /admin
 * (members + invites):
 *
 *   1. Cloud connection — connect Supabase (enables real sign-in, orgs, sync).
 *   2. Organization     — create or view the org this account belongs to.
 *   3. Members          — roster + role changes + removal (owner/admin).
 *   4. Invite teammates — one shareable link that auto-joins on sign-in.
 *
 * Deep security policy (MFA, IP allowlist, audit, share links, trust mode)
 * still lives in /admin and is linked from here.
 *
 * Works in both auth modes:
 *   - local    → synthetic owner (local-user-1 / Personal Org).
 *   - supabase → real session resolved from the auth cookie.
 */

import { AdminShell, StatusPill, EmptyState } from '@/app/components/admin/admin-page.jsx';
import { requireSession, getAuthMode } from '@/lib/auth.js';
import { getSupabaseAuthConfig, isServiceKeyConfigured, isAuthModeEnvLocked } from '@/lib/auth-config.js';
import { getOrgById, listMembers, getMembership } from '@/lib/org.js';
import { isSharedCloudReady } from '@/lib/shared-cloud.js';
import { ShieldCheck, Cloud, CloudOff } from 'lucide-react';
import AuthConfigForm from '../account/auth-config-form.jsx';
import TeamCreateOrg from './team-create-org.jsx';
import TeamMembers from './team-members.jsx';
import TeamInvites from './team-invites.jsx';
import TeamOrgName from './team-org-name.jsx';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

const CAN_MANAGE = new Set(['owner', 'admin']);

export default async function SettingsTeamPage() {
  let session = null;
  try {
    session = await requireSession(null);
  } catch {
    session = null;
  }

  const authMode = getAuthMode();
  const supabaseCfg = getSupabaseAuthConfig();
  const authConfig = {
    mode: authMode,
    url: supabaseCfg.url || '',
    anonKey: supabaseCfg.anonKey || '',
    serviceKeySet: isServiceKeyConfigured(),
    envLocked: isAuthModeEnvLocked(),
  };

  const orgId = session?.org_id || null;
  const org = orgId ? getOrgById(orgId) : null;
  // node:sqlite returns null-prototype rows — map to plain objects (and only the
  // fields the client needs) before handing them to the TeamMembers client
  // component, or React refuses to serialize them across the RSC boundary.
  const members = (orgId ? listMembers(orgId) : []).map((m) => ({
    user_id: m.user_id,
    role: m.role,
    email: m.email || null,
    display_name: m.display_name || null,
    accepted_at: m.accepted_at || null,
  }));
  const myMembership = orgId && session ? getMembership(session.user_id, orgId) : null;
  const myRole = myMembership?.role || session?.role || 'owner';
  const canManage = CAN_MANAGE.has(myRole);
  const cloudReady = isSharedCloudReady();
  // The seeded `personal-org` in local auth mode is the solo, machine-local
  // default — never shared, never the cloud org. Label it as such so it isn't
  // mistaken for a shareable organization (a real org is auto-created with a
  // unique id on first Supabase sign-in).
  const isLocalDefault = authMode === 'local' && org?.id === 'personal-org';

  return (
    <AdminShell
      kicker="Settings"
      title="Team"
      description="Connect Supabase, set up your organization, and invite teammates. Advanced security policy lives in Admin."
      hideProjectSwitcher
    >
      <div className="mkt-page" data-page="settings-team">

        {/* Stats strip */}
        <section className="mkt-stats">
          <div className="mkt-stat">
            <b>{members.length || 1}</b>
            <span>Members</span>
          </div>
          <div className="mkt-stat">
            <b style={{ textTransform: 'capitalize' }}>{myRole}</b>
            <span>Your role</span>
          </div>
          <div className="mkt-stat">
            <b>{authMode === 'supabase' ? 'Supabase' : 'Local'}</b>
            <span>Auth mode</span>
          </div>
          <div className="mkt-stat">
            <b>{cloudReady ? 'Connected' : 'Local only'}</b>
            <span>Cloud sync</span>
          </div>
        </section>

        {/* 1. Cloud connection */}
        <section className="admin-panel">
          <div className="admin-panel-head">
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: '0.5rem' }}>
              {cloudReady
                ? <Cloud className="settings-rail-icon" strokeWidth={1.75} aria-hidden="true" />
                : <CloudOff className="settings-rail-icon" strokeWidth={1.75} aria-hidden="true" />}
              Cloud connection
            </span>
            <small>Connect a Supabase project to enable real sign-in, shared organizations, and cloud sync. Stored encrypted in the local vault.</small>
          </div>
          <div className="admin-card-list">
            <div className="admin-record">
              <AuthConfigForm initial={authConfig} />
            </div>
          </div>
        </section>

        {/* 2. Organization */}
        <section className="admin-panel">
          <div className="admin-panel-head">
            <span>Organization</span>
            <small>The shared space for members, invites, and audited collaboration.</small>
          </div>
          {org ? (
            <div className="admin-card-list">
              <div className="admin-record">
                <div className="admin-record-top">
                  <TeamOrgName orgId={org.id} name={org.name} canRename={myRole === 'owner'} />
                  {isLocalDefault
                    ? <StatusPill tone="neutral">Personal workspace · local</StatusPill>
                    : <StatusPill tone={org.plan === 'free' ? 'neutral' : 'ready'}>{org.plan || 'free'} plan</StatusPill>}
                </div>
                {isLocalDefault ? (
                  <p className="admin-muted" style={{ fontSize: '0.85em', margin: '0.4rem 0 0' }}>
                    This is your <b>Personal workspace (local)</b> — private to this machine and never shared.
                    Connect Supabase above and sign in to create a real organization (it gets its own unique ID)
                    that you can invite teammates into.
                  </p>
                ) : null}
                <dl className="account-meta">
                  <div><dt>Slug</dt><dd className="mono">{org.slug}</dd></div>
                  <div><dt>Org ID</dt><dd className="mono">{org.id}</dd></div>
                  <div><dt>Members</dt><dd>{members.length || 1}</dd></div>
                  <div><dt>MFA policy</dt><dd>{org.mfa_required ? 'Required' : 'Optional'}</dd></div>
                  <div>
                    <dt>Cloud sync</dt>
                    <dd>{cloudReady ? 'Connected to Supabase' : 'Local only (no service-role key)'}</dd>
                  </div>
                </dl>
                <div className="admin-form-actions" style={{ marginTop: '0.75rem', gap: '0.5rem' }}>
                  <a href="/admin" className="admin-btn-sm" style={{ display: 'inline-flex', alignItems: 'center', gap: '0.4rem' }}>
                    <ShieldCheck className="settings-rail-icon" strokeWidth={1.75} aria-hidden="true" />
                    Advanced security settings
                  </a>
                </div>
              </div>
            </div>
          ) : (
            <div className="admin-card-list">
              <div className="admin-record">
                {session ? (
                  <TeamCreateOrg />
                ) : (
                  <EmptyState title="Sign in to create an organization">
                    Connect Supabase above, then sign in to create or join an organization.
                  </EmptyState>
                )}
              </div>
            </div>
          )}
        </section>

        {/* 3. Members */}
        {org ? (
          <section className="admin-panel">
            <div className="admin-panel-head">
              <span>Members</span>
              <small>
                {canManage
                  ? 'Change roles or remove members. The last owner cannot be removed or demoted.'
                  : 'People in this organization. Ask an owner to change roles.'}
              </small>
            </div>
            <TeamMembers
              orgId={org.id}
              members={members}
              currentUserId={session?.user_id || ''}
              canManage={canManage}
              isOwner={myRole === 'owner'}
            />
          </section>
        ) : null}

        {/* 4. Invite teammates */}
        {org && canManage ? (
          <section className="admin-panel">
            <div className="admin-panel-head">
              <span>Invite teammates</span>
              <small>Share one link. They sign in and join automatically — no codes to copy.</small>
            </div>
            {isLocalDefault ? (
              <div className="admin-card-list">
                <div className="admin-record admin-muted" style={{ fontSize: '0.9em' }}>
                  Your Personal workspace can't be shared — it's local to this machine.
                  Connect Supabase above and sign in to create a shareable organization, then invite teammates here.
                </div>
              </div>
            ) : (
              <TeamInvites orgId={org.id} creatorRole={myRole} cloudReady={cloudReady} />
            )}
          </section>
        ) : null}

      </div>
    </AdminShell>
  );
}
