import { render } from 'preact';
import { useEffect, useMemo, useState } from 'preact/hooks';
import { enqueue, findPendingDuplicate, pendingCount, sync, type Enquiry } from './offline';
import {
  csvTemplate,
  parseCsv,
  validateImportRows,
  type CsvIssue,
  type CsvRow,
} from './csv-import';
import {
  ageDetails,
  genders,
  lookingOptions,
  normaliseEnquiry,
  programmes,
  referralOptions,
} from './enquiry-integrity';
import './style.css';

const clientId = import.meta.env.VITE_GOOGLE_CLIENT_ID || '';
// One setting drives every school-website link, including every logo link.
const mainSite =
  import.meta.env.VITE_SCHOOL_WEBSITE_URL ||
  import.meta.env.VITE_MAIN_SITE_URL ||
  'https://firstep.ananthdeodhar.com';
const statuses = ['new', 'contacted', 'visit', 'application', 'admitted', 'closed'];
// Change table pagination in one place rather than inside individual components.
const pageSizes = { enquiries: 10, devices: 8, staffUsers: 8 } as const;
const staffSessionTimeoutMs = { sharedDevice: 2 * 60 * 1000, standard: 15 * 60 * 1000 };
const blankForm: Omit<Enquiry, 'id'> = {
  parent_name: '',
  email: '',
  phone: '',
  child_name: '',
  child_dob: '',
  programme: '',
  preferred_centre_id: '',
  looking_for: [],
  child_gender: '',
  child_age: '',
  last_school_attended: '',
  mother_name: '',
  mother_mobile: '',
  mother_occupation: '',
  mother_qualification: '',
  mother_company: '',
  mother_designation: '',
  mother_email: '',
  father_name: '',
  father_mobile: '',
  father_occupation: '',
  father_qualification: '',
  father_company: '',
  father_designation: '',
  father_email: '',
  guardian_name: '',
  guardian_mobile: '',
  guardian_occupation: '',
  guardian_qualification: '',
  guardian_company: '',
  guardian_designation: '',
  guardian_email: '',
  residential_address: '',
  city: '',
  state: '',
  pin_code: '',
  referral_sources: [],
};

async function api(path: string, token: string, options: RequestInit = {}) {
  const r = await fetch('/api/' + path, {
    ...options,
    headers: {
      'content-type': 'application/json',
      authorization: 'Bearer ' + token,
      ...options.headers,
    },
  });
  const data = await r.json();
  if (!r.ok) throw Error(data.error || 'Request failed');
  return data;
}
const Icon = ({ name }: { name: string }) => (
  <span class="icon" aria-hidden="true">
    {{
      home: '⌂',
      enquiries: '▤',
      users: '♙',
      assets: '◇',
      devices: '▣',
      import: '⇩',
      menu: '☰',
      close: '×',
    }[name] || '•'}
  </span>
);
function ActionIcon({ name }: { name: 'edit' | 'delete' | 'open' | 'deactivate' }) {
  const paths = {
    edit: (
      <>
        <path d="M12 20h9" />
        <path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L8 18l-4 1 1-4Z" />
      </>
    ),
    delete: (
      <>
        <path d="M3 6h18" />
        <path d="M8 6V4h8v2" />
        <path d="M19 6l-1 14H6L5 6" />
        <path d="M10 11v5M14 11v5" />
      </>
    ),
    open: (
      <>
        <path d="M14 3h7v7" />
        <path d="M10 14 21 3" />
        <path d="M21 14v6a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h6" />
      </>
    ),
    deactivate: (
      <>
        <circle cx="12" cy="12" r="9" />
        <path d="m6 6 12 12" />
      </>
    ),
  };
  return (
    <svg
      class="action-svg"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      {paths[name]}
    </svg>
  );
}
function Brand() {
  return (
    <a class="brand" href={mainSite} title="Open the school website">
      <img src="/first-step-logo.png" alt="First Step Montessori School" />
    </a>
  );
}
function Field({
  label,
  name,
  type = 'text',
  value,
  onInput,
  required = false,
  placeholder = '',
  span = false,
}: {
  label: string;
  name: string;
  type?: string;
  value: string;
  onInput: (v: string) => void;
  required?: boolean;
  placeholder?: string;
  span?: boolean;
}) {
  return (
    <label class={'field ' + (span ? 'span-2' : '')}>
      <span>
        {label}
        {required && <b aria-hidden="true"> *</b>}
      </span>
      <input
        id={name}
        name={name}
        type={type}
        value={value}
        placeholder={placeholder}
        required={required}
        onInput={(e: any) => onInput(e.currentTarget.value)}
      />
    </label>
  );
}
function CheckGroup({
  title,
  options,
  value,
  onChange,
}: {
  title: string;
  options: readonly string[];
  value: string[];
  onChange: (v: string[]) => void;
}) {
  return (
    <fieldset class="check-group">
      <legend>{title}</legend>
      <div class="check-grid">
        {options.map((option) => (
          <label class="check">
            <input
              type="checkbox"
              checked={value.includes(option)}
              onChange={() =>
                onChange(
                  value.includes(option) ? value.filter((x) => x !== option) : [...value, option],
                )
              }
            />
            <span>{option}</span>
          </label>
        ))}
      </div>
    </fieldset>
  );
}

function ReceptionForm({
  device = '',
  pending = 0,
  onSaved,
  onSync = () => {},
  embedded = false,
  staffCentre = '',
  onStaffSubmit,
  onStaffComplete,
}: {
  device?: string;
  pending?: number;
  onSaved: (message: string) => void;
  onSync?: () => void;
  embedded?: boolean;
  staffCentre?: string;
  onStaffSubmit?: (payload: Enquiry & { centre_id: string }) => Promise<void>;
  onStaffComplete?: () => void;
}) {
  const [form, setForm] = useState({ ...blankForm }),
    [busy, setBusy] = useState(false),
    [submitted, setSubmitted] = useState(false);
  const set = (key: keyof typeof blankForm, value: any) =>
    setForm((current) => ({ ...current, [key]: value }));
  useEffect(() => {
    if (!form.child_dob) return;
    const details = ageDetails(form.child_dob);
    setForm((current) => ({ ...current, child_age: details.label, programme: details.programme }));
  }, [form.child_dob]);
  async function submit(e: Event) {
    e.preventDefault();
    setSubmitted(true);
    const normalised = normaliseEnquiry(form);
    if (!normalised.ok) {
      onSaved(normalised.error);
      return;
    }
    const payload: Enquiry = {
      ...form,
      ...normalised.value,
      id: crypto.randomUUID(),
    };
    if (onStaffSubmit) {
      if (!staffCentre) {
        onSaved('Select the centre handling this enquiry.');
        return;
      }
      setBusy(true);
      try {
        await onStaffSubmit({ ...payload, centre_id: staffCentre });
        setForm({ ...blankForm });
        setSubmitted(false);
        onStaffComplete?.();
      } catch (error: any) {
        onSaved(error.message || 'Could not create the enquiry.');
      } finally {
        setBusy(false);
      }
      return;
    }
    if (!device) {
      onSaved(
        'This reception device must be registered by an administrator before it can accept enquiries.',
      );
      return;
    }
    setBusy(true);
    try {
      if (await findPendingDuplicate(payload)) {
        onSaved('This enquiry is already waiting to sync on this device.');
        return;
      }
      if (navigator.onLine) {
        const check = await fetch('/api/enquiries/check-duplicate', {
            method: 'POST',
            headers: { 'content-type': 'application/json', 'x-device-token': device },
            body: JSON.stringify(payload),
          }),
          result = await check.json();
        if (!check.ok) throw Error(result.error || 'Duplicate check failed');
        if (result.duplicate) {
          onSaved(
            `Possible duplicate: ${result.enquiry_number || 'an existing enquiry'} already exists for this child.`,
          );
          return;
        }
      }
      await enqueue(payload);
      setForm({ ...blankForm });
      setSubmitted(false);
      onSaved(
        navigator.onLine
          ? 'Enquiry saved securely. Syncing now…'
          : 'Enquiry saved on this device. It will sync when the connection returns.',
      );
      if (navigator.onLine) await sync(device, onSync);
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } catch (error: any) {
      onSaved('Could not check or save this enquiry: ' + error.message);
    } finally {
      setBusy(false);
    }
  }
  return (
    <div class={'reception-page ' + (embedded ? 'embedded-reception-form' : '')}>
      {!embedded && (
        <div class="page-intro">
          <div>
            <span class="eyebrow">RECEPTION DESK</span>
            <h1>New enquiry</h1>
            <p>Capture a family’s first conversation with First Step.</p>
          </div>
          <div class="sync-card">
            <span class={'sync-dot ' + (navigator.onLine ? 'online' : '')}></span>
            <div>
              <strong>{navigator.onLine ? 'Online' : 'Working offline'}</strong>
              <small>
                {pending} {pending === 1 ? 'enquiry' : 'enquiries'} waiting to sync
              </small>
            </div>
            <button class="text-button" type="button" onClick={onSync}>
              Sync now
            </button>
          </div>
        </div>
      )}
      <form class="enquiry-form" onSubmit={submit} noValidate>
        <section class="form-section">
          <SectionTitle
            n="01"
            title="What are you looking for?"
            copy="Select every service the family is interested in."
          />
          <CheckGroup
            title="Services of interest"
            options={lookingOptions}
            value={form.looking_for}
            onChange={(v) => set('looking_for', v)}
          />
        </section>
        <section class="form-section">
          <SectionTitle
            n="02"
            title="About the child"
            copy="Basic details to help the team guide the family."
          />
          <div class="form-grid">
            <Field
              label="Name of the child"
              name="child_name"
              value={form.child_name}
              required
              onInput={(v) => set('child_name', v)}
            />
            <Field
              label="Date of birth"
              name="child_dob"
              type="date"
              value={form.child_dob}
              required
              onInput={(v) => set('child_dob', v)}
            />
            <label class="field">
              <span>Gender</span>
              <select
                value={form.child_gender}
                onChange={(e: any) => set('child_gender', e.currentTarget.value)}
              >
                <option value="">Select</option>
                <option>Female</option>
                <option>Male</option>
                <option>Other</option>
                <option>Prefer not to say</option>
              </select>
            </label>
            <label class="field programme-field">
              <span>
                Programme of interest <b>*</b>
              </span>
              <select
                value={form.programme}
                required
                onChange={(e: any) => set('programme', e.currentTarget.value)}
              >
                <option value="">Select a programme</option>
                {programmes.map((x) => (
                  <option value={x}>{x}</option>
                ))}
              </select>
              <small>Suggested from date of birth. Staff or parents can adjust it.</small>
            </label>
            <label class="field">
              <span>Age</span>
              <output class="calculated-value" aria-live="polite">
                {form.child_age || 'Calculated automatically from date of birth'}
              </output>
            </label>
            <Field
              label="Last school attended"
              name="last_school_attended"
              value={form.last_school_attended}
              onInput={(v) => set('last_school_attended', v)}
              span
            />
          </div>
        </section>
        <ParentSection title="Mother’s details" prefix="mother" form={form} set={set} />
        <ParentSection title="Father’s details" prefix="father" form={form} set={set} />
        <ParentSection title="Guardian’s details" prefix="guardian" form={form} set={set} />
        <section class="form-section">
          <SectionTitle n="06" title="Home address" copy="Where the family currently lives." />
          <div class="form-grid">
            <Field
              label="Residential address"
              name="residential_address"
              value={form.residential_address}
              onInput={(v) => set('residential_address', v)}
              span
            />
            <Field label="City" name="city" value={form.city} onInput={(v) => set('city', v)} />
            <Field label="State" name="state" value={form.state} onInput={(v) => set('state', v)} />
            <Field
              label="PIN code"
              name="pin_code"
              value={form.pin_code}
              onInput={(v) => set('pin_code', v)}
            />
          </div>
        </section>
        <section class="form-section">
          <SectionTitle
            n="07"
            title="How did you hear about us?"
            copy="Select all sources mentioned by the family."
          />
          <CheckGroup
            title="Referral sources"
            options={referralOptions}
            value={form.referral_sources}
            onChange={(v) => set('referral_sources', v)}
          />
        </section>
        {submitted &&
          !(
            (form.mother_name && form.mother_mobile) ||
            (form.father_name && form.father_mobile) ||
            (form.guardian_name && form.guardian_mobile)
          ) && (
            <p class="form-error" role="alert">
              Please provide a name and mobile number for at least one parent or guardian.
            </p>
          )}
        <div class="form-actions">
          <div>
            <strong>Ready to save?</strong>
            <span>
              {onStaffSubmit
                ? 'The enquiry will be saved directly and assigned to your staff account.'
                : 'The enquiry is stored offline first and synchronised securely.'}
            </span>
          </div>
          <button class="primary large" disabled={busy}>
            {busy ? 'Saving…' : onStaffSubmit ? 'Create enquiry' : 'Save enquiry'}
          </button>
        </div>
      </form>
    </div>
  );
}
function SectionTitle({ n, title, copy }: { n: string; title: string; copy: string }) {
  return (
    <div class="section-title">
      <span>{n}</span>
      <div>
        <h2>{title}</h2>
        <p>{copy}</p>
      </div>
    </div>
  );
}
function ParentSection({
  title,
  prefix,
  form,
  set,
}: {
  title: string;
  prefix: 'mother' | 'father' | 'guardian';
  form: any;
  set: (key: any, value: string) => void;
}) {
  const n = (suffix: string) => `${prefix}_${suffix}`;
  return (
    <section class="form-section">
      <SectionTitle
        n={prefix === 'mother' ? '03' : prefix === 'father' ? '04' : '05'}
        title={title}
        copy="Contact and professional information."
      />
      <div class="form-grid">
        <Field
          label="Name"
          name={n('name')}
          value={form[n('name')]}
          onInput={(v) => set(n('name'), v)}
        />
        <Field
          label="Mobile"
          name={n('mobile')}
          type="tel"
          value={form[n('mobile')]}
          onInput={(v) => set(n('mobile'), v)}
        />
        <Field
          label="Email"
          name={n('email')}
          type="email"
          value={form[n('email')]}
          onInput={(v) => set(n('email'), v)}
          span
        />
        <Field
          label="Occupation"
          name={n('occupation')}
          value={form[n('occupation')]}
          onInput={(v) => set(n('occupation'), v)}
        />
        <Field
          label="Qualification"
          name={n('qualification')}
          value={form[n('qualification')]}
          onInput={(v) => set(n('qualification'), v)}
        />
        <Field
          label="Company"
          name={n('company')}
          value={form[n('company')]}
          onInput={(v) => set(n('company'), v)}
        />
        <Field
          label="Designation"
          name={n('designation')}
          value={form[n('designation')]}
          onInput={(v) => set(n('designation'), v)}
        />
      </div>
    </section>
  );
}

function Login({ onLogin, notice }: { onLogin: () => void; notice: string }) {
  return (
    <div class="login-page">
      <div class="login-top">
        <Brand />
        <a href={mainSite}>Visit school website</a>
      </div>
      <main class="login-main">
        <div class="login-heading">
          <span class="eyebrow">STAFF ACCESS</span>
          <h1>Welcome back</h1>
          <p>Sign in with your authorised First Step Google Workspace account.</p>
        </div>
        <div class="login-card">
          <div class="login-icon">F</div>
          <h2>Admissions workspace</h2>
          <p>Enquiries, follow-ups and reception tools in one secure place.</p>
          {notice && (
            <p class="login-notice" role="alert">
              {notice}
            </p>
          )}
          <button class="google-button" onClick={onLogin}>
            <span class="google-g">G</span>
            <strong>Continue with Google</strong>
          </button>
          <div id="google-button"></div>
          <div class="secure-note">
            <span>●</span> Access is limited to approved staff accounts
          </div>
        </div>
      </main>
      <footer class="login-footer">
        <span>First Step Montessori School</span>
        <span>Private staff system</span>
      </footer>
    </div>
  );
}

function Admin({
  user,
  token,
  notice,
  setNotice,
  onSignOut,
  onReception,
  onInstall,
}: {
  user: any;
  token: string;
  notice: string;
  setNotice: (v: string) => void;
  onSignOut: () => void;
  onReception: () => void;
  onInstall: () => void;
}) {
  const [section, setSection] = useState('enquiries'),
    [menu, setMenu] = useState(false),
    [centres, setCentres] = useState<any[]>([]),
    [entries, setEntries] = useState<any[]>([]),
    [users, setUsers] = useState<any[]>([]),
    [assets, setAssets] = useState<any[]>([]),
    [devices, setDevices] = useState<any[]>([]),
    [centreFilter, setCentreFilter] = useState(''),
    [statusFilter, setStatusFilter] = useState(''),
    [search, setSearch] = useState(''),
    [enquiryPage, setEnquiryPage] = useState(1),
    [selected, setSelected] = useState<any>(null),
    [newEnquiryOpen, setNewEnquiryOpen] = useState(false),
    [confirmation, setConfirmation] = useState<any>(null),
    [userEditor, setUserEditor] = useState<any>(null),
    [assetEditor, setAssetEditor] = useState<any>(null),
    [deviceCentre, setDeviceCentre] = useState(''),
    [deviceLabel, setDeviceLabel] = useState(''),
    [deviceSetup, setDeviceSetup] = useState<any>(null),
    [importPreview, setImportPreview] = useState<{
      fileName: string;
      rows: CsvRow[];
      issues: CsvIssue[];
    } | null>(null),
    [importing, setImporting] = useState(false);
  function reload() {
    api('centres', token).then((r: any) => setCentres(r.results || []));
    api(
      'enquiries?centre=' +
        encodeURIComponent(centreFilter) +
        '&status=' +
        encodeURIComponent(statusFilter),
      token,
    )
      .then((r: any) => setEntries(r.results || []))
      .catch((e) => setNotice(e.message));
    api('users', token).then((r: any) => setUsers(r.results || []));
    api('assets', token).then((r: any) => setAssets(r.results || []));
    if (user.role === 'admin')
      api('devices', token)
        .then((r: any) => setDevices(r.results || []))
        .catch((e) => setNotice(e.message));
  }
  useEffect(reload, [centreFilter, statusFilter]);
  const shown = useMemo(
      () =>
        entries.filter((r) =>
          (
            r.child_name +
            ' ' +
            r.parent_name +
            ' ' +
            r.phone +
            ' ' +
            (r.email || '') +
            ' ' +
            (r.mother_email || '') +
            ' ' +
            (r.father_email || '') +
            ' ' +
            (r.guardian_email || '') +
            ' ' +
            (r.enquiry_number || '')
          )
            .toLowerCase()
            .includes(search.toLowerCase()),
        ),
      [entries, search],
    ),
    pageSize = pageSizes.enquiries,
    pageCount = Math.max(1, Math.ceil(shown.length / pageSize)),
    pageEntries = shown.slice((enquiryPage - 1) * pageSize, enquiryPage * pageSize);
  useEffect(() => {
    if (enquiryPage > pageCount) setEnquiryPage(pageCount);
  }, [pageCount]);
  const counts = Object.fromEntries(
    statuses.map((s) => [s, entries.filter((e) => e.status === s).length]),
  );
  async function save(row: any) {
    try {
      const normalised = normaliseEnquiry({
        ...row,
        looking_for: parseList(row.looking_for),
        referral_sources: parseList(row.referral_sources),
      });
      if (!normalised.ok) throw Error(normalised.error);
      const updated = await api('enquiries/' + row.id, token, {
        method: 'PATCH',
        body: JSON.stringify({
          ...normalised.value,
          status: row.status,
          assigned_to: row.assigned_to || null,
          notes: row.notes || '',
          office_date: row.office_date || '',
          eligible_learning_environment: row.eligible_learning_environment || '',
          attended_by: row.attended_by || '',
          office_comments: row.office_comments || '',
        }),
      });
      setNotice('Enquiry updated successfully.');
      setSelected(null);
      setEntries((current) =>
        current.map((x) => (x.id === row.id ? { ...x, ...updated.enquiry } : x)),
      );
      reload();
    } catch (e: any) {
      setNotice('Could not save the enquiry: ' + e.message);
    }
  }
  async function createEnquiry(form: any) {
    try {
      const result = await api('enquiries', token, {
        method: 'POST',
        body: JSON.stringify(form),
      });
      setNotice(`Enquiry ${result.enquiry_number} created and assigned to you.`);
      reload();
    } catch (error: any) {
      throw Error('Could not create the enquiry: ' + error.message);
    }
  }
  function remove(row: any) {
    setConfirmation({
      title: 'Delete enquiry?',
      message: `${row.enquiry_number || row.child_name} will be permanently deleted. This cannot be undone.`,
      confirmLabel: 'Delete enquiry',
      onConfirm: async () => {
        try {
          await api('enquiries/' + row.id, token, { method: 'DELETE' });
          setSelected(null);
          setNotice('Enquiry deleted.');
          reload();
        } catch (e: any) {
          setNotice('Could not delete the enquiry: ' + e.message);
        }
      },
    });
  }
  async function exportCsv() {
    const r = await fetch('/api/enquiries/export', {
        headers: { authorization: 'Bearer ' + token },
      }),
      blob = await r.blob(),
      a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = 'first-step-enquiries.csv';
    a.click();
    URL.revokeObjectURL(a.href);
  }
  async function importFile(e: Event) {
    const input = e.target as HTMLInputElement,
      file = input.files?.[0];
    if (!file) return;
    setImportPreview(null);
    try {
      if (file.size > 10 * 1024 * 1024) throw Error('Choose a CSV file smaller than 10 MB.');
      const parsed = parseCsv(await file.text());
      if (parsed.rows.length > 10000)
        throw Error('A single import can contain at most 10,000 records.');
      const issues = [
        ...parsed.issues,
        ...validateImportRows(parsed.rows, new Set(centres.map((centre) => centre.id))),
      ];
      if (!parsed.rows.length)
        issues.push({ row: 1, message: 'The file has headers but no records.' });
      setImportPreview({ fileName: file.name, rows: parsed.rows, issues });
    } catch (error: any) {
      setNotice('Could not read this CSV: ' + error.message);
    } finally {
      input.value = '';
    }
  }
  async function runImport() {
    if (!importPreview || importPreview.issues.length || !importPreview.rows.length) return;
    setImporting(true);
    try {
      let imported = 0,
        skipped = 0;
      for (let i = 0; i < importPreview.rows.length; i += 500) {
        const result = await api('import', token, {
          method: 'POST',
          body: JSON.stringify({ rows: importPreview.rows.slice(i, i + 500) }),
        });
        imported += result.imported;
        skipped += result.skipped;
      }
      setNotice(`Import complete: ${imported} imported and ${skipped} skipped as duplicates.`);
      setImportPreview(null);
      reload();
    } catch (error: any) {
      setNotice('Import stopped: ' + error.message);
    } finally {
      setImporting(false);
    }
  }
  function downloadTemplate() {
    const blob = new Blob([csvTemplate()], { type: 'text/csv;charset=utf-8' }),
      url = URL.createObjectURL(blob),
      link = document.createElement('a');
    link.href = url;
    link.download = 'first-step-import-template.csv';
    link.click();
    URL.revokeObjectURL(url);
  }
  async function createDevice() {
    try {
      const result = await api('devices', token, {
        method: 'POST',
        body: JSON.stringify({ centre_id: deviceCentre, label: deviceLabel }),
      });
      setDeviceSetup(result);
      setDeviceLabel('');
      reload();
    } catch (error: any) {
      setNotice('Could not create the device registration: ' + error.message);
    }
  }
  function revokeDevice(device: any) {
    setConfirmation({
      title: 'Deregister device?',
      message: `${device.label} will immediately stop accepting enquiries. You can create a new setup key later if needed.`,
      confirmLabel: 'Deregister device',
      onConfirm: async () => {
        try {
          await api('devices/' + device.id, token, {
            method: 'PATCH',
            body: JSON.stringify({ active: false }),
          });
          setNotice(`${device.label} has been deregistered.`);
          reload();
        } catch (error: any) {
          setNotice('Could not deregister the device: ' + error.message);
        }
      },
    });
  }
  function deleteDevice(device: any) {
    setConfirmation({
      title: 'Delete inactive device?',
      message: `${device.label} will be permanently removed from the device history.`,
      confirmLabel: 'Delete device',
      onConfirm: async () => {
        try {
          await api('devices/' + device.id, token, { method: 'DELETE' });
          setNotice(`${device.label} has been deleted.`);
          reload();
        } catch (error: any) {
          setNotice('Could not delete the device: ' + error.message);
        }
      },
    });
  }
  async function saveUser(form: any) {
    const editing = Boolean(form.originalEmail);
    try {
      await api(editing ? 'users/' + encodeURIComponent(form.originalEmail) : 'users', token, {
        method: editing ? 'PATCH' : 'POST',
        body: JSON.stringify({
          email: form.email,
          name: form.name,
          role: form.role,
          active: form.active,
        }),
      });
      setUserEditor(null);
      setNotice(editing ? 'Staff user updated.' : 'Staff user added.');
      reload();
    } catch (error: any) {
      setNotice('Could not save the staff user: ' + error.message);
    }
  }
  function deleteUser(staffUser: any) {
    setConfirmation({
      title: 'Delete staff user?',
      message: `${staffUser.name} will lose access permanently. Their assigned enquiries will become unassigned.`,
      confirmLabel: 'Delete staff user',
      onConfirm: async () => {
        try {
          await api('users/' + encodeURIComponent(staffUser.email), token, { method: 'DELETE' });
          setNotice(`${staffUser.name} has been deleted.`);
          reload();
        } catch (error: any) {
          setNotice('Could not delete the staff user: ' + error.message);
        }
      },
    });
  }
  async function saveAsset(form: any) {
    const editing = Boolean(form.id);
    try {
      await api(editing ? 'assets/' + form.id : 'assets', token, {
        method: editing ? 'PATCH' : 'POST',
        body: JSON.stringify(form),
      });
      setAssetEditor(null);
      setNotice(editing ? 'Resource updated.' : 'Resource added.');
      reload();
    } catch (error: any) {
      setNotice('Could not save the resource: ' + error.message);
    }
  }
  const nav = [
    ['enquiries', 'Enquiries'],
    ['users', 'Staff users'],
    ['assets', 'Resources'],
    ['devices', 'Reception devices'],
    ['import', 'Data import'],
  ];
  return (
    <div class="admin-shell">
      <aside class={'sidebar ' + (menu ? 'open' : '')}>
        <div class="sidebar-brand">
          <Brand />
          <button
            class="icon-button mobile-only"
            onClick={() => setMenu(false)}
            aria-label="Close menu"
          >
            <Icon name="close" />
          </button>
        </div>
        <nav>
          <span class="nav-label">WORKSPACE</span>
          {nav.map(([id, label]) => (
            <button
              class={section === id ? 'active' : ''}
              onClick={() => {
                setSection(id);
                setMenu(false);
              }}
            >
              <Icon name={id} />
              {label}
            </button>
          ))}
        </nav>
        <div class="sidebar-bottom">
          <button onClick={onReception}>
            <Icon name="home" />
            Reception form
          </button>
          <a href={mainSite}>
            <Icon name="home" />
            School website
          </a>
          <button onClick={onInstall}>
            <Icon name="import" />
            Install app
          </button>
        </div>
      </aside>
      <div class="admin-main">
        <header class="admin-header">
          <button
            class="icon-button mobile-only"
            onClick={() => setMenu(true)}
            aria-label="Open menu"
          >
            <Icon name="menu" />
          </button>
          <div>
            <span class="header-kicker">FIRST STEP</span>
            <strong>Admissions administration</strong>
          </div>
          <div class="admin-user">
            <span class="avatar">{(user.name || user.email)[0].toUpperCase()}</span>
            <div>
              <strong>{user.name}</strong>
              <small>{user.role}</small>
            </div>
            <button class="text-button" onClick={onSignOut}>
              Sign out
            </button>
          </div>
        </header>
        <main class="admin-content">
          {notice && (
            <div class="toast" role="status">
              {notice}
              <button onClick={() => setNotice('')}>×</button>
            </div>
          )}
          {section === 'enquiries' && (
            <>
              <div class="admin-title">
                <div>
                  <span class="eyebrow">ADMISSIONS PIPELINE</span>
                  <h1>Enquiries</h1>
                  <p>Review new families, assign follow-ups and track every next step.</p>
                </div>
                <div class="title-actions">
                  <button class="secondary" onClick={exportCsv}>
                    Export CSV
                  </button>
                  <button class="primary" onClick={() => setNewEnquiryOpen(true)}>
                    + New enquiry
                  </button>
                </div>
              </div>
              <div class="metric-grid">
                <Metric label="Total enquiries" value={entries.length} />
                <Metric label="New" value={counts.new || 0} />
                <Metric label="Visits planned" value={counts.visit || 0} />
                <Metric label="Admitted" value={counts.admitted || 0} />
              </div>
              <div class="table-card">
                <div class="table-tools">
                  <label class="search">
                    <span>⌕</span>
                    <input
                      value={search}
                      onInput={(e: any) => {
                        setSearch(e.currentTarget.value);
                        setEnquiryPage(1);
                      }}
                      placeholder="Search child, parent, phone or enquiry number"
                    />
                  </label>
                  <select
                    value={centreFilter}
                    onChange={(e: any) => {
                      setCentreFilter(e.currentTarget.value);
                      setEnquiryPage(1);
                    }}
                  >
                    <option value="">All centres</option>
                    {centres.map((c) => (
                      <option value={c.id}>{c.name}</option>
                    ))}
                  </select>
                  <select
                    value={statusFilter}
                    onChange={(e: any) => {
                      setStatusFilter(e.currentTarget.value);
                      setEnquiryPage(1);
                    }}
                  >
                    <option value="">All statuses</option>
                    {statuses.map((s) => (
                      <option value={s}>{statusLabel(s)}</option>
                    ))}
                  </select>
                </div>
                <div class="table-scroll">
                  <table>
                    <thead>
                      <tr>
                        <th>Enquiry</th>
                        <th>Child</th>
                        <th>Parent & contact</th>
                        <th>Programme</th>
                        <th>Status</th>
                        <th>Assigned to</th>
                        <th></th>
                      </tr>
                    </thead>
                    <tbody>
                      {pageEntries.map((row) => (
                        <tr>
                          <td>
                            <strong>{row.enquiry_number || 'Pending number'}</strong>
                            <small>{formatDate(row.submitted_at)}</small>
                          </td>
                          <td>
                            <strong>{row.child_name}</strong>
                            <small>{row.child_age || row.child_dob || 'Age not entered'}</small>
                          </td>
                          <td>
                            <strong>{row.parent_name}</strong>
                            <small>{row.phone}</small>
                          </td>
                          <td>{row.programme || '—'}</td>
                          <td>
                            <span class={'status ' + row.status}>{statusLabel(row.status)}</span>
                          </td>
                          <td>{row.assigned_to || 'Unassigned'}</td>
                          <td class="table-row-actions">
                            <button
                              class="icon-action edit-icon"
                              onClick={() => setSelected({ ...row })}
                              aria-label={`Edit enquiry ${row.enquiry_number || row.child_name}`}
                              title="Edit enquiry"
                            >
                              <ActionIcon name="edit" />
                            </button>
                            {user.role === 'admin' && (
                              <button
                                class="icon-action danger-icon"
                                onClick={() => remove(row)}
                                aria-label={`Delete enquiry ${row.enquiry_number || row.child_name}`}
                                title="Delete enquiry"
                              >
                                <ActionIcon name="delete" />
                              </button>
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                  {!shown.length && <div class="empty">No enquiries match these filters.</div>}
                </div>
                {shown.length > 0 && (
                  <Pagination
                    page={enquiryPage}
                    pages={pageCount}
                    total={shown.length}
                    label="enquiries"
                    onPage={setEnquiryPage}
                  />
                )}
              </div>
            </>
          )}
          {section === 'users' && (
            <AdminUsers
              user={user}
              users={users}
              add={() => setUserEditor({ email: '', name: '', role: 'staff', active: true })}
              edit={(staffUser: any) =>
                setUserEditor({ ...staffUser, originalEmail: staffUser.email })
              }
              remove={deleteUser}
            />
          )}
          {section === 'assets' && (
            <AdminAssets
              user={user}
              assets={assets}
              add={() => setAssetEditor({ title: '', url: '', kind: 'link', active: true })}
              edit={(asset: any) => setAssetEditor({ ...asset, active: Boolean(asset.active) })}
            />
          )}
          {section === 'devices' && (
            <AdminDevices
              user={user}
              centres={centres}
              devices={devices}
              centre={deviceCentre}
              setCentre={setDeviceCentre}
              label={deviceLabel}
              setLabel={setDeviceLabel}
              setup={deviceSetup}
              clearSetup={() => setDeviceSetup(null)}
              create={createDevice}
              revoke={revokeDevice}
              remove={deleteDevice}
            />
          )}
          {section === 'import' && (
            <SimplePage
              eyebrow="DATA TOOLS"
              title="Historical import"
              copy="Validate and preview older enquiries before adding them in controlled batches."
            >
              <div class="settings-card import-card">
                <div class="import-heading">
                  <div>
                    <h2>Upload CSV</h2>
                    <p class="help">
                      CSV files exported by Excel and Google Sheets are supported, including quoted
                      commas and line breaks.
                    </p>
                  </div>
                  <button class="secondary" type="button" onClick={downloadTemplate}>
                    Download template
                  </button>
                </div>
                <label class="file-picker">
                  Choose CSV file
                  <input
                    type="file"
                    accept=".csv,text/csv"
                    onChange={importFile}
                    disabled={user.role !== 'admin' || importing}
                  />
                </label>
                {user.role !== 'admin' && (
                  <p class="import-error">Only administrators can import records.</p>
                )}
                {importPreview && (
                  <ImportPreview
                    preview={importPreview}
                    importing={importing}
                    onCancel={() => setImportPreview(null)}
                    onImport={runImport}
                  />
                )}
              </div>
            </SimplePage>
          )}
        </main>
      </div>
      {selected && (
        <EnquiryDialog
          row={selected}
          setRow={setSelected}
          users={users}
          onClose={() => setSelected(null)}
          onSave={() => save(selected)}
        />
      )}{' '}
      {newEnquiryOpen && (
        <StaffEnquiryDialog
          centres={centres}
          onSave={createEnquiry}
          onClose={() => setNewEnquiryOpen(false)}
        />
      )}
      {confirmation && <ConfirmDialog {...confirmation} onClose={() => setConfirmation(null)} />}
      {userEditor && (
        <StaffUserDialog
          value={userEditor}
          currentUserEmail={user.email}
          onChange={setUserEditor}
          onSave={saveUser}
          onClose={() => setUserEditor(null)}
        />
      )}
      {assetEditor && (
        <ResourceDialog
          value={assetEditor}
          onChange={setAssetEditor}
          onSave={saveAsset}
          onClose={() => setAssetEditor(null)}
        />
      )}
    </div>
  );
}

function DeviceActivation({
  onRegistered,
  onSaved,
}: {
  onRegistered: (token: string, centre: string) => void;
  onSaved: (message: string) => void;
}) {
  const [key, setKey] = useState(''),
    [busy, setBusy] = useState(false);
  async function activate(e: Event) {
    e.preventDefault();
    setBusy(true);
    try {
      const response = await fetch('/api/devices/claim', {
          method: 'POST',
          headers: { 'content-type': 'application/json' },
          body: JSON.stringify({ key }),
        }),
        result = await response.json();
      if (!response.ok) throw Error(result.error || 'Could not register this device');
      onRegistered(result.token, result.centre_id);
      onSaved(`${result.label} is now registered for reception use.`);
    } catch (error: any) {
      onSaved(error.message);
    } finally {
      setBusy(false);
    }
  }
  return (
    <div class="device-activation">
      <div class="activation-card">
        <span class="activation-icon">▣</span>
        <span class="eyebrow">DEVICE SETUP</span>
        <h1>Register this reception device</h1>
        <p>
          An administrator can create a one-time setup key from the Reception devices area. No
          administrator sign-in is required on this tablet.
        </p>
        <form onSubmit={activate}>
          <label>
            Setup key
            <input
              value={key}
              onInput={(e: any) => setKey(e.currentTarget.value.toUpperCase())}
              placeholder="XXXXX-XXXXX-XXXXX-XXXXX"
              autoCapitalize="characters"
              autoComplete="off"
              required
            />
          </label>
          <button
            class="primary large"
            disabled={busy || key.replace(/[^A-Z0-9]/gi, '').length !== 20}
          >
            {busy ? 'Registering…' : 'Register device'}
          </button>
        </form>
      </div>
    </div>
  );
}

function AdminDevices({
  user,
  centres,
  devices,
  centre,
  setCentre,
  label,
  setLabel,
  setup,
  clearSetup,
  create,
  revoke,
  remove,
}: any) {
  const [page, setPage] = useState(1),
    size = pageSizes.devices,
    pages = Math.max(1, Math.ceil(devices.length / size)),
    shown = devices.slice((page - 1) * size, page * size);
  useEffect(() => {
    if (page > pages) setPage(pages);
  }, [pages]);
  return (
    <SimplePage
      eyebrow="SECURE RECEPTION"
      title="Reception devices"
      copy="Provision and remotely manage every browser allowed to collect reception enquiries."
    >
      {user.role !== 'admin' ? (
        <div class="settings-card">
          <p>Only administrators can manage reception devices.</p>
        </div>
      ) : (
        <>
          <div class="settings-card device-create">
            <h2>Create a device setup key</h2>
            <p class="help">
              Name the tablet so it can be identified later. The one-time key expires after 24
              hours.
            </p>
            <div class="device-form">
              <label>
                Device name
                <input
                  value={label}
                  onInput={(e: any) => setLabel(e.currentTarget.value)}
                  placeholder="e.g. Sector 7 front desk tablet"
                />
              </label>
              <label>
                Assigned centre
                <select value={centre} onChange={(e: any) => setCentre(e.currentTarget.value)}>
                  <option value="">Select a centre</option>
                  {centres.map((item: any) => (
                    <option value={item.id}>{item.name}</option>
                  ))}
                </select>
              </label>
              <button class="primary" disabled={!centre || !label.trim()} onClick={create}>
                Create setup key
              </button>
            </div>
            {setup && (
              <div class="setup-key" role="status">
                <div>
                  <span>
                    One-time setup key for <strong>{setup.label}</strong>
                  </span>
                  <code>{setup.setup_key}</code>
                  <small>
                    Expires {formatDateTime(setup.expires_at)}. This key is shown only once.
                  </small>
                </div>
                <div>
                  <button
                    class="secondary"
                    onClick={() => navigator.clipboard.writeText(setup.setup_key)}
                  >
                    Copy key
                  </button>
                  <button class="text-button" onClick={clearSetup}>
                    Done
                  </button>
                </div>
              </div>
            )}
          </div>
          <div class="table-card device-list">
            <div class="device-list-head">
              <div>
                <h2>Registered devices</h2>
                <p>
                  {devices.length} {devices.length === 1 ? 'device' : 'devices'} across all centres
                </p>
              </div>
            </div>
            <div class="table-scroll">
              <table>
                <thead>
                  <tr>
                    <th>Device</th>
                    <th>Centre</th>
                    <th>Status</th>
                    <th>Registered</th>
                    <th>Last active</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  {shown.map((device: any) => (
                    <tr>
                      <td>
                        <strong>{device.label}</strong>
                        <small>{device.id.slice(0, 8)}</small>
                      </td>
                      <td>{device.centre_name}</td>
                      <td>
                        <span
                          class={
                            'status ' +
                            (device.status === 'active'
                              ? 'admitted'
                              : device.status === 'pending'
                                ? 'new'
                                : 'closed')
                          }
                        >
                          {device.status}
                        </span>
                      </td>
                      <td>{formatDateTime(device.registered_at)}</td>
                      <td>{formatDateTime(device.last_seen_at)}</td>
                      <td>
                        <div class="device-actions">
                          {device.status !== 'inactive' ? (
                            <button
                              class="icon-action deactivate-icon"
                              onClick={() => revoke(device)}
                              aria-label={`Deregister ${device.label}`}
                              title="Deregister device"
                            >
                              <ActionIcon name="deactivate" />
                            </button>
                          ) : (
                            <button
                              class="icon-action danger-icon"
                              onClick={() => remove(device)}
                              aria-label={`Delete ${device.label}`}
                              title="Delete device"
                            >
                              <ActionIcon name="delete" />
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {!devices.length && <div class="empty">No reception devices have been created.</div>}
            </div>
            {devices.length > 0 && (
              <Pagination
                page={page}
                pages={pages}
                total={devices.length}
                label="devices"
                onPage={setPage}
              />
            )}
          </div>
        </>
      )}
    </SimplePage>
  );
}

function ConfirmDialog({
  title,
  message,
  confirmLabel,
  onConfirm,
  onClose,
}: {
  title: string;
  message: string;
  confirmLabel: string;
  onConfirm: () => Promise<void> | void;
  onClose: () => void;
}) {
  const [busy, setBusy] = useState(false);
  useEffect(() => {
    const close = (event: KeyboardEvent) => {
      if (event.key === 'Escape' && !busy) onClose();
    };
    window.addEventListener('keydown', close);
    return () => window.removeEventListener('keydown', close);
  }, [busy]);
  async function accept() {
    setBusy(true);
    try {
      await onConfirm();
      onClose();
    } finally {
      setBusy(false);
    }
  }
  return (
    <div
      class="confirm-backdrop"
      role="presentation"
      onMouseDown={(e: any) => e.target === e.currentTarget && !busy && onClose()}
    >
      <section
        class="confirm-dialog"
        role="alertdialog"
        aria-modal="true"
        aria-labelledby="confirm-title"
        aria-describedby="confirm-message"
      >
        <span class="confirm-icon" aria-hidden="true">
          !
        </span>
        <h2 id="confirm-title">{title}</h2>
        <p id="confirm-message">{message}</p>
        <div>
          <button class="secondary" onClick={onClose} disabled={busy} autoFocus>
            Cancel
          </button>
          <button class="danger" onClick={accept} disabled={busy}>
            {busy ? 'Working…' : confirmLabel}
          </button>
        </div>
      </section>
    </div>
  );
}

function ImportPreview({
  preview,
  importing,
  onCancel,
  onImport,
}: {
  preview: { fileName: string; rows: CsvRow[]; issues: CsvIssue[] };
  importing: boolean;
  onCancel: () => void;
  onImport: () => void;
}) {
  const ready = preview.rows.length > 0 && !preview.issues.length;
  return (
    <section class="import-preview" aria-live="polite">
      <div class="import-summary">
        <div>
          <strong>{preview.fileName}</strong>
          <span>
            {preview.rows.length} {preview.rows.length === 1 ? 'record' : 'records'} found
          </span>
        </div>
        <span class={'status ' + (ready ? 'admitted' : 'closed')}>
          {ready
            ? 'Ready to import'
            : `${preview.issues.length} ${preview.issues.length === 1 ? 'issue' : 'issues'}`}
        </span>
      </div>
      {preview.issues.length > 0 && (
        <div class="issue-list" role="alert">
          <strong>Fix these issues and upload the file again:</strong>
          <ul>
            {preview.issues.slice(0, 12).map((issue) => (
              <li>
                Row {issue.row}: {issue.message}
              </li>
            ))}
          </ul>
          {preview.issues.length > 12 && <p>And {preview.issues.length - 12} more issues.</p>}
        </div>
      )}
      {ready && (
        <div class="import-table">
          <table>
            <thead>
              <tr>
                <th>Row</th>
                <th>Child</th>
                <th>Parent</th>
                <th>Phone</th>
                <th>Centre</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {preview.rows.slice(0, 8).map((row, index) => (
                <tr>
                  <td>{index + 2}</td>
                  <td>{row.child_name}</td>
                  <td>
                    {row.parent_name || row.mother_name || row.father_name || row.guardian_name}
                  </td>
                  <td>
                    {row.phone || row.mother_mobile || row.father_mobile || row.guardian_mobile}
                  </td>
                  <td>{row.centre_id}</td>
                  <td>{row.status || 'new'}</td>
                </tr>
              ))}
            </tbody>
          </table>
          {preview.rows.length > 8 && (
            <p class="preview-more">Previewing 8 of {preview.rows.length} records.</p>
          )}
        </div>
      )}
      <div class="import-actions">
        <button class="secondary" type="button" onClick={onCancel} disabled={importing}>
          Cancel
        </button>
        <button class="primary" type="button" onClick={onImport} disabled={!ready || importing}>
          {importing ? 'Importing…' : `Import ${preview.rows.length} records`}
        </button>
      </div>
    </section>
  );
}

function Metric({ label, value }: { label: string; value: number }) {
  return (
    <div class="metric">
      <span>{label}</span>
      <strong>{value}</strong>
    </div>
  );
}
function Pagination({
  page,
  pages,
  total,
  label,
  onPage,
}: {
  page: number;
  pages: number;
  total: number;
  label: string;
  onPage: (page: number) => void;
}) {
  return (
    <div class="pagination">
      <span>
        {total} {label}
      </span>
      <div>
        <button class="secondary" disabled={page === 1} onClick={() => onPage(page - 1)}>
          Previous
        </button>
        <span>
          Page {page} of {pages}
        </span>
        <button class="secondary" disabled={page === pages} onClick={() => onPage(page + 1)}>
          Next
        </button>
      </div>
    </div>
  );
}
function statusLabel(s: string) {
  return (
    (
      {
        new: 'New',
        contacted: 'Contacted',
        visit: 'Visit planned',
        application: 'Application',
        admitted: 'Admitted',
        closed: 'Closed',
      } as any
    )[s] || s
  );
}
function formatDate(value: string) {
  if (!value) return '—';
  return new Intl.DateTimeFormat('en-IN', { dateStyle: 'medium' }).format(new Date(value + 'Z'));
}
function formatDateTime(value: string) {
  if (!value) return '—';
  const date = new Date(value.includes('T') ? value : value.replace(' ', 'T') + 'Z');
  return Number.isNaN(date.valueOf())
    ? '—'
    : new Intl.DateTimeFormat('en-IN', { dateStyle: 'medium', timeStyle: 'short' }).format(date);
}
function SimplePage({
  eyebrow,
  title,
  copy,
  children,
}: {
  eyebrow: string;
  title: string;
  copy: string;
  children: any;
}) {
  return (
    <>
      <div class="admin-title">
        <div>
          <span class="eyebrow">{eyebrow}</span>
          <h1>{title}</h1>
          <p>{copy}</p>
        </div>
      </div>
      {children}
    </>
  );
}
function AdminUsers({ user, users, add, edit, remove }: any) {
  const [page, setPage] = useState(1),
    size = pageSizes.staffUsers,
    pages = Math.max(1, Math.ceil(users.length / size)),
    shown = users.slice((page - 1) * size, page * size);
  useEffect(() => {
    if (page > pages) setPage(pages);
  }, [pages]);
  return (
    <SimplePage
      eyebrow="ACCESS CONTROL"
      title="Staff users"
      copy="Manage the people who can access admissions records."
    >
      <div class="settings-card management-card">
        <div class="management-head">
          <div>
            <h2>Authorised staff</h2>
            <p>{users.length} staff accounts</p>
          </div>
          {user.role === 'admin' && (
            <button class="primary" onClick={add}>
              + Add staff user
            </button>
          )}
        </div>
        <div class="user-list">
          {shown.map((x: any) => (
            <div>
              <span class="avatar">{x.name[0]}</span>
              <p>
                <strong>{x.name}</strong>
                <small>{x.email}</small>
              </p>
              <span class={'status ' + (x.active ? 'admitted' : 'closed')}>
                {x.active ? 'Active' : 'Disabled'}
              </span>
              <b>{x.role}</b>
              {user.role === 'admin' && (
                <div class="management-actions">
                  <button
                    class="icon-action edit-icon"
                    onClick={() => edit(x)}
                    aria-label={`Edit ${x.name}`}
                    title="Edit staff user"
                  >
                    <ActionIcon name="edit" />
                  </button>
                  {x.email !== user.email && (
                    <button
                      class="icon-action danger-icon"
                      onClick={() => remove(x)}
                      aria-label={`Delete ${x.name}`}
                      title="Delete staff user"
                    >
                      <ActionIcon name="delete" />
                    </button>
                  )}
                </div>
              )}
            </div>
          ))}
        </div>
        {users.length > 0 && (
          <Pagination
            page={page}
            pages={pages}
            total={users.length}
            label="staff users"
            onPage={setPage}
          />
        )}
      </div>
    </SimplePage>
  );
}
function AdminAssets({ user, assets, add, edit }: any) {
  return (
    <SimplePage
      eyebrow="TEAM LIBRARY"
      title="Resources"
      copy="Keep useful school links and admission documents together."
    >
      <div class="settings-card management-card">
        <div class="management-head">
          <div>
            <h2>Shared resources</h2>
            <p>{assets.length} saved resources</p>
          </div>
          {user.role === 'admin' && (
            <button class="primary" onClick={add}>
              + Add resource
            </button>
          )}
        </div>
        <div class="resource-list">
          {assets.map((x: any) => (
            <div>
              <span>◇</span>
              <p>
                <strong>{x.title}</strong>
                <small>
                  {x.kind} · {x.active ? 'Active' : 'Inactive'}
                </small>
              </p>
              <a
                class="icon-action open-icon"
                href={x.url}
                target="_blank"
                rel="noreferrer"
                aria-label={`Open ${x.title}`}
                title="Open resource"
              >
                <ActionIcon name="open" />
              </a>
              {user.role === 'admin' && (
                <button
                  class="icon-action edit-icon"
                  onClick={() => edit(x)}
                  aria-label={`Edit ${x.title}`}
                  title="Edit resource"
                >
                  <ActionIcon name="edit" />
                </button>
              )}
            </div>
          ))}
        </div>
      </div>
    </SimplePage>
  );
}

function FormDialog({ title, copy, submitLabel, onSubmit, onClose, children }: any) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  useEffect(() => {
    const close = (event: KeyboardEvent) => {
      if (event.key === 'Escape' && !busy) onClose();
    };
    window.addEventListener('keydown', close);
    return () => window.removeEventListener('keydown', close);
  }, [busy]);
  async function submit(event: Event) {
    event.preventDefault();
    setBusy(true);
    setError('');
    try {
      await onSubmit();
    } catch (submitError: any) {
      setError(submitError.message || 'Could not save your changes.');
    } finally {
      setBusy(false);
    }
  }
  return (
    <div
      class="form-dialog-backdrop"
      role="presentation"
      onMouseDown={(event: any) => event.target === event.currentTarget && !busy && onClose()}
    >
      <section class="form-dialog" role="dialog" aria-modal="true" aria-labelledby="form-title">
        <div class="form-dialog-head">
          <div>
            <h2 id="form-title">{title}</h2>
            <p>{copy}</p>
          </div>
          <button class="icon-button" type="button" onClick={onClose} disabled={busy}>
            ×
          </button>
        </div>
        <form onSubmit={submit}>
          <div class="form-dialog-fields">{children}</div>
          {error && (
            <p class="form-dialog-error" role="alert">
              {error}
            </p>
          )}
          <div class="form-dialog-actions">
            <button class="secondary" type="button" onClick={onClose} disabled={busy}>
              Cancel
            </button>
            <button class="primary" disabled={busy}>
              {busy ? 'Saving…' : submitLabel}
            </button>
          </div>
        </form>
      </section>
    </div>
  );
}

function StaffUserDialog({ value, currentUserEmail, onChange, onSave, onClose }: any) {
  const editing = Boolean(value.originalEmail);
  const editingSelf = value.email === currentUserEmail;
  return (
    <FormDialog
      title={editing ? 'Edit staff user' : 'Add staff user'}
      copy="Manage sign-in access and the staff member's role."
      submitLabel={editing ? 'Save changes' : 'Add staff user'}
      onSubmit={() => onSave(value)}
      onClose={onClose}
    >
      <label>
        Name
        <input
          required
          autoFocus
          value={value.name}
          onInput={(event: any) => onChange({ ...value, name: event.currentTarget.value })}
        />
      </label>
      <label>
        School email
        <input
          required
          type="email"
          value={value.email}
          disabled={editing}
          onInput={(event: any) => onChange({ ...value, email: event.currentTarget.value })}
        />
        {editing && <small>Email addresses are fixed after an account is created.</small>}
      </label>
      <label>
        Role
        <select
          value={value.role}
          disabled={editingSelf}
          onChange={(event: any) => onChange({ ...value, role: event.currentTarget.value })}
        >
          <option value="staff">Staff</option>
          <option value="admin">Administrator</option>
        </select>
      </label>
      {editing && (
        <label class="toggle-field">
          <input
            type="checkbox"
            checked={Boolean(value.active)}
            disabled={editingSelf}
            onChange={(event: any) => onChange({ ...value, active: event.currentTarget.checked })}
          />
          <span>Account is active</span>
        </label>
      )}
    </FormDialog>
  );
}

function ResourceDialog({ value, onChange, onSave, onClose }: any) {
  const editing = Boolean(value.id);
  return (
    <FormDialog
      title={editing ? 'Edit resource' : 'Add resource'}
      copy="Keep a useful school link available to the admissions team."
      submitLabel={editing ? 'Save changes' : 'Add resource'}
      onSubmit={() => onSave(value)}
      onClose={onClose}
    >
      <label>
        Title
        <input
          required
          autoFocus
          value={value.title}
          onInput={(event: any) => onChange({ ...value, title: event.currentTarget.value })}
        />
      </label>
      <label>
        HTTPS URL
        <input
          required
          type="url"
          value={value.url}
          onInput={(event: any) => onChange({ ...value, url: event.currentTarget.value })}
        />
      </label>
      <label>
        Type
        <input
          value={value.kind}
          placeholder="e.g. policy"
          onInput={(event: any) => onChange({ ...value, kind: event.currentTarget.value })}
        />
      </label>
      {editing && (
        <label class="toggle-field">
          <input
            type="checkbox"
            checked={Boolean(value.active)}
            onChange={(event: any) => onChange({ ...value, active: event.currentTarget.checked })}
          />
          <span>Resource is active</span>
        </label>
      )}
    </FormDialog>
  );
}

function StaffEnquiryDialog({ centres, onSave, onClose }: any) {
  const [centre, setCentre] = useState('');
  const [message, setMessage] = useState('');
  useEffect(() => {
    const close = (event: KeyboardEvent) => {
      if (event.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', close);
    return () => window.removeEventListener('keydown', close);
  }, []);
  return (
    <div
      class="staff-enquiry-dialog-backdrop"
      role="presentation"
      onMouseDown={(event: any) => event.target === event.currentTarget && onClose()}
    >
      <section
        class="staff-enquiry-dialog"
        role="dialog"
        aria-modal="true"
        aria-labelledby="staff-enquiry-title"
      >
        <div class="staff-enquiry-dialog-head">
          <div>
            <span class="eyebrow">STAFF-ASSISTED ENQUIRY</span>
            <h2 id="staff-enquiry-title">New enquiry</h2>
            <p>The fields below are identical to the parent reception form.</p>
          </div>
          <button class="icon-button" onClick={onClose} aria-label="Close new enquiry form">
            ×
          </button>
        </div>
        <div class="staff-enquiry-centre">
          <label>
            Centre handling this enquiry
            <select
              autoFocus
              value={centre}
              onChange={(event: any) => setCentre(event.currentTarget.value)}
            >
              <option value="">Select a centre</option>
              {centres.map((item: any) => (
                <option value={item.id}>{item.name}</option>
              ))}
            </select>
          </label>
        </div>
        {message && (
          <p class="staff-enquiry-error" role="alert">
            {message}
          </p>
        )}
        <div class="staff-enquiry-dialog-body">
          <ReceptionForm
            embedded
            staffCentre={centre}
            onStaffSubmit={onSave}
            onStaffComplete={onClose}
            onSaved={setMessage}
          />
        </div>
      </section>
    </div>
  );
}

function EnquiryDialog({ row, setRow, users, onClose, onSave }: any) {
  const set = (key: string, value: any) => setRow({ ...row, [key]: value });
  const calculatedAge = ageDetails(row.child_dob || '').label;
  useEffect(() => {
    const close = (event: KeyboardEvent) => {
      if (event.key === 'Escape' && !document.querySelector('.confirm-backdrop')) onClose();
    };
    window.addEventListener('keydown', close);
    return () => window.removeEventListener('keydown', close);
  }, []);
  return (
    <div
      class="enquiry-dialog-backdrop"
      role="presentation"
      onMouseDown={(e: any) => e.target === e.currentTarget && onClose()}
    >
      <section
        class="enquiry-dialog"
        role="dialog"
        aria-modal="true"
        aria-labelledby="enquiry-dialog-title"
      >
        <div class="enquiry-dialog-head">
          <div>
            <span class="eyebrow">EDIT ENQUIRY · {row.enquiry_number || 'UNNUMBERED'}</span>
            <h2 id="enquiry-dialog-title">{row.child_name}</h2>
            <p>{row.programme}</p>
          </div>
          <button class="icon-button" onClick={onClose} aria-label="Close enquiry editor">
            ×
          </button>
        </div>
        <form
          class="enquiry-dialog-body"
          onSubmit={(event) => {
            event.preventDefault();
            onSave();
          }}
        >
          <section class="dialog-edit-section">
            <h3>Services of interest</h3>
            <CheckGroup
              title="Select all that apply"
              options={lookingOptions}
              value={parseList(row.looking_for)}
              onChange={(value) => set('looking_for', value)}
            />
          </section>
          <section class="dialog-edit-section">
            <h3>Child details</h3>
            <div class="form-grid">
              <Field
                label="Name of the child"
                name="edit_child_name"
                value={row.child_name || ''}
                required
                onInput={(value) => set('child_name', value)}
              />
              <Field
                label="Date of birth"
                name="edit_child_dob"
                type="date"
                value={row.child_dob || ''}
                required
                onInput={(value) => set('child_dob', value)}
              />
              <label class="field">
                <span>Gender</span>
                <select
                  value={row.child_gender || ''}
                  onChange={(event: any) => set('child_gender', event.currentTarget.value)}
                >
                  <option value="">Select</option>
                  {genders.map((gender) => (
                    <option value={gender}>{gender}</option>
                  ))}
                </select>
              </label>
              <label class="field">
                <span>
                  Programme of interest <b>*</b>
                </span>
                <select
                  value={row.programme || ''}
                  required
                  onChange={(event: any) => set('programme', event.currentTarget.value)}
                >
                  <option value="">Select a programme</option>
                  {programmes.map((programme) => (
                    <option value={programme}>{programme}</option>
                  ))}
                </select>
              </label>
              <label class="field">
                <span>Age</span>
                <output class="calculated-value">
                  {calculatedAge || 'Calculated automatically from date of birth'}
                </output>
              </label>
              <Field
                label="Last school attended"
                name="edit_last_school_attended"
                value={row.last_school_attended || ''}
                onInput={(value) => set('last_school_attended', value)}
              />
            </div>
          </section>
          <EditableParentSection title="Mother’s details" prefix="mother" row={row} set={set} />
          <EditableParentSection title="Father’s details" prefix="father" row={row} set={set} />
          <EditableParentSection title="Guardian’s details" prefix="guardian" row={row} set={set} />
          <section class="dialog-edit-section">
            <h3>Home address</h3>
            <div class="form-grid">
              <Field
                label="Residential address"
                name="edit_residential_address"
                value={row.residential_address || ''}
                onInput={(value) => set('residential_address', value)}
                span
              />
              <Field
                label="City"
                name="edit_city"
                value={row.city || ''}
                onInput={(value) => set('city', value)}
              />
              <Field
                label="State"
                name="edit_state"
                value={row.state || ''}
                onInput={(value) => set('state', value)}
              />
              <Field
                label="PIN code"
                name="edit_pin_code"
                value={row.pin_code || ''}
                onInput={(value) => set('pin_code', value)}
              />
            </div>
          </section>
          <section class="dialog-edit-section">
            <h3>How did you hear about us?</h3>
            <CheckGroup
              title="Select all that apply"
              options={referralOptions}
              value={parseList(row.referral_sources)}
              onChange={(value) => set('referral_sources', value)}
            />
          </section>
          <section class="office-fields">
            <h3>Office use</h3>
            <label>
              Status
              <select
                value={row.status}
                onChange={(e: any) => set('status', e.currentTarget.value)}
              >
                {statuses.map((s) => (
                  <option value={s}>{statusLabel(s)}</option>
                ))}
              </select>
            </label>
            <label>
              Assigned to
              <select
                value={row.assigned_to || ''}
                onChange={(e: any) => set('assigned_to', e.currentTarget.value)}
              >
                <option value="">Unassigned</option>
                {users
                  .filter((x: any) => x.active)
                  .map((x: any) => (
                    <option value={x.email}>{x.name}</option>
                  ))}
              </select>
            </label>
            <label>
              Date
              <input
                type="date"
                value={row.office_date || ''}
                onInput={(e: any) => set('office_date', e.currentTarget.value)}
              />
            </label>
            <label>
              Eligible learning environment
              <input
                value={row.eligible_learning_environment || ''}
                onInput={(e: any) => set('eligible_learning_environment', e.currentTarget.value)}
              />
            </label>
            <label>
              Attended by
              <input
                value={row.attended_by || ''}
                onInput={(e: any) => set('attended_by', e.currentTarget.value)}
              />
            </label>
            <label>
              Follow-up notes
              <textarea
                rows={3}
                value={row.notes || ''}
                onInput={(e: any) => set('notes', e.currentTarget.value)}
              />
            </label>
            <label>
              Other comments
              <textarea
                rows={3}
                value={row.office_comments || ''}
                onInput={(e: any) => set('office_comments', e.currentTarget.value)}
              />
            </label>
          </section>
          <div class="enquiry-dialog-actions">
            <button class="secondary" type="button" onClick={onClose}>
              Cancel
            </button>
            <button class="primary" type="submit">
              Save changes
            </button>
          </div>
        </form>
      </section>
    </div>
  );
}
function EditableParentSection({ title, prefix, row, set }: any) {
  const key = (suffix: string) => `${prefix}_${suffix}`;
  return (
    <section class="dialog-edit-section">
      <h3>{title}</h3>
      <div class="form-grid">
        <Field
          label="Name"
          name={`edit_${key('name')}`}
          value={row[key('name')] || ''}
          onInput={(value) => set(key('name'), value)}
        />
        <Field
          label="Mobile"
          name={`edit_${key('mobile')}`}
          type="tel"
          value={row[key('mobile')] || ''}
          onInput={(value) => set(key('mobile'), value)}
        />
        <Field
          label="Email"
          name={`edit_${key('email')}`}
          type="email"
          value={row[key('email')] || ''}
          onInput={(value) => set(key('email'), value)}
          span
        />
        <Field
          label="Occupation"
          name={`edit_${key('occupation')}`}
          value={row[key('occupation')] || ''}
          onInput={(value) => set(key('occupation'), value)}
        />
        <Field
          label="Qualification"
          name={`edit_${key('qualification')}`}
          value={row[key('qualification')] || ''}
          onInput={(value) => set(key('qualification'), value)}
        />
        <Field
          label="Company"
          name={`edit_${key('company')}`}
          value={row[key('company')] || ''}
          onInput={(value) => set(key('company'), value)}
        />
        <Field
          label="Designation"
          name={`edit_${key('designation')}`}
          value={row[key('designation')] || ''}
          onInput={(value) => set(key('designation'), value)}
        />
      </div>
    </section>
  );
}
function parseList(value: any) {
  try {
    return Array.isArray(value) ? value : JSON.parse(value || '[]');
  } catch {
    return [];
  }
}

function App() {
  const initialView =
    new URLSearchParams(location.search).get('view') === 'admin' ? 'admin' : 'form';
  const [view, setView] = useState<'form' | 'admin'>(initialView),
    [token, setToken] = useState(sessionStorage.getItem('staff-token') || ''),
    [user, setUser] = useState<any>(null),
    [notice, setNotice] = useState(''),
    [pending, setPending] = useState(0),
    [device, setDevice] = useState(localStorage.getItem('first-step-device') || ''),
    [installPrompt, setInstallPrompt] = useState<any>(null);
  useEffect(() => {
    navigator.serviceWorker?.register('/sw.js');
    pendingCount().then(setPending);
    const script = document.createElement('script');
    script.src = 'https://accounts.google.com/gsi/client';
    script.async = true;
    document.head.append(script);
    const install = (e: any) => {
      e.preventDefault();
      setInstallPrompt(e);
    };
    window.addEventListener('beforeinstallprompt', install);
    return () => {
      script.remove();
      window.removeEventListener('beforeinstallprompt', install);
    };
  }, []);
  useEffect(() => {
    if (!token) {
      setUser(null);
      return;
    }
    api('me', token)
      .then(setUser)
      .catch(() => {
        setToken('');
        sessionStorage.removeItem('staff-token');
      });
  }, [token]);
  useEffect(() => {
    if (!device) return;
    const verify = async () => {
      if (!navigator.onLine) return;
      const response = await fetch('/api/devices/current', {
        headers: { 'x-device-token': device },
      });
      if (response.ok) {
        const current = await response.json();
        localStorage.setItem('first-step-device-centre', current.centre_id);
        await sync(device, () => pendingCount().then(setPending));
      } else if (response.status === 403) {
        localStorage.removeItem('first-step-device');
        setDevice('');
        setNotice('This device was deregistered. Enter a new setup key to use reception mode.');
      }
    };
    verify();
    const timer = window.setInterval(verify, 5 * 60 * 1000);
    window.addEventListener('online', verify);
    window.addEventListener('focus', verify);
    return () => {
      window.clearInterval(timer);
      window.removeEventListener('online', verify);
      window.removeEventListener('focus', verify);
    };
  }, [device]);
  useEffect(() => {
    if (view !== 'admin' || !user) return;
    const timeout = device ? staffSessionTimeoutMs.sharedDevice : staffSessionTimeoutMs.standard;
    let timer = window.setTimeout(lock, timeout);
    function lock() {
      sessionStorage.removeItem('staff-token');
      setToken('');
      setUser(null);
      setNotice('Staff session locked after inactivity. Sign in again to continue.');
    }
    function reset() {
      window.clearTimeout(timer);
      timer = window.setTimeout(lock, timeout);
    }
    const events = ['pointerdown', 'keydown', 'touchstart'] as const;
    events.forEach((event) => window.addEventListener(event, reset));
    return () => {
      window.clearTimeout(timer);
      events.forEach((event) => window.removeEventListener(event, reset));
    };
  }, [view, user, device]);
  function clearStaffSession() {
    sessionStorage.removeItem('staff-token');
    setToken('');
    setUser(null);
    (window as any).google?.accounts.id.disableAutoSelect?.();
  }
  function openStaffAccess() {
    clearStaffSession();
    setNotice('');
    setView('admin');
  }
  function returnToReception() {
    clearStaffSession();
    setNotice('');
    setView('form');
  }
  function login() {
    if (!clientId) {
      setNotice('Google sign-in is not configured. Add VITE_GOOGLE_CLIENT_ID to .env.local.');
      return;
    }
    if (!(window as any).google) {
      setNotice('Google sign-in is still loading. Please try again.');
      return;
    }
    (window as any).google.accounts.id.initialize({
      client_id: clientId,
      callback: (r: any) => {
        sessionStorage.setItem('staff-token', r.credential);
        setToken(r.credential);
      },
    });
    (window as any).google.accounts.id.prompt();
    const el = document.getElementById('google-button');
    if (el)
      (window as any).google.accounts.id.renderButton(el, {
        theme: 'outline',
        size: 'large',
        width: 360,
      });
  }
  function install() {
    if (installPrompt) {
      installPrompt.prompt();
      setInstallPrompt(null);
    } else
      setNotice(
        'To install: open your browser menu and choose “Install First Step Admissions” or “Add to Home screen”.',
      );
  }
  if (view === 'admin' && !user) return <Login onLogin={login} notice={notice} />;
  if (view === 'admin' && user)
    return (
      <Admin
        user={user}
        token={token}
        notice={notice}
        setNotice={setNotice}
        onSignOut={() => {
          clearStaffSession();
        }}
        onReception={returnToReception}
        onInstall={install}
      />
    );
  return (
    <>
      <header class="reception-header">
        <Brand />
        <div class="reception-nav">
          <a href={mainSite}>School website</a>
          <button class="secondary" onClick={install}>
            Install app
          </button>
          {!device && (
            <button class="secondary staff-access" onClick={openStaffAccess}>
              Staff access
            </button>
          )}
        </div>
      </header>
      {notice && (
        <div class="global-notice" role="status">
          {notice}
          <button onClick={() => setNotice('')}>×</button>
        </div>
      )}
      <main>
        {device ? (
          <ReceptionForm
            device={device}
            pending={pending}
            onSaved={setNotice}
            onSync={() => sync(device, () => pendingCount().then(setPending))}
          />
        ) : (
          <DeviceActivation
            onSaved={setNotice}
            onRegistered={(newToken, centre) => {
              localStorage.setItem('first-step-device', newToken);
              localStorage.setItem('first-step-device-centre', centre);
              setDevice(newToken);
            }}
          />
        )}
      </main>
    </>
  );
}
render(<App />, document.getElementById('app')!);
