/* DMS screens — visual refinement of each screen. Behavior/labels mirror the original;
   navigation + access calls go through window.DMS and window.useApp (logic untouched). */
(function () {
  const DMS = window.DMS;
  const { Icon } = window;
  const {
    TweakContext, useTw, ConfidentialityBadge, StatusChip, LegalHoldChip, AccessIndicator,
    Card, SectionTitle, Button, EmptyState, DeniedState, Field, Block, DataTable,
  } = window;
  const useApp = (...a) => window.useApp(...a);

  const {
    RECORDS, DEPARTMENTS, CONFIDENTIALITY, STATUS, RETENTION_CLASS, VERBS, CATEGORIES,
    CATEGORY_BY_CODE, DEPARTMENT_BY_CODE, ACCESS_CONFIG,
    daysUntil, departmentOf, isListable, recordVisibility, recordById, versionsOf,
    relationshipsOf, categoryOf, caseById, personById, allowedVerbs, decideAccess,
    casesOfCategory, recordCountOfCategory, recordCountOfDepartment, recordsOfCase,
    categoriesOf, searchRecords, fieldsOf, runEdgeCases,
  } = DMS;

  const VERB_LABEL = Object.fromEntries(VERBS.map((v) => [v.key, v.label]));
  const VERB_ICON = { read: 'eye', download: 'download', edit: 'edit', approve: 'check', move: 'layers', manage_lifecycle: 'history', grant: 'shield', dispose: 'x' };

  function fmtNum(n) {
    return Number(n).toLocaleString('ka-GE');
  }
  function formatField(def, value) {
    if (value === undefined || value === null || value === '') return '';
    if (def?.type === 'money') return `${fmtNum(value)} ₾`;
    if (def?.type === 'bool') return value === true || value === 'true' ? 'Yes' : 'No';
    return String(value);
  }
  const moneyKeys = new Set(['value', 'amount', 'vat']);

  /* ── Breadcrumbs ──────────────────────────────────────────── */
  function Breadcrumbs({ crumbs }) {
    const { go } = useApp();
    return (
      <nav className="mb-4 flex flex-wrap items-center gap-1.5 text-[13px] text-text-muted">
        {crumbs.map((c, i) => {
          const last = i === crumbs.length - 1;
          return (
            <span key={i} className="flex items-center gap-1.5">
              {c.view && !last ? (
                <button onClick={() => go(c.view)} className="rounded px-0.5 hover:text-primary hover:underline focusring">{c.label}</button>
              ) : (
                <span className={last ? 'font-medium text-text' : ''}>{c.label}</span>
              )}
              {!last && <Icon name="chevron" size={13} className="text-text-faint" />}
            </span>
          );
        })}
      </nav>
    );
  }

  /* ── Step-up modal ────────────────────────────────────────── */
  function StepUpModal({ title, onConfirm, onCancel }) {
    return (
      <div className="fixed inset-0 z-50 flex items-center justify-center bg-[rgb(16_24_40_/_0.45)] p-4" onClick={onCancel}>
        <div className="w-full max-w-md rounded-card border border-border bg-surface p-6 shadow-pop" onClick={(e) => e.stopPropagation()}>
          <div className="mb-3 flex h-10 w-10 items-center justify-center rounded-full" style={{ background: 'color-mix(in srgb, rgb(var(--st-hold)) 12%, white)', color: 'rgb(var(--st-hold))' }}>
            <Icon name="lock" size={20} strokeWidth={1.8} />
          </div>
          <h3 className="text-[17px] font-semibold text-text">Additional Confirm (step-up)</h3>
          <p className="mt-1.5 text-sm leading-relaxed text-text-muted">
            „{title}" is top secret. Opening requires extra confirmation (in the demo — one click). The event is logged in the audit.
          </p>
          <div className="mt-5 flex justify-end gap-2">
            <Button variant="ghost" onClick={onCancel}>Cancel</Button>
            <Button variant="danger" icon="lock" onClick={onConfirm}>Confirm and open</Button>
          </div>
        </div>
      </div>
    );
  }

  /* ── Lobby ────────────────────────────────────────────────── */
  function Kpi({ label, value, icon, tone = 'primary' }) {
    const toneVar = { primary: 'var(--c-primary)', amber: 'var(--st-disposal)', red: 'var(--st-hold)', slate: 'var(--st-archived)' }[tone];
    return (
      <Card className="dms-card flex items-center gap-3.5">
        <div className="flex h-11 w-11 flex-none items-center justify-center rounded-[10px]" style={{ background: `color-mix(in srgb, rgb(${toneVar}) 12%, white)`, color: `rgb(${toneVar})` }}>
          <Icon name={icon} size={19} strokeWidth={1.7} />
        </div>
        <div className="min-w-0">
          <div className="serif-num text-[27px] font-semibold leading-none text-text">{value}</div>
          <div className="mt-1.5 text-xs text-text-muted">{label}</div>
        </div>
      </Card>
    );
  }

  function Lobby() {
    const { person, go } = useApp();
    const visible = RECORDS.filter((r) => r.tenantId === person.tenantId && isListable(person, r));
    const expiring = visible.filter((r) => {
      const e = r.fields.expiry_date;
      if (!e) return false;
      const d = daysUntil(e);
      return d > 0 && d <= ACCESS_CONFIG.expiryWarnContractDays;
    });
    const overdue = visible.filter((r) => r.fields.payment_status === 'Pending' && r.fields.due_date && daysUntil(r.fields.due_date) < 0);
    const accessibleDepts = DEPARTMENTS.filter((d) => RECORDS.some((r) => r.departmentCode === d.code && r.tenantId === person.tenantId && isListable(person, r)));
    const openRecord = (r) => go({ name: 'record', recordId: r.id });

    return (
      <div className="mx-auto max-w-[1180px] space-y-9">
        <div className="border-b border-border pb-6">
          <div className="mb-2 flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.13em]" style={{ color: 'rgb(var(--c-accent2-ink))' }}>
            <span className="seal-rule" aria-hidden="true" /> Nuskha · Digital Archive
          </div>
          <h1 className="serif text-[30px] font-semibold leading-tight tracking-tight text-text">Hello, {person.name}</h1>
          <p className="mt-2 max-w-2xl text-sm leading-relaxed text-text-muted">This archive is shown with your access — "View as" Switching role changes what’s visible.</p>
        </div>

        <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
          <Kpi icon="file" tone="primary" label="Visible document" value={visible.length} />
          <Kpi icon="clock" tone="amber" label="Due date approaching" value={expiring.length} />
          <Kpi icon="coins" tone="red" label="Payable (overdue)" value={overdue.length} />
          <Kpi icon="archive" tone="slate" label="Available shelf" value={accessibleDepts.length} />
        </div>

        {(expiring.length > 0 || overdue.length > 0) && (
          <div>
            <SectionTitle hint="Lifecycle reminders">Warnings</SectionTitle>
            <div className="dms-stack">
              {expiring.map((r) => (
                <AlertRow key={r.id} icon="clock" tone="amber" tag="E11" onClick={() => openRecord(r)} title={r.title}
                  detail={`Expires in ${daysUntil(r.fields.expiry_date)} days`} />
              ))}
              {overdue.map((r) => (
                <AlertRow key={r.id} icon="coins" tone="red" tag="E12" onClick={() => openRecord(r)} title={r.title}
                  detail={`Overdue by ${Math.abs(daysUntil(r.fields.due_date))} days`} />
              ))}
            </div>
          </div>
        )}

        <div>
          <SectionTitle hint={`${accessibleDepts.length} shelves`}>My shelves</SectionTitle>
          {accessibleDepts.length === 0 ? (
            <Card className="dms-card text-sm text-text-muted">You haven’t been granted access to any shelf yet.</Card>
          ) : (
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
              {accessibleDepts.map((d) => {
                const count = RECORDS.filter((r) => r.departmentCode === d.code && r.tenantId === person.tenantId && isListable(person, r)).length;
                return <ShelfCard key={d.code} code={d.code} name={d.name} count={count} onClick={() => go({ name: 'department', dept: d.code })} />;
              })}
            </div>
          )}
        </div>

        <div>
          <SectionTitle>Recently viewed (visible)</SectionTitle>
          <Card className="overflow-hidden">
            {visible.slice(0, 5).map((r, i) => {
              const vis = recordVisibility(person, r).visibility;
              return (
                <button key={r.id} onClick={() => openRecord(r)}
                  className={`dms-row flex w-full items-center justify-between gap-3 text-left text-sm transition-colors hover:bg-[rgb(var(--c-primary)/0.045)] ${i ? 'border-t border-border' : ''}`}>
                  <span className="flex min-w-0 items-center gap-2.5">
                    <Icon name="file" size={15} className="flex-none text-text-faint" />
                    <span className="truncate font-medium text-text">{r.title}</span>
                    <span className="hidden truncate text-xs text-text-faint sm:inline">{departmentOf(r)?.name}</span>
                  </span>
                  <AccessIndicator visibility={vis} />
                </button>
              );
            })}
          </Card>
        </div>

        <AskArchive />
      </div>
    );
  }

  function AlertRow({ icon, tone, tag, title, detail, onClick }) {
    const toneVar = tone === 'red' ? 'var(--st-hold)' : 'var(--st-disposal)';
    return (
      <Card className="dms-row flex items-center justify-between gap-3">
        <div className="flex min-w-0 items-center gap-2.5 text-sm">
          <span className="flex h-6 w-6 flex-none items-center justify-center rounded-md" style={{ background: `color-mix(in srgb, rgb(${toneVar}) 13%, white)`, color: `rgb(${toneVar})` }}>
            <Icon name={icon} size={14} strokeWidth={1.8} />
          </span>
          <button onClick={onClick} className="truncate font-medium text-text hover:text-primary hover:underline">{title}</button>
          <span className="truncate text-text-muted">— {detail}</span>
        </div>
        <span className="mono flex-none rounded bg-surface-2 px-1.5 py-0.5 text-[11px] text-text-faint">{tag}</span>
      </Card>
    );
  }

  function ShelfCard({ code, name, count, onClick, conf, fieldSet, closed, subtitle }) {
    return (
      <button onClick={onClick} disabled={!onClick} className="group block text-left focusring rounded-card">
        <Card className={`dms-card h-full transition-all ${onClick ? 'group-hover:-translate-y-0.5 group-hover:border-border-strong group-hover:shadow-raise' : ''} ${closed ? 'opacity-65' : ''}`}>
          <div className="flex items-start justify-between gap-2">
            <span className="flex h-8 w-8 items-center justify-center rounded-[8px] bg-primary-tint text-primary">
              <Icon name="archive" size={17} strokeWidth={1.7} />
            </span>
            {conf && <ConfidentialityBadge level={conf} />}
          </div>
          <div className="mt-3 flex items-baseline gap-1.5">
            <span className="mono text-[13px] font-semibold text-text-muted">{code}</span>
          </div>
          <div className="mt-0.5 font-semibold leading-snug text-text text-balance">{name}</div>
          <div className="mt-1.5 flex items-center gap-2 text-xs text-text-muted">
            <span className="tnum">{count} visible Doc</span>
            {fieldSet && <><span className="text-text-faint">·</span><span className="mono text-text-faint">{fieldSet}</span></>}
          </div>
          {closed && <div className="mt-2 inline-flex items-center gap-1 text-xs" style={{ color: 'rgb(var(--st-disposal))' }}><Icon name="lock" size={12} /> Closed — you can’t add new</div>}
          {subtitle && !closed && <div className="mt-2 text-xs text-text-faint">{subtitle}</div>}
        </Card>
      </button>
    );
  }

  function AskArchive() {
    return (
      <Card className="dms-card">
        <div className="mb-2.5 flex items-center gap-2 text-sm font-semibold text-text">
          <span className="flex h-6 w-6 items-center justify-center rounded-md bg-primary-tint text-primary"><Icon name="sparkles" size={14} /></span>
          Ask the archive
        </div>
        <div className="flex gap-2">
          <input placeholder="e.g. “show me expired contracts…"
            className="w-full rounded-btn border border-border bg-bg px-3 py-2 text-sm outline-none transition-colors focus:border-primary focusring" />
          <Button variant="ghost" disabled>question</Button>
        </div>
        <p className="mt-2 text-xs text-text-faint">AI questions are not part of this archive demo — search and filters above work. AI document search is a separate service on minonode.com.</p>
      </Card>
    );
  }

  /* ── Department ───────────────────────────────────────────── */
  function DepartmentScreen({ dept }) {
    const { person, go } = useApp();
    const d = DEPARTMENT_BY_CODE[dept];
    const cats = categoriesOf(dept);
    return (
      <div className="mx-auto max-w-[1180px]">
        <Breadcrumbs crumbs={[{ label: 'Lobby', view: { name: 'lobby' } }, { label: `${d?.code} ${d?.name}` }]} />
        <PageTitle icon="archive" code={d?.code} title={d?.name} />
        {cats.length === 0 ? (
          <EmptyState title="No category on this shelf yet" hint="Only part of the registered categories is shown (sec. 8)." />
        ) : (
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
            {cats.map((c) => (
              <ShelfCard key={c.code} code={c.code} name={c.name} count={recordCountOfCategory(c.code, person.tenantId)}
                conf={c.defaultConfidentiality} fieldSet={c.fieldSet} closed={c.status === 'closed'}
                onClick={() => go({ name: 'category', cat: c.code })} />
            ))}
          </div>
        )}
      </div>
    );
  }

  function PageTitle({ icon, code, title, right }) {
    return (
      <div className="mb-5 flex items-start justify-between gap-3">
        <div className="flex items-center gap-3">
          {icon && <span className="flex h-9 w-9 items-center justify-center rounded-[9px] bg-primary-tint text-primary"><Icon name={icon} size={19} strokeWidth={1.7} /></span>}
          <div>
            <h1 className="serif flex items-center gap-2.5 text-[24px] font-semibold tracking-tight text-text">
              {code && <span className="mono text-[15px] font-semibold text-text-muted" style={{ letterSpacing: 0 }}>{code}</span>}
              {title}
            </h1>
          </div>
        </div>
        {right}
      </div>
    );
  }

  /* ── Category (cases table) ───────────────────────────────── */
  function CategoryScreen({ cat }) {
    const { person, go } = useApp();
    const c = CATEGORY_BY_CODE[cat];
    const d = DEPARTMENT_BY_CODE[c?.departmentCode];
    const cases = casesOfCategory(cat, person.tenantId);
    const closed = c?.status === 'closed';
    return (
      <div className="mx-auto max-w-[1180px]">
        <Breadcrumbs crumbs={[{ label: 'Lobby', view: { name: 'lobby' } }, { label: `${d?.code} ${d?.name}`, view: { name: 'department', dept: c.departmentCode } }, { label: `${c?.code} ${c?.name}` }]} />
        <PageTitle code={c?.code} title={c?.name} icon="archive"
          right={<Button variant="ghost" icon="plus" disabled={closed} title={closed ? 'Closed cat. — you can’t add new (P6)' : 'New doc'}>New doc</Button>} />
        {closed && (
          <Card className="dms-row mb-3 flex items-start gap-2.5 text-sm" style={{ borderColor: 'color-mix(in srgb, rgb(var(--st-disposal)) 30%, transparent)', background: 'color-mix(in srgb, rgb(var(--st-disposal)) 7%, white)', color: 'color-mix(in srgb, rgb(var(--st-disposal)) 85%, black)' }}>
            <Icon name="lock" size={15} className="mt-0.5 flex-none" />
            <span>This category is closed (deprecated). Existing ones are readable, you can’t add new — P6 (E7).</span>
          </Card>
        )}
        {cases.length === 0 ? (
          <EmptyState title="No case yet" icon="folder" />
        ) : (
          <DataTable headers={[{ label: 'Case' }, { label: 'Address' }, { label: 'Doc', style: { textAlign: 'right' } }, { label: 'Status', style: { textAlign: 'right' } }]}>
            {cases.map((cs) => (
              <tr key={cs.id} className="clickable" onClick={() => go({ name: 'case', caseId: cs.id })}>
                <td className="dms-td">
                  <span className="flex items-center gap-2 font-medium text-text"><Icon name="folder" size={15} className="flex-none text-text-faint" />{cs.title}</span>
                </td>
                <td className="dms-td mono text-text-muted">{cs.address}</td>
                <td className="dms-td tnum text-right text-text-muted">{recordsOfCase(cs.id).length}</td>
                <td className="dms-td text-right text-text-muted">{cs.status}</td>
              </tr>
            ))}
          </DataTable>
        )}
      </div>
    );
  }

  /* ── Case (documents table) ───────────────────────────────── */
  function CaseScreen({ caseId }) {
    const { person, go } = useApp();
    const cs = caseById(caseId);
    if (!cs) return <EmptyState title="Case not found" icon="folder" />;
    const c = CATEGORY_BY_CODE[cs.categoryCode];
    const records = recordsOfCase(caseId);
    return (
      <div className="mx-auto max-w-[1180px]">
        <Breadcrumbs crumbs={[
          { label: 'Lobby', view: { name: 'lobby' } },
          { label: `${cs.departmentCode} ${DEPARTMENT_BY_CODE[cs.departmentCode]?.name ?? ''}`, view: { name: 'department', dept: cs.departmentCode } },
          { label: `${c?.code} ${c?.name}`, view: { name: 'category', cat: cs.categoryCode } },
          { label: cs.title },
        ]} />
        <div className="mb-5 flex items-center gap-3">
          <span className="flex h-9 w-9 items-center justify-center rounded-[9px] bg-primary-tint text-primary"><Icon name="folder" size={19} strokeWidth={1.7} /></span>
          <div>
            <h1 className="serif text-[23px] font-semibold tracking-tight text-text">{cs.title}</h1>
            <div className="mono mt-0.5 text-xs text-text-faint">{cs.address}</div>
          </div>
        </div>
        <DataTable headers={[{ label: 'Document' }, { label: 'Type' }, { label: 'Date' }, { label: 'Confid.' }, { label: 'Status' }, { label: 'Access', style: { textAlign: 'right' } }]}>
          {records.map((r) => {
            const vis = recordVisibility(person, r).visibility;
            const denied = vis === 'denied';
            return (
              <tr key={r.id} className={denied ? '' : 'clickable'} onClick={() => !denied && go({ name: 'record', recordId: r.id })} style={denied ? { opacity: 0.55 } : undefined}>
                <td className="dms-td">
                  <span className="flex items-center gap-2">
                    <Icon name="file" size={15} className="flex-none text-text-faint" />
                    <span className="font-medium text-text">{r.title}</span>
                    {r.legalHold && <LegalHoldChip />}
                  </span>
                  <span className="mono ml-[23px] block text-[11px] text-text-faint">{r.address}</span>
                </td>
                <td className="dms-td text-text-muted">{r.docType}</td>
                <td className="dms-td tnum text-text-muted">{r.documentDate}</td>
                <td className="dms-td"><ConfidentialityBadge level={r.confidentiality} /></td>
                <td className="dms-td"><StatusChip status={r.status} /></td>
                <td className="dms-td text-right"><AccessIndicator visibility={vis} /></td>
              </tr>
            );
          })}
        </DataTable>
      </div>
    );
  }

  window.Screens = { Lobby, DepartmentScreen, CategoryScreen, CaseScreen, Breadcrumbs, StepUpModal, PageTitle, formatField, moneyKeys, VERB_LABEL, VERB_ICON };

  /* ── Skeleton (loading state) — matches lobby shape; gray blocks, gentle shimmer ── */
  function Sk({ w, h = 14, className = '', r }) {
    return <div className={`skel ${className}`} style={{ width: w, height: h, borderRadius: r }} />;
  }
  function LobbySkeleton() {
    return (
      <div className="mx-auto max-w-[1180px] space-y-9" aria-busy="true" aria-label="Loading">
        <div className="border-b border-border pb-6">
          <Sk w={120} h={11} />
          <div className="mt-3"><Sk w={340} h={30} /></div>
          <div className="mt-3"><Sk w={'min(90%,560px)'} h={14} /></div>
        </div>
        <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
          {[0, 1, 2, 3].map((i) => (
            <div key={i} className="rounded-card border border-border bg-surface shadow-card dms-card flex items-center gap-3.5">
              <Sk w={40} h={40} r={9} />
              <div className="flex-1 space-y-2"><Sk w={'56%'} h={20} /><Sk w={'76%'} h={11} /></div>
            </div>
          ))}
        </div>
        <div>
          <div className="mb-3 flex items-center gap-2.5"><span className="seal-rule" /><Sk w={150} h={16} /></div>
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
            {[0, 1, 2, 3, 4, 5].map((i) => (
              <div key={i} className="rounded-card border border-border bg-surface shadow-card dms-card">
                <div className="flex items-start justify-between"><Sk w={32} h={32} r={8} /><Sk w={90} h={22} r={6} /></div>
                <div className="mt-3 space-y-2"><Sk w={48} h={12} /><Sk w={'80%'} h={16} /><Sk w={'40%'} h={11} /></div>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }
  window.Screens.LobbySkeleton = LobbySkeleton;
  window.Screens.Sk = Sk;
})();
