/* ============================================================
   Archive Screen — per Proud Workpapers PDF slide 6 + ISA 230
   ============================================================
   Two tabs:
   1. ⏰ Approaching auto-archive — Active projects with auditorReportDate
      within the 60-day lock window. Sorted by countdown ascending.
   2. 📦 Archived — projects with status="archived". Supports
      "Record transaction after archived" per PDF (append-only post-archive log).
   ============================================================ */

/* ====== Request extension modal ====== */
const ExtensionRequestModal = ({ project, daysLeft, onClose, onConfirm }) => {
  const [days, setDays] = React.useState(14);
  const [reason, setReason] = React.useState("");
  const valid = days >= 1 && days <= ARCHIVE_RULES.MAX_EXTENSION_DAYS && reason.trim().length >= 10;
  return (
    <div className="modal-veil" onClick={onClose}>
      <div className="modal" onClick={e=>e.stopPropagation()} style={{maxWidth:500}}>
        <div className="modal-head">
          <div style={{width:32,height:32,borderRadius:8,background:"var(--warn-soft)",color:"var(--warn-ink)",display:"grid",placeItems:"center"}}>
            <Icon n="clock" s={16}/>
          </div>
          <h3>Request archive extension</h3>
        </div>
        <div className="modal-body">
          <div className="banner muted" style={{marginBottom:14}}>
            <div className="b-ico"><Icon n="info" s={14}/></div>
            <div className="b-body">
              <span className="b-title">{project.name}</span>
              Auto-archive in <b>T-{daysLeft} days</b>. Extensions are exceptional — Admin must approve, and you can request up to <b>{ARCHIVE_RULES.MAX_EXTENSION_DAYS} days</b> per cycle.
            </div>
          </div>
          <div className="field">
            <label>Extension days <span className="req">*</span></label>
            <input type="number" min={1} max={ARCHIVE_RULES.MAX_EXTENSION_DAYS} value={days}
              onChange={e=>setDays(Math.max(1, Math.min(ARCHIVE_RULES.MAX_EXTENSION_DAYS, parseInt(e.target.value)||1)))}
              style={{fontFamily:"var(--mono)"}}/>
            <div className="help">Cap: {ARCHIVE_RULES.MAX_EXTENSION_DAYS} days. New T-Lock will be T-{daysLeft + days} days.</div>
          </div>
          <div className="field" style={{marginBottom:0}}>
            <label>Reason <span className="req">*</span></label>
            <textarea value={reason} onChange={e=>setReason(e.target.value)}
              placeholder="e.g. Awaiting signed board minutes from year-end meeting — client confirmed delivery by X date."
              style={{minHeight:90}} autoFocus/>
            {reason && reason.trim().length < 10 && <div className="err"><Icon n="alert" s={11}/> Minimum 10 chars — be specific so Admin can decide.</div>}
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn primary" disabled={!valid} onClick={()=>onConfirm({days, reason: reason.trim()})}>
            <Icon n="send" s={13}/> Send to Admin
          </button>
        </div>
      </div>
    </div>
  );
};

/* ====== Record post-archive transaction modal ====== */
const PostArchiveTransactionModal = ({ project, onClose, onConfirm }) => {
  const [type, setType] = React.useState("subsequent-event");
  const [title, setTitle] = React.useState("");
  const [detail, setDetail] = React.useState("");
  const valid = title.trim().length >= 5 && detail.trim().length >= 20;
  const meta = POST_ARCHIVE_TYPES.find(t => t.v === type);
  return (
    <div className="modal-veil" onClick={onClose}>
      <div className="modal" onClick={e=>e.stopPropagation()} style={{maxWidth:560}}>
        <div className="modal-head">
          <div style={{width:32,height:32,borderRadius:8,background:"var(--accent-soft)",color:"var(--accent-ink)",display:"grid",placeItems:"center"}}>
            <Icon n="archive" s={16}/>
          </div>
          <h3>Record transaction after archive</h3>
        </div>
        <div className="modal-body">
          <div className="banner warn" style={{marginBottom:14}}>
            <div className="b-ico"><Icon n="alert-triangle" s={14}/></div>
            <div className="b-body">
              <span className="b-title">POST-ARCHIVE — append-only</span>
              This entry will be tagged with a <b>POST-ARCHIVE</b> watermark and stored separately from the original sealed workpapers. The original opinion and audit hash are <b>not</b> modified. Admin approval required.
            </div>
          </div>

          <div className="field">
            <label>Project</label>
            <div className="dval" style={{fontSize:12,fontWeight:500}}>{project.name}</div>
          </div>

          <div className="field">
            <label>Transaction type <span className="req">*</span></label>
            <select value={type} onChange={e=>setType(e.target.value)}>
              {POST_ARCHIVE_TYPES.map(t => <option key={t.v} value={t.v} title={t.desc}>{t.label}</option>)}
            </select>
            {meta && <div className="help" style={{marginTop:6}}><Icon n="info" s={11}/> {meta.desc}</div>}
          </div>

          <div className="field">
            <label>Title <span className="req">*</span></label>
            <input type="text" value={title} onChange={e=>setTitle(e.target.value)}
              placeholder="e.g. Bankruptcy filing notice from client" autoFocus/>
          </div>

          <div className="field" style={{marginBottom:0}}>
            <label>Detail / justification <span className="req">*</span></label>
            <textarea value={detail} onChange={e=>setDetail(e.target.value)}
              placeholder="What happened, when, who notified you, and why this needs to be recorded post-archive. Minimum 20 chars."
              style={{minHeight:100}}/>
            <div className="help">Document references, dates, and reason. This becomes part of the immutable audit trail.</div>
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn primary" disabled={!valid} onClick={()=>onConfirm({type, title: title.trim(), detail: detail.trim()})}>
            <Icon n="check" s={13}/> Submit for Admin approval
          </button>
        </div>
      </div>
    </div>
  );
};

/* ====== Archive Screen ====== */
const ArchiveScreen = ({ state, nav }) => {
  const [tab, setTab] = React.useState("approaching");
  const [q, setQ] = React.useState("");
  const [yearFilter, setYearFilter] = React.useState("all");
  const [entityFilter, setEntityFilter] = React.useState("all");
  const [reasonFilter, setReasonFilter] = React.useState("all");
  const [modal, setModal] = React.useState(null);   // {type, project}
  const [transactions, setTransactions] = React.useState(POST_ARCHIVE_TRANSACTIONS);
  const [extensions, setExtensions] = React.useState(ARCHIVE_EXTENSIONS);
  const [access, setAccess] = React.useState(ARCHIVE_ACCESS_SEED);

  /* === Approaching auto-archive === */
  const approaching = React.useMemo(() => {
    return state.projects
      .filter(p => p.status === "active")
      .map(p => ({ p, days: daysToAutoArchive(p) }))
      .filter(x => x.days != null && x.days <= ARCHIVE_RULES.LOCK_DAYS)
      .sort((a,b) => a.days - b.days);
  }, [state.projects]);

  /* === Archived projects === */
  const archived = React.useMemo(() =>
    state.projects.filter(p => p.status === "archived"),
    [state.projects]
  );
  const archivedFiltered = archived.filter(p => {
    if (entityFilter !== "all" && p.entityId !== entityFilter) return false;
    if (reasonFilter !== "all" && p.archiveReason !== reasonFilter) return false;
    if (yearFilter !== "all") {
      const y = (p.archivedAt || "").slice(0,4);
      if (y !== yearFilter) return false;
    }
    if (q) {
      const target = `${p.name} ${p.id} ${entityById(p.entityId)?.name || ""}`.toLowerCase();
      if (!target.includes(q.toLowerCase())) return false;
    }
    return true;
  });

  /* === Stats === */
  const stats = {
    critical: approaching.filter(x => x.days <= ARCHIVE_RULES.CRITICAL_DAYS).length,
    approaching: approaching.length,
    archived: archived.length,
    pendingTx: transactions.filter(t => t.status === "pending").length,
    pendingExt: extensions.filter(e => e.status === "pending").length,
    activeAccess: access.length,
  };

  const handleRevokeAccess = (grant) => {
    const u = userById(grant.userId);
    const p = state.projects.find(x => x.id === grant.projectId);
    setAccess(prev => prev.filter(g => g.id !== grant.id));
    nav.log && nav.log({ action:"perm", scope: grant.projectId, obj:`Archive access · ${u?.name || grant.userId}`, detail:`Revoked ${ARCHIVE_ACCESS_SCOPES[grant.scope]?.label || grant.scope} access to archived project ${p?.name || grant.projectId}`, severity:"critical" });
    nav.toast && nav.toast(`Access revoked — ${u?.name || grant.userId}`, "warn");
  };

  const archivedYears = [...new Set(archived.map(p => (p.archivedAt||"").slice(0,4)).filter(Boolean))].sort().reverse();

  /* === Handlers === */
  const handleRequestExtension = (project, payload) => {
    const newExt = {
      id: "AE-" + Math.random().toString(36).slice(2,7).toUpperCase(),
      projectId: project.id,
      days: payload.days, reason: payload.reason,
      requestedBy: CURRENT_ADMIN.id,
      requestedAt: new Date().toISOString(),
      status: "pending",
    };
    setExtensions(prev => [newExt, ...prev]);
    nav.toast(`Extension request sent — ${payload.days} days`, "ok");
    nav.log && nav.log({ action:"edit", scope: project.id, obj:`Project ${project.id}`, detail:`Archive extension requested · +${payload.days}d · "${payload.reason.slice(0,60)}"`, severity:"critical" });
    setModal(null);
  };

  const handleRecordTransaction = (project, payload) => {
    const newTx = {
      id: "PAT-" + Math.random().toString(36).slice(2,7).toUpperCase(),
      projectId: project.id,
      type: payload.type,
      title: payload.title, detail: payload.detail,
      submittedBy: CURRENT_ADMIN.id,
      submittedAt: new Date().toISOString(),
      status: "pending",
    };
    setTransactions(prev => [newTx, ...prev]);
    nav.toast("Post-archive transaction submitted for approval", "ok");
    nav.log && nav.log({ action:"edit", scope: project.id, obj:`Project ${project.id}`, detail:`POST-ARCHIVE ${payload.type}: "${payload.title}"`, severity:"critical" });
    setModal(null);
  };

  const handleForceArchive = (project) => {
    if (!confirm(`Force archive "${project.name}" immediately? This cannot be undone.`)) return;
    nav.toast(`${project.name} would be force-archived (POC mock)`, "warn");
    nav.log && nav.log({ action:"edit", scope: project.id, obj:`Project ${project.id}`, detail:"Force-archived by Admin (pre-T-0)", severity:"critical" });
  };

  /* === Render === */
  return (
    <>
      <div className="page-head tight">
        <div className="page-title-row">
          <h1 className="page-title">Archive</h1>
          <span className="badge mono">{ARCHIVE_RULES.LOCK_DAYS}-day hard lock</span>
        </div>
        <div className="page-sub">
          Read-only repository of closed engagements + countdown for active projects approaching auto-archive. Post-archive transactions can still be recorded as append-only entries.
        </div>
        <div style={{marginTop:18, display:"flex", gap:10, flexWrap:"wrap"}}>
          <div className="cnt"><span className="val" style={{color: stats.critical > 0 ? "var(--danger-ink)" : undefined}}>{stats.critical}</span><span className="lbl">Critical (T≤{ARCHIVE_RULES.CRITICAL_DAYS}d)</span></div>
          <div className="cnt"><span className="val">{stats.approaching}</span><span className="lbl">Approaching</span></div>
          <div className="cnt"><span className="val">{stats.archived}</span><span className="lbl">Archived total</span></div>
          <div className="cnt"><span className="val" style={{color: stats.activeAccess > 0 ? "var(--warn-ink)" : undefined}}>{stats.activeAccess}</span><span className="lbl">Active access</span></div>
          <div className="cnt"><span className="val">{stats.pendingTx}</span><span className="lbl">Pending post-archive tx</span></div>
          {stats.pendingExt > 0 && <div className="cnt"><span className="val">{stats.pendingExt}</span><span className="lbl">Pending extensions</span></div>}
        </div>
      </div>

      <div className="tabbar">
        <button className={`tab ${tab==="approaching"?"active":""}`} onClick={()=>setTab("approaching")}>
          <Icon n="clock" s={13}/> Approaching auto-archive
          <span className={`badge-count ${stats.critical>0?"amber":""}`}>{stats.approaching}</span>
        </button>
        <button className={`tab ${tab==="archived"?"active":""}`} onClick={()=>setTab("archived")}>
          <Icon n="archive" s={13}/> Archived <span className="badge-count">{stats.archived}</span>
        </button>
        <button className={`tab ${tab==="access"?"active":""}`} onClick={()=>setTab("access")}>
          <Icon n="lock" s={13}/> Active access <span className={`badge-count ${stats.activeAccess>0?"amber":""}`}>{stats.activeAccess}</span>
        </button>
        <button className={`tab ${tab==="post-archive"?"active":""}`} onClick={()=>setTab("post-archive")}>
          <Icon n="history" s={13}/> Post-archive log <span className="badge-count">{transactions.length}</span>
        </button>
      </div>

      <div className="page-body">
        {/* === TAB 1: Approaching === */}
        {tab === "approaching" && (
          approaching.length === 0 ? (
            <div className="card">
              <EmptyState icon="check-circle" title="Nothing approaching auto-archive" sub="All active projects are >60 days from their auditor report date. ✨"/>
            </div>
          ) : (
            <div className="card">
              <div className="tbl-wrap"><table className="tbl">
                <thead><tr>
                  <th>Project</th>
                  <th>Entity</th>
                  <th>Auditor Report Date</th>
                  <th>T-Lock</th>
                  <th>Members</th>
                  <th style={{width:220,textAlign:"right"}}></th>
                </tr></thead>
                <tbody>
                  {approaching.map(({p, days}) => {
                    const e = entityById(p.entityId);
                    const tone = archiveTone(days);
                    const cls = tone === "danger" ? "danger" : tone === "warn" ? "warn" : "";
                    return (
                      <tr key={p.id} className="clickable" onClick={()=>nav.go({view:"project-structure", projectId:p.id})}>
                        <td>
                          <div style={{display:"flex",flexDirection:"column",gap:3}}>
                            <span style={{fontWeight:600}}>{p.name}</span>
                            <span style={{fontSize:10.5,color:"var(--muted)"}}>{p.serviceType}{p.serviceDetail && ` · ${p.serviceDetail}`}</span>
                          </div>
                        </td>
                        <td>
                          <div style={{display:"flex",alignItems:"center",gap:8}}>
                            <span className="ent-mark" style={{width:24,height:24,fontSize:9,background:"var(--ink)"}}>{e.code}</span>
                            <span className="truncate" style={{maxWidth:140}}>{e.name}</span>
                          </div>
                        </td>
                        <td><span className="mono" style={{fontSize:12}}>{p.auditorReportDate}</span></td>
                        <td>
                          <span className={`sbadge ${cls}`} style={{fontSize:11.5}}>
                            <Icon n="clock" s={11}/>
                            T-{days} day{days!==1?"s":""}
                          </span>
                          {tone === "danger" && <div className="mono" style={{fontSize:10,color:"var(--danger-ink)",marginTop:3}}>CRITICAL</div>}
                          {tone === "warn"   && <div className="mono" style={{fontSize:10,color:"var(--warn-ink)",marginTop:3}}>Warning</div>}
                        </td>
                        <td>
                          <div className="avatar-stack">
                            {p.members.slice(0,4).map(uid=>{const u=userById(uid);return <Avatar key={uid} id={uid} name={u.name} size="sm"/>;})}
                            {p.members.length > 4 && <span className="avatar sm" style={{background:"var(--ink)",color:"#fff",borderColor:"transparent"}}>+{p.members.length-4}</span>}
                          </div>
                        </td>
                        <td style={{textAlign:"right"}} onClick={ev=>ev.stopPropagation()}>
                          <div style={{display:"inline-flex",gap:6}}>
                            <button className="btn sm" onClick={()=>setModal({type:"extension", project:p, days})} title="Request extension">
                              <Icon n="clock" s={11}/> Extend
                            </button>
                            {CURRENT_ADMIN.role === "Admin" && (
                              <button className="btn sm danger" onClick={()=>handleForceArchive(p)} title="Force-archive now (Admin)">
                                <Icon n="archive" s={11}/>
                              </button>
                            )}
                            <button className="btn sm primary" onClick={()=>nav.go({view:"project-structure", projectId:p.id})}>
                              Review <Icon n="chev-r" s={11}/>
                            </button>
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table></div>
            </div>
          )
        )}

        {/* === TAB 2: Archived === */}
        {tab === "archived" && (
          <>
            <div className="card" style={{padding:14,marginBottom:14,display:"flex",gap:10,alignItems:"center",flexWrap:"wrap"}}>
              <div className="input" style={{maxWidth:280, flex:1}}>
                <Icon n="search" s={13} c="muted"/>
                <input placeholder="Search by name, project ID, entity…" value={q} onChange={e=>setQ(e.target.value)}/>
              </div>
              <select className="btn sm" value={entityFilter} onChange={e=>setEntityFilter(e.target.value)} style={{paddingRight:24}}>
                <option value="all">All entities</option>
                {state.entities.map(en => <option key={en.id} value={en.id}>{en.code} · {en.name}</option>)}
              </select>
              <select className="btn sm" value={yearFilter} onChange={e=>setYearFilter(e.target.value)} style={{paddingRight:24}}>
                <option value="all">All years</option>
                {archivedYears.map(y => <option key={y} value={y}>{y}</option>)}
              </select>
              <select className="btn sm" value={reasonFilter} onChange={e=>setReasonFilter(e.target.value)} style={{paddingRight:24}}>
                <option value="all">All reasons</option>
                <option value="auto-lock">Auto-lock (T-0)</option>
                <option value="manual">Manual</option>
                <option value="wind-down">Entity wind-down</option>
              </select>
              <span style={{flex:1}}/>
              <span className="mono" style={{fontSize:11,color:"var(--muted)"}}>
                {archivedFiltered.length} of {archived.length}
              </span>
            </div>

            {archivedFiltered.length === 0 ? (
              <div className="card">
                <EmptyState icon="archive" title={archived.length === 0 ? "No archived projects yet" : "No archives match the filters"} sub={archived.length === 0 ? "Archived projects appear here when closed." : "Try clearing search or filters."}/>
              </div>
            ) : (
              <div className="card">
                <div className="tbl-wrap"><table className="tbl">
                  <thead><tr>
                    <th>Project</th>
                    <th>Entity</th>
                    <th>Archived</th>
                    <th>By</th>
                    <th>Reason</th>
                    <th>Hash</th>
                    <th style={{width:200,textAlign:"right"}}></th>
                  </tr></thead>
                  <tbody>
                    {archivedFiltered.map(p => {
                      const e = entityById(p.entityId);
                      const archiver = userById(p.archivedBy);
                      const reasonLabel = p.archiveReason === "auto-lock" ? "Auto-lock T-0" :
                                          p.archiveReason === "manual" ? "Manual" :
                                          p.archiveReason === "wind-down" ? "Entity wind-down" : "—";
                      const txCount = transactions.filter(t => t.projectId === p.id).length;
                      return (
                        <tr key={p.id}>
                          <td>
                            <div style={{display:"flex",flexDirection:"column",gap:3}}>
                              <span style={{fontWeight:600,display:"inline-flex",alignItems:"center",gap:6}}>
                                {p.name}
                                {txCount > 0 && (
                                  <span className="badge accent" style={{fontSize:9.5}} title={`${txCount} post-archive transaction${txCount>1?"s":""}`}>
                                    +{txCount} PAT
                                  </span>
                                )}
                              </span>
                              <span style={{fontSize:10.5,color:"var(--muted)"}}>{p.serviceType}{p.serviceDetail && ` · ${p.serviceDetail}`}</span>
                            </div>
                          </td>
                          <td>
                            <div style={{display:"flex",alignItems:"center",gap:8}}>
                              <span className="ent-mark" style={{width:24,height:24,fontSize:9,background:"var(--ink)"}}>{e?.code || "?"}</span>
                              <span className="truncate" style={{maxWidth:140}}>{e?.name || p.entityId}</span>
                            </div>
                          </td>
                          <td>
                            <span className="mono" style={{fontSize:11.5}}>{fmtTsShort(p.archivedAt)}</span>
                          </td>
                          <td>
                            {archiver && (
                              <div style={{display:"flex",alignItems:"center",gap:6}}>
                                <Avatar id={archiver.id} name={archiver.name} size="sm"/>
                                <span style={{fontSize:12}}>{archiver.name}</span>
                              </div>
                            )}
                          </td>
                          <td><span className="badge">{reasonLabel}</span></td>
                          <td><span className="mono" style={{fontSize:10.5,color:"var(--muted)"}}>{p.archiveHash || "—"}</span></td>
                          <td style={{textAlign:"right"}}>
                            <div style={{display:"inline-flex",gap:6}}>
                              <button className="btn sm" onClick={()=>nav.go({view:"activity", projectId:p.id})} title="View audit trail (read-only)">
                                <Icon n="eye" s={11}/> View
                              </button>
                              <button className="btn sm accent" onClick={()=>setModal({type:"transaction", project:p})}
                                title="Record transaction after archive">
                                <Icon n="plus" s={11}/> Post-tx
                              </button>
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table></div>
              </div>
            )}
          </>
        )}

        {/* === TAB: Active access — who can currently get into archived projects === */}
        {tab === "access" && (
          access.length === 0 ? (
            <div className="card">
              <EmptyState icon="lock" title="No active archive access" sub="People granted access to archived (Hard-Locked) projects appear here — you can revoke any time."/>
            </div>
          ) : (
            <>
              <div className="banner muted" style={{marginBottom:14}}>
                <div className="b-ico"><Icon n="info" s={14}/></div>
                <div className="b-body">
                  People currently allowed into <b>archived</b> projects — regulators, successor auditors, or staff assisting a response. Revoking removes access immediately and is logged.
                </div>
              </div>
              <div className="card">
                <div className="tbl-wrap"><table className="tbl">
                  <thead><tr>
                    <th>Person</th>
                    <th>Archived project</th>
                    <th>Scope</th>
                    <th>Granted by</th>
                    <th>Granted</th>
                    <th>Expires</th>
                    <th style={{width:120,textAlign:"right"}}></th>
                  </tr></thead>
                  <tbody>
                    {access.map(g => {
                      const u = userById(g.userId);
                      const p = state.projects.find(x => x.id === g.projectId);
                      const e = p ? entityById(p.entityId) : null;
                      const grantedBy = userById(g.grantedBy);
                      const scope = ARCHIVE_ACCESS_SCOPES[g.scope] || { label:g.scope, cls:"" };
                      const expired = g.expiresAt && g.expiresAt < "2026-05-22";
                      return (
                        <tr key={g.id}>
                          <td>
                            <div style={{display:"flex",alignItems:"center",gap:8}}>
                              <Avatar id={u.id} name={u.name} size="sm"/>
                              <div style={{minWidth:0}}>
                                <div style={{fontWeight:500,fontSize:12.5}}>{u.name}</div>
                                <div className="muted mono" style={{fontSize:10.5}}>{u.role}{u.email ? ` · ${u.email}` : ""}</div>
                              </div>
                            </div>
                          </td>
                          <td>
                            <div style={{display:"flex",alignItems:"center",gap:8}}>
                              {e && <span className="ent-mark" style={{width:22,height:22,fontSize:8.5,background:"var(--ink)"}}>{e.code}</span>}
                              <span className="truncate" style={{maxWidth:160,fontSize:12.5}}>{p?.name || g.projectId}</span>
                            </div>
                          </td>
                          <td><span className={`sbadge ${scope.cls}`} style={{fontSize:11}}>{scope.label}</span></td>
                          <td style={{fontSize:12}}>{grantedBy?.name || g.grantedBy}</td>
                          <td><span className="mono" style={{fontSize:11.5}}>{fmtTsShort(g.grantedAt)}</span></td>
                          <td>
                            {g.expiresAt
                              ? <span className="mono" style={{fontSize:11.5, color: expired ? "var(--danger-ink)" : undefined}}>{g.expiresAt}{expired ? " · expired" : ""}</span>
                              : <span className="muted" style={{fontSize:11.5}}>No expiry</span>}
                          </td>
                          <td style={{textAlign:"right"}}>
                            <button className="btn sm danger" onClick={()=>handleRevokeAccess(g)}><Icon n="x" s={11}/> Revoke</button>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table></div>
              </div>
            </>
          )
        )}

        {/* === TAB 3: Post-archive log === */}
        {tab === "post-archive" && (
          transactions.length === 0 ? (
            <div className="card">
              <EmptyState icon="history" title="No post-archive transactions" sub="Append-only transactions recorded after a project is archived will appear here."/>
            </div>
          ) : (
            <div className="card">
              <div className="tbl-wrap"><table className="tbl">
                <thead><tr>
                  <th>Title / type</th>
                  <th>Project</th>
                  <th>Submitted</th>
                  <th>Status</th>
                  <th>Approved</th>
                </tr></thead>
                <tbody>
                  {transactions.map(tx => {
                    const proj = state.projects.find(p => p.id === tx.projectId);
                    const submitter = userById(tx.submittedBy);
                    const approver = tx.approvedBy ? userById(tx.approvedBy) : null;
                    const typeMeta = POST_ARCHIVE_TYPES.find(t => t.v === tx.type);
                    return (
                      <tr key={tx.id}>
                        <td>
                          <div style={{display:"flex",flexDirection:"column",gap:3}}>
                            <span style={{fontWeight:500}}>{tx.title}</span>
                            <span className="mono" style={{fontSize:10.5,color:"var(--muted)"}}>{tx.id} · {typeMeta?.label || tx.type}</span>
                          </div>
                        </td>
                        <td>
                          <div style={{fontWeight:500,fontSize:12}}>{proj?.name || tx.projectId}</div>
                          <div className="mono" style={{fontSize:10.5,color:"var(--muted)"}}>{tx.projectId}</div>
                        </td>
                        <td>
                          <div style={{display:"flex",alignItems:"center",gap:6}}>
                            <Avatar id={submitter.id} name={submitter.name} size="sm"/>
                            <div>
                              <div style={{fontSize:12}}>{submitter.name}</div>
                              <div className="mono" style={{fontSize:10,color:"var(--muted)"}}>{fmtTsShort(tx.submittedAt)}</div>
                            </div>
                          </div>
                        </td>
                        <td>
                          {tx.status === "approved" && <span className="sbadge ok" style={{fontSize:11}}><Icon n="check" s={10}/> Approved</span>}
                          {tx.status === "pending"  && <span className="sbadge warn" style={{fontSize:11}}><Icon n="clock" s={10}/> Pending</span>}
                          {tx.status === "rejected" && <span className="sbadge archived" style={{fontSize:11}}><Icon n="x" s={10}/> Rejected</span>}
                        </td>
                        <td>
                          {approver ? (
                            <div>
                              <div style={{fontSize:12}}>{approver.name}</div>
                              <div className="mono" style={{fontSize:10,color:"var(--muted)"}}>{fmtTsShort(tx.approvedAt)}</div>
                            </div>
                          ) : <span className="muted">—</span>}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table></div>
            </div>
          )
        )}

        <div className="banner muted" style={{marginTop:14}}>
          <div className="b-ico"><Icon n="info" s={14}/></div>
          <div className="b-body">
            <b>How the 60-day rule works</b> — Projects are auto-archived 60 days after the auditor's report date. Post-archive recordings (e.g. subsequent events, regulator requests) are accepted as <b>append-only</b> entries that don't modify the original sealed workpapers. Restore is reserved for exceptional cases and requires Admin approval.
          </div>
        </div>
      </div>

      {/* Modals */}
      {modal?.type === "extension" && (
        <ExtensionRequestModal project={modal.project} daysLeft={modal.days}
          onClose={()=>setModal(null)}
          onConfirm={(p)=>handleRequestExtension(modal.project, p)}/>
      )}
      {modal?.type === "transaction" && (
        <PostArchiveTransactionModal project={modal.project}
          onClose={()=>setModal(null)}
          onConfirm={(p)=>handleRecordTransaction(modal.project, p)}/>
      )}
    </>
  );
};

Object.assign(window, { ArchiveScreen, ExtensionRequestModal, PostArchiveTransactionModal });
