/**
 * app/settings/account/page.js — Account & Organization (server component).
 *
 * Replaces the former General settings page (which duplicated the in-dashboard
 * Agent Configuration panel). Surfaces the signed-in profile and the Supabase
 * organization the account belongs to. Read-mostly: deep membership / security
 * controls live in /admin.
 *
 * Works in both auth modes:
 *   - local    → synthetic owner (local-user-1 / Personal Org).
 *   - supabase → real session resolved from the auth cookie.
 */

import { AdminShell, StatusPill } from '@/app/components/admin/admin-page.jsx';
import { requireSession, getAuthMode } from '@/lib/auth.js';
import { listMembers, getMembership } from '@/lib/org.js';
import { isSharedCloudReady } from '@/lib/shared-cloud.js';
import { getDb } from '@/lib/db.js';
import { Users } from 'lucide-react';

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

const ROLE_TONES = {
  owner: 'mars',
  admin: 'ready',
  member: 'neutral',
  viewer: 'neutral',
};

function initials(name = '', email = '') {
  const source = name || email || '';
  return (
    source
      .split(/[\s@.]+/)
      .map((part) => part[0])
      .filter(Boolean)
      .slice(0, 2)
      .join('')
      .toUpperCase() || '·'
  );
}

function getUserRow(userId) {
  try {
    return getDb()
      .prepare('SELECT email, display_name, avatar_url, auth_provider, last_sign_in_at, created_at FROM users WHERE id = ?')
      .get(userId) || null;
  } catch {
    return null;
  }
}

export default async function SettingsAccountPage() {
  // requireSession ignores the request entirely in local mode (returns the
  // synthetic owner); in supabase mode the server-component request context
  // carries the auth cookie. Mirrors app/admin/page.js.
  let session = null;
  try {
    session = await requireSession(null);
  } catch {
    session = null;
  }

  const userRow = session ? getUserRow(session.user_id) : null;
  const displayName = userRow?.display_name || session?.display_name || 'Local Owner';
  const email = userRow?.email || session?.email || '—';
  const role = session?.role || 'owner';
  const authMode = getAuthMode();

  const orgId = session?.org_id || null;
  const members = orgId ? listMembers(orgId) : [];
  const myMembership = orgId && session ? getMembership(session.user_id, orgId) : null;
  const cloudReady = isSharedCloudReady();

  const lastSignIn = userRow?.last_sign_in_at ? userRow.last_sign_in_at.slice(0, 10) : null;
  const joined = (myMembership?.accepted_at || userRow?.created_at || '').slice(0, 10) || null;

  return (
    <AdminShell
      kicker="Settings"
      title="Account"
      description="Your login profile and the organization this account belongs to. Membership, roles, and security policy are managed in Admin."
      hideProjectSwitcher
    >
      <div className="mkt-page" data-page="settings-account">

        {/* Stats strip */}
        <section className="mkt-stats">
          <div className="mkt-stat">
            <b style={{ textTransform: 'capitalize' }}>{role}</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>{members.length || 1}</b>
            <span>Org members</span>
          </div>
          <div className="mkt-stat">
            <b>{cloudReady ? 'Connected' : 'Local only'}</b>
            <span>Cloud sync</span>
          </div>
        </section>

        {/* Login profile */}
        <section className="admin-panel">
          <div className="admin-panel-head">
            <span>Login profile</span>
            <small>The identity this session is authenticated as.</small>
          </div>
          <div className="admin-card-list">
            <div className="admin-record">
              <div className="admin-record-top" style={{ alignItems: 'center', gap: '0.85rem' }}>
                <div className="org-card-avatar" aria-hidden="true">{initials(displayName, email)}</div>
                <div style={{ flex: 1 }}>
                  <b>{displayName}</b>
                  <div className="admin-muted" style={{ fontSize: '0.9em' }}>{email}</div>
                </div>
                <StatusPill tone={ROLE_TONES[role] || 'neutral'}>{role}</StatusPill>
              </div>
              <dl className="account-meta">
                <div><dt>Auth provider</dt><dd>{userRow?.auth_provider || authMode}</dd></div>
                <div><dt>User ID</dt><dd className="mono">{session?.user_id || '—'}</dd></div>
                {lastSignIn ? <div><dt>Last sign-in</dt><dd>{lastSignIn}</dd></div> : null}
                {joined ? <div><dt>Member since</dt><dd>{joined}</dd></div> : null}
              </dl>
              {authMode === 'supabase' ? (
                <div className="admin-form-actions" style={{ marginTop: '0.75rem' }}>
                  <a href="/login" className="admin-btn-sm">Switch account</a>
                </div>
              ) : (
                <p className="admin-muted" style={{ fontSize: '0.85em', marginTop: '0.5rem' }}>
                  Local mode — a single synthetic owner. Configure Supabase below to enable real account sign-in.
                </p>
              )}
            </div>
          </div>
        </section>

        {/* Team & organization moved to /settings/team */}
        <section className="admin-panel">
          <div className="admin-panel-head">
            <span>Team &amp; organization</span>
            <small>Supabase connection, your organization, members, and invites now live in one place.</small>
          </div>
          <div className="admin-card-list">
            <div className="admin-record">
              <div className="admin-record-top" style={{ alignItems: 'center', gap: '0.75rem' }}>
                <Users className="settings-rail-icon" strokeWidth={1.75} aria-hidden="true" />
                <div style={{ flex: 1 }}>
                  <b>Manage your team</b>
                  <div className="admin-muted" style={{ fontSize: '0.9em' }}>
                    Connect Supabase, create your organization, and invite teammates with one shareable link.
                  </div>
                </div>
                <StatusPill tone={cloudReady ? 'ready' : 'neutral'}>{cloudReady ? 'Connected' : 'Local only'}</StatusPill>
              </div>
              <div className="admin-form-actions" style={{ marginTop: '0.75rem' }}>
                <a href="/settings/team" className="admin-btn-primary">Open Team settings</a>
              </div>
            </div>
          </div>
        </section>

      </div>
    </AdminShell>
  );
}
