// app/hail/page.js — HAIL engagements list + new-engagement intake.
//
// Calm, confidential, principal-grade. The entry point to the operating-model
// configuration layer. Creating an engagement provisions a project and starts
// the lifecycle case; HAIL requires a named accountable human.

import Link from 'next/link';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { AdminShell, EmptyState, StatusPill } from '../components/admin/admin-page.jsx';
import { listEngagements, createEngagement } from '../../lib/hail/engagements.js';
import { requirePractitionerPage } from './hail-guard.js';
import { INSTITUTION_TYPES } from './hail-ui.js';

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

const STAGE_TONE = { diagnostic: 'info', blueprint: 'info', pilot: 'warning', managed_layer: 'success' };
const STAGE_LABEL = { diagnostic: 'Diagnostic', blueprint: 'Blueprint', pilot: 'Pilot', managed_layer: 'Managed Layer' };

async function createEngagementAction(formData) {
  'use server';
  await requirePractitionerPage();
  const principal_name = String(formData.get('principal_name') || '').trim();
  const accountable_human = String(formData.get('accountable_human') || '').trim();
  const institution_type = String(formData.get('institution_type') || '').trim() || null;
  const confidentiality_posture = String(formData.get('confidentiality_posture') || 'local_first_strict').trim();
  if (!principal_name || !accountable_human) return;
  const engagement = createEngagement({ principal_name, accountable_human, institution_type, confidentiality_posture });
  revalidatePath('/hail');
  redirect(`/hail/${engagement.id}`);
}

export default async function HailPage() {
  await requirePractitionerPage();
  const engagements = listEngagements();

  return (
    <AdminShell
      kicker="madarX OS · HAIL"
      title="Operating-model engagements"
      description="The Human-to-Agent Intelligence Layer. Each engagement studies a principal's operating reality and configures madarX OS under governance — only after human review."
      hideProjectSwitcher
    >
      <div className="hail-grid">
        <section className="hail-panel">
          <h2 className="hail-panel-title">Engagements</h2>
          {engagements.length === 0 ? (
            <EmptyState title="No engagements yet">
              Start the first HAIL engagement. The first hour is the Configuration Interview.
            </EmptyState>
          ) : (
            <ul className="hail-list">
              {engagements.map((e) => (
                <li key={e.id} className="hail-list-row">
                  <Link href={`/hail/${e.id}`} className="hail-list-link">
                    <span className="hail-list-name">{e.principal_name}</span>
                    <span className="hail-list-meta">{e.institution_type || 'Principal'} · {e.accountable_human}</span>
                  </Link>
                  <StatusPill tone={STAGE_TONE[e.current_stage] || 'neutral'}>
                    {STAGE_LABEL[e.current_stage] || e.current_stage}
                  </StatusPill>
                </li>
              ))}
            </ul>
          )}
        </section>

        <section className="hail-panel">
          <h2 className="hail-panel-title">New engagement</h2>
          <form action={createEngagementAction} className="hail-form">
            <label className="hail-field">
              <span>Principal / institution name</span>
              <input name="principal_name" required placeholder="As it should appear on the dossier" />
            </label>
            <label className="hail-field">
              <span>Institution type</span>
              <select name="institution_type" defaultValue="">
                <option value="">Select…</option>
                {INSTITUTION_TYPES.map((t) => <option key={t} value={t}>{t}</option>)}
              </select>
            </label>
            <label className="hail-field">
              <span>Named accountable counterparty <em className="hail-req">required</em></span>
              <input name="accountable_human" required placeholder="Chief of staff, counsel, principal…" />
              <small className="hail-hint">HAIL will not proceed without a named human accountable for the work.</small>
            </label>
            <label className="hail-field">
              <span>Confidentiality posture</span>
              <select name="confidentiality_posture" defaultValue="local_first_strict">
                <option value="local_first_strict">Local-first strict (no cloud)</option>
                <option value="local_first_named_cloud">Local-first with named, scoped cloud</option>
                <option value="hybrid">Hybrid (explicit per-artifact sharing)</option>
              </select>
            </label>
            <button type="submit" className="hail-btn hail-btn-primary">Begin engagement</button>
          </form>
        </section>
      </div>
    </AdminShell>
  );
}
