/* ============ Screens: Project Detail / Form / Recycle Bin ============ */


/* ====== Project Approval Detail (Admin reviews a Draft) ======
   Per MTG3 §2.2 — Admin may correct Category / Risk Level inline before activating,
   without rejecting back to the Creator. */
const ProjectApprovalDetail = ({ state, nav, projectId }) => {
  const p = state.projects.find((p) => p.id === projectId);
  if (!p) return <div className="page-body"><div className="empty">Project not found</div></div>;
  const e = entityById(p.entityId);
  const creator = userById(p.createdBy);
  const tpl = templateById(p.templateId);
  const lastEditor = userById(p.lastEditBy);
  const [showApprove, setShowApprove] = React.useState(false);

  /* Inline-edit state — preload from project, save back via nav.editProjectFields on Activate */
  const [editCategory, setEditCategory] = React.useState(p.category);
  const [editRisk,     setEditRisk]     = React.useState(p.riskLevel || "");
  const dirty = editCategory !== p.category || editRisk !== (p.riskLevel || "");

  return (
    <>
      <div className="page-head">
        <div className="page-title-row">
          <StatusBadge project={p} size="lg" />
          <h1 className="page-title" style={{ flex: 1, minWidth: 0 }}>{p.name}</h1>
          {/* No Activity-log button here — drafts aren't logged (logging begins at publish) */}
        </div>
        <div className="page-sub" style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
          <span><b style={{ color: "var(--ink)" }}>For:</b> {e.name}</span>
          <span className="muted">·</span>
          <span><b style={{ color: "var(--ink)" }}>Created by</b> {creator.name} at <span className="mono">{fmtTs(p.createdAt)}</span></span>
          <span className="muted">·</span>
          <span><b style={{ color: "var(--ink)" }}>Last edited</b> <span className="mono">{fmtTs(p.lastEditAt)}</span></span>
        </div>
      </div>

      <div className="page-body">
        <div className="banner info" style={{ marginBottom: 14 }}>
          <div className="b-ico"><Icon n="info" s={15}/></div>
          <div className="b-body">
            <span className="b-title">Inline fix-then-publish</span>
            Spotted a wrong Category or Risk Level? Correct it below and click <b>Publish</b> — no need to reject this back to the Project Creator.
          </div>
        </div>
        <div className="detail-grid">
          <div>

            {/* Basic Info — inline-editable Category & Risk */}
            <div className="sec">
              <div className="sec-head">
                <span className="sec-title"><Icon n="info" s={14} /> Basic info</span>
                {dirty && <span className="badge warn"><Icon n="edit-3" s={10}/> Unsaved</span>}
              </div>
              <div className="sec-body">
                <dl className="kv">
                  <dt>Entity</dt><dd>{e.name} <span className="muted mono" style={{ fontSize: 11 }}>· {e.taxId}</span></dd>
                  <dt>Service Type</dt>
                  <dd>
                    {p.serviceType ? (
                      <span style={{display:"inline-flex",alignItems:"center",gap:8,flexWrap:"wrap"}}>
                        <b>{p.serviceType}</b>
                        {p.serviceDetail && <span className="muted">· {p.serviceDetail}</span>}
                      </span>
                    ) : <span className="muted">—</span>}
                  </dd>
                  <dt>Service Period</dt>
                  <dd>
                    {p.periodStart && p.periodEnd ? (
                      <span className="mono" style={{fontSize:12.5}}>
                        {p.periodStart} <span className="muted">→</span> {p.periodEnd}
                      </span>
                    ) : <span className="muted">—</span>}
                  </dd>
                  <dt>Category</dt>
                  <dd>
                    <select
                      value={editCategory}
                      onChange={ev => setEditCategory(ev.target.value)}
                      style={{minWidth:280}}
                      title={CATEGORY_INFO[editCategory]?.desc}>
                      {Object.entries(CATEGORY_INFO).map(([k,info]) => (
                        <option key={k} value={k}>{info.label}</option>
                      ))}
                    </select>
                    {editCategory && CATEGORY_INFO[editCategory] && (
                      <div className="help" style={{marginTop:6,lineHeight:1.5,maxWidth:520}}>
                        <Icon n="info" s={11}/> {CATEGORY_INFO[editCategory].desc}
                      </div>
                    )}
                  </dd>
                  <dt>Risk Level <span className="req">*</span></dt>
                  <dd>
                    <select
                      value={editRisk}
                      onChange={ev => setEditRisk(ev.target.value)}
                      style={{minWidth:220, borderColor: !editRisk ? "var(--danger)" : "var(--line)"}}
                      title={RISK_INFO[editRisk]?.desc}>
                      <option value="">— Select risk level —</option>
                      {RISK_LEVELS.map(r => (
                        <option key={r.v} value={r.v}>{r.label} — {r.desc.slice(0,55)}{r.desc.length>55?"…":""}</option>
                      ))}
                    </select>
                    {!editRisk && <div className="err" style={{marginTop:6}}><Icon n="alert" s={11}/> Risk Level required — must be set before Publish.</div>}
                  </dd>
                  <dt>Description</dt><dd>{p.description}</dd>
                </dl>
              </div>
            </div>

            {/* Members — MTG4 §2.2: Project Creator + Members are the two project-level roles */}
            <div className="sec">
              <div className="sec-head">
                <span className="sec-title"><Icon n="users" s={14} /> Members <span className="badge">{p.members.length}</span></span>
                <Tooltip text="Project Role hierarchy: Project Creator (the Supervisor who created it) and Members (everyone else). System Role appears alongside.">
                  <span/>
                </Tooltip>
              </div>
              <div className="sec-body">
                <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                  {p.members.map((uid) => {
                    const u = userById(uid);
                    const isCreator = uid === p.createdBy;
                    return (
                      <div key={uid} style={{ display: "flex", alignItems: "center", gap: 10 }}>
                        <Avatar id={uid} name={u.name} size="md" />
                        <div style={{ flex: 1 }}>
                          <div style={{ fontWeight: 500 }}>{u.name}</div>
                          <div className="muted" style={{ fontSize: 11, fontFamily: "var(--mono)" }}>{u.email}</div>
                        </div>
                        {isCreator && <span className="sbadge accent" style={{fontSize:10}}><Icon n="flag" s={9}/> Project Creator</span>}
                        {!isCreator && <span className="badge" title="Project-level role: Member">Member</span>}
                        <span className="badge" title="System role">{u.role}</span>
                      </div>);

                  })}
                </div>
              </div>
            </div>

            {/* Structure */}
            <div className="sec">
              <div className="sec-head">
                <span className="sec-title"><Icon n="layers" s={14} /> Structure</span>
                {tpl ? <span className="badge accent" data-comment-anchor="70b9229f96-span-221-24">{tpl.name} · {tpl.v}</span> : <span className="badge">Empty (start from scratch)</span>}
              </div>
              <div className="sec-body">
                {tpl ?
                <>
                    <div className="banner muted" style={{ marginBottom: 14 }}>
                      <div className="b-ico"><Icon n="info" s={14} /></div>
                      <div className="b-body">
                        Structure is copied from the template once. Editing the template later will not affect this Project.
                      </div>
                    </div>
                    <div className="tree">
                      {TEMPLATE_PREVIEW.map((n) =>
                    <div key={n.id}>
                          <div className="tree-node"><Icon n="chev-d" s={12} c="chev" /><Icon n="folder" s={14} c="muted" /><b style={{ fontWeight: 500 }}>{n.name}</b><span className="tree-meta">{n.n} files</span></div>
                          {n.kids &&
                      <div className="tree-kids">
                              {n.kids.map((k) =>
                        <div key={k.id} className="tree-node"><Icon n="folder" s={13} c="muted" />{k.name}<span className="tree-meta">{k.n}</span></div>
                        )}
                            </div>
                      }
                        </div>
                    )}
                    </div>
                  </> :

                <div className="empty" style={{ padding: 24 }}>
                    <div className="em-illu" style={{ width: 42, height: 42 }}><Icon n="folder" s={18} /></div>
                    <div className="em-title" style={{ fontSize: 13 }}>No structure yet</div>
                    <div className="em-sub">The Project Creator chose to start from scratch — folders will be added after the project is active.</div>
                  </div>
                }
              </div>
            </div>

          </div>

          {/* Right column: Approval timeline + meta */}
          <div>
            {/* Drafts keep no detailed change history (user decision 2026-06-12) —
               just who created it and who touched it last. Full logging starts at publish. */}
            <div className="sec">
              <div className="sec-head"><span className="sec-title"><Icon n="history" s={14} /> Draft info</span></div>
              <div className="sec-body">
                <dl className="kv" style={{ gridTemplateColumns: "100px 1fr" }}>
                  <dt>Created by</dt>
                  <dd>
                    <div style={{display:"flex",alignItems:"center",gap:8}}>
                      <Avatar id={creator.id} name={creator.name} size="sm"/>
                      <div>
                        <div style={{fontSize:12.5,fontWeight:500}}>{creator.name}</div>
                        <div className="mono" style={{fontSize:10.5,color:"var(--muted)"}}>{fmtTsShort(p.createdAt)}</div>
                      </div>
                    </div>
                  </dd>
                  <dt>Last edited</dt>
                  <dd>
                    <div style={{display:"flex",alignItems:"center",gap:8}}>
                      <Avatar id={lastEditor.id} name={lastEditor.name} size="sm"/>
                      <div>
                        <div style={{fontSize:12.5,fontWeight:500}}>{lastEditor.name}</div>
                        <div className="mono" style={{fontSize:10.5,color:"var(--muted)"}}>{fmtTsShort(p.lastEditAt)}</div>
                      </div>
                    </div>
                  </dd>
                </dl>
              </div>
            </div>

            <div className="sec">
              <div className="sec-head"><span className="sec-title"><Icon n="info" s={14} /> Meta</span></div>
              <div className="sec-body">
                <dl className="kv" style={{ gridTemplateColumns: "100px 1fr" }}>
                  <dt>Folders</dt><dd>{p.folders || 0}</dd>
                  <dt>Files</dt><dd>{p.files || 0}</dd>
                  <dt>Members</dt><dd>{p.members.length}</dd>
                  <dt>Template</dt><dd data-comment-anchor="c4c22b7f70-dd-290-36">{tpl ? `${tpl.name} · ${tpl.v}` : "—"}</dd>
                </dl>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="actionbar">
        <button className="btn" onClick={() => nav.go({ view: "home" })}>
          <Icon n="arrow-l" s={13} /> Back to Home
        </button>
        <span style={{ flex: 1 }}></span>
        {dirty && (
          <span className="lead" style={{marginRight:10,color:"var(--warn-ink)"}}>
            <Icon n="edit-3" s={12}/> Edits will be saved when you publish
          </span>
        )}
        <button className="btn primary" disabled={!editRisk} onClick={() => setShowApprove(true)}
          title={!editRisk ? "Risk Level required before publish" : ""}>
          <Icon n="check" s={13} /> {dirty ? "Save & Publish" : "Publish"}
        </button>
      </div>

      {showApprove && <ApproveModal project={p} edits={dirty ? { category: editCategory, riskLevel: editRisk } : null}
        onClose={() => setShowApprove(false)} onConfirm={(comment) => {
        if (dirty) nav.editProjectFields(p.id, { category: editCategory, riskLevel: editRisk });
        nav.approveProject(p.id, comment);
        setShowApprove(false);
      }} />}
    </>);

};

/* ====== Project Draft Detail — collaborative editing of an existing draft.
   Delegates to ProjectDraftForm in `existing` mode so the form layout is the
   exact same shape as project creation (Basic info / Members / Reviewer
   Roles / Structure) with every field genuinely editable. Save patches the
   project in place; Publish promotes it to Active. */
const ProjectDraftDetail = ({ state, nav, projectId }) => {
  const p = state.projects.find((p) => p.id === projectId);
  if (!p) return <div className="page-body"><div className="empty">Project not found</div></div>;
  return <ProjectDraftForm state={state} nav={nav} entityId={p.entityId} existing={p}/>;
};

/* Tiny helper section with inline Edit button */
const SectionEditable = ({ title, icon, rightBadge, canEdit, children }) =>
<div className="sec">
    <div className="sec-head">
      <span className="sec-title"><Icon n={icon} s={14} /> {title}</span>
      {rightBadge && <span className="badge accent">{rightBadge}</span>}
      {canEdit &&
    <div className="sec-actions">
          <button className="btn sm"><Icon n="edit-3" s={12} /> Edit</button>
        </div>
    }
    </div>
    <div className="sec-body">{children}</div>
  </div>;


/* ====== Project Draft Form (NEW project) ======
   Per MTG3:
   - Risk Level (High/Moderate/Low) is REQUIRED — ก.ล.ต. rule
   - Tooltips on Category A–D and SOP Template selection
   - Save flow:
     · Admin POV → "Save as Draft" or "Save & Activate" (immediate Active per MTG3)
     · Creator POV → "Save as Draft" (sits with Creator) or "Send to Admin for Activation"
*/
const ProjectDraftForm = ({ state, nav, entityId, existing }) => {
  const e = entityById(entityId || existing?.entityId);
  const isEdit = !!existing;
  const [name, setName] = React.useState(existing?.name || "");
  const [desc, setDesc] = React.useState(existing?.description || "");
  const [cat, setCat] = React.useState(existing?.category || "");
  const [riskLevel, setRiskLevel] = React.useState(existing?.riskLevel || "");
  const [serviceType, setServiceType] = React.useState(existing?.serviceType || "");
  const [periodStart, setPeriodStart] = React.useState(existing?.periodStart || "");
  const [periodEnd, setPeriodEnd] = React.useState(existing?.periodEnd || "");
  const [members, setMembers] = React.useState(existing?.members || []);
  const [reviewerSlots, setReviewerSlots] = React.useState(
    existing?.reviewerSlots
      ? existing.reviewerSlots.map(r => ({...r}))
      : DEFAULT_REVIEWER_SLOTS.map(r => ({...r}))
  );
  const [tplId, setTplId] = React.useState(existing?.templateId || "T-FS-STD");
  const [scratch, setScratch] = React.useState(existing ? !existing.templateId : false);
  const [pickerOpen, setPickerOpen] = React.useState(false);
  const [showDelete, setShowDelete] = React.useState(false);

  /* Reviewer-slot helpers */
  const updateSlot = (idx, patch) => setReviewerSlots(prev =>
    prev.map((r, i) => i === idx ? {...r, ...patch} : r)
  );
  const addSlot = () => setReviewerSlots(prev =>
    [...prev, { role:"Custom slot", required:false, userId:null }]
  );
  const removeSlot = (idx) => setReviewerSlots(prev =>
    prev.filter((_, i) => i !== idx)
  );
  /* Eligible reviewers — must be a project member (plus the creator who
     is implicitly a member). Guest is excluded because they can't sign. */
  const memberIdSet = new Set([CURRENT_ADMIN.id, ...members]);
  const reviewerCandidates = USERS.filter(u =>
    u.active && u.role !== "Guest" && memberIdSet.has(u.id)
  );

  const isAdmin = CURRENT_ADMIN.role === "Admin";
  const serviceTypeObj = serviceTypeByName(serviceType);

  /* Period validation — end must be >= start */
  const periodValid = !!periodStart && !!periodEnd && periodEnd >= periodStart;
  const periodDays = periodValid
    ? Math.ceil((new Date(periodEnd) - new Date(periodStart)) / 86400000) + 1
    : null;

  /* Risk Level + Period required per MTG3 §2.2 + MTG4 §2.1 */
  const valid = name.trim().length >= 2 && !!cat && !!riskLevel && !!serviceType && periodValid;
  const missing = (() => {
    const m = [];
    if (name.trim().length < 2) m.push("Project name");
    if (!serviceType) m.push("Service Type");
    if (!periodStart || !periodEnd) m.push("Service Period");
    if (periodStart && periodEnd && periodEnd < periodStart) m.push("Period end ≥ start");
    if (!cat) m.push("Category");
    if (!riskLevel) m.push("Risk Level");
    return m;
  })();
  const tpl = templateById(tplId);

  /* `mode`:
       "draft"   — save as draft (auto-visible under Pending approvals on Home for either role)
       "publish" — Admin only — go live immediately (status=active)               */
  const save = (mode) => {
    if (isEdit) {
      /* Edit existing draft — patch fields in place */
      nav.editProjectFields(existing.id, {
        name: name.trim(),
        description: desc.trim(),
        category: cat,
        riskLevel,
        serviceType,
        periodStart, periodEnd,
        members,
        reviewerSlots: reviewerSlots.map(r => ({...r})),
        templateId: scratch ? null : tplId,
      });
      nav.toast("Draft updated", "ok");
      if (mode === "publish") nav.approveProject(existing.id, "Published by Admin");
      return;
    }
    const id = "P-2026-" + String(20 + state.projects.length).padStart(3, "0");
    const now = "2026-05-22T10:00:00";
    const proj = {
      id, entityId, name: name.trim(),
      category: cat,
      riskLevel,
      serviceType,
      serviceDetail: null,
      periodStart, periodEnd,
      status: mode === "publish" ? "active" : "draft",
      description: desc.trim(), members,
      reviewerSlots: reviewerSlots.map(r => ({...r})),
      templateId: scratch ? null : tplId,
      folders: scratch ? 0 : tpl?.folders || 0, files: scratch ? 0 : tpl?.wpids || 0,
      createdBy: CURRENT_ADMIN.id, createdAt: now,
      submittedAt: null,
      approvedAt: mode === "publish" ? now : null,
      approvedBy: mode === "publish" ? CURRENT_ADMIN.id : null,
      lastEditBy: CURRENT_ADMIN.id, lastEditAt: now,
    };
    nav.addProject(proj);
    if (mode === "publish") {
      nav.toast("Project published", "ok");
      nav.go({ view: "project-structure", projectId: id });
    } else {
      nav.toast(isAdmin ? "Draft saved — visible under Pending approvals on Home" : "Draft saved — Admin will see it under Pending approvals on Home", "ok");
      nav.go({ view: "project-draft", projectId: id });
    }
  };

  return (
    <>
      <div className="formpage">
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 18 }}>
          <span className="ent-mark lg" style={{ background: `var(--ink)`, width: 36, height: 36, fontSize: 11, borderRadius: 8 }}>{e?.code}</span>
          <div style={{flex:1, minWidth:0}}>
            <div className="muted" style={{ fontSize: 11, fontFamily: "var(--mono)", textTransform: "uppercase", letterSpacing: ".05em", fontWeight: 600 }}>
              {isEdit ? "Edit draft for" : "New project for"}
            </div>
            <h2 style={{ margin: 0, fontSize: 18 }}>{e?.name}</h2>
          </div>
          {isEdit && (
            <div style={{display:"flex", gap:8}}>
              <button className="btn danger" onClick={() => setShowDelete(true)}>
                <Icon n="trash" s={13} /> Delete draft
              </button>
            </div>
          )}
        </div>

        {/* Draft info — drafts keep no detailed history, just creator + last touch */}
        {isEdit && (
          <div className="page-sub" style={{display:"flex",alignItems:"center",gap:14,flexWrap:"wrap",margin:"-6px 0 16px"}}>
            <span><b style={{color:"var(--ink)"}}>Created by</b> {userById(existing.createdBy)?.name} <span className="mono" style={{fontSize:11.5}}>{fmtTsShort(existing.createdAt)}</span></span>
            <span className="muted">·</span>
            <span><b style={{color:"var(--ink)"}}>Last edited by</b> {userById(existing.lastEditBy)?.name} <span className="mono" style={{fontSize:11.5}}>{fmtTsShort(existing.lastEditAt)}</span></span>
          </div>
        )}

        <div className="sec">
          <div className="sec-head"><span className="sec-title"><Icon n="info" s={14} /> Basic info</span></div>
          <div className="sec-body">
            <div className="field">
              <label>Project name <span className="req">*</span></label>
              <input type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Annual Audit FY2026" />
            </div>
            <div className="field">
              <label>Description</label>
              <textarea value={desc} onChange={(e) => setDesc(e.target.value)} placeholder="Scope, group consolidation notes, regulatory context…" />
            </div>
            <div className="field">
              <label>
                <Tooltip text="Main engagement type (Audit / Limited Review / Agreed-Upon Procedures / Others).">
                  <span>Service Type <span className="req">*</span></span>
                </Tooltip>
              </label>
              <select value={serviceType} onChange={(e) => setServiceType(e.target.value)} title={serviceTypeObj?.desc}>
                <option value="">— Select service type —</option>
                {SERVICE_TYPE_CATALOG.map(st => (
                  <option key={st.code} value={st.name} title={st.desc}>{st.name}</option>
                ))}
              </select>
              {serviceTypeObj && (
                <div className="help" style={{marginTop:6}}>
                  {serviceTypeObj.desc}
                </div>
              )}
            </div>
            <div className="field">
              <label>
                <Tooltip text="Service Period is mandatory for every project. Pick the start and end dates that the engagement covers (e.g. fiscal year, quarter, due-diligence window).">
                  <span>Service Period <span className="req">*</span></span>
                </Tooltip>
              </label>
              <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
                <div>
                  <div className="mono" style={{fontSize:10,color:"var(--muted)",marginBottom:4,textTransform:"uppercase",letterSpacing:".05em"}}>Start</div>
                  <input type="date" value={periodStart} onChange={e => setPeriodStart(e.target.value)} style={{fontFamily:"var(--mono)"}}/>
                </div>
                <div>
                  <div className="mono" style={{fontSize:10,color:"var(--muted)",marginBottom:4,textTransform:"uppercase",letterSpacing:".05em"}}>End</div>
                  <input type="date" value={periodEnd} onChange={e => setPeriodEnd(e.target.value)}
                    min={periodStart || undefined}
                    style={{fontFamily:"var(--mono)", borderColor: periodStart && periodEnd && periodEnd < periodStart ? "var(--danger)" : undefined}}/>
                </div>
              </div>
              {periodStart && periodEnd && periodEnd < periodStart && (
                <div className="err" style={{marginTop:6}}><Icon n="alert" s={11}/> End date must be on or after Start date.</div>
              )}
              {periodValid && (
                <div className="help" style={{marginTop:6}}>
                  <Icon n="check" s={11}/> Period covers <b>{periodDays}</b> day{periodDays !== 1 ? "s" : ""}.
                </div>
              )}
            </div>
            <div className="field">
              <label>
                <Tooltip text="Category drives sampling depth, EQR triggers, partner-review requirements, and regulatory reporting.">
                  <span>Category <span className="req">*</span></span>
                </Tooltip>
              </label>
              <select value={cat} onChange={(e) => setCat(e.target.value)} title={CATEGORY_INFO[cat]?.desc}>
                <option value="">— Select category —</option>
                {Object.entries(CATEGORY_INFO).map(([k,info]) => (
                  <option key={k} value={k} title={info.desc}>{info.label}</option>
                ))}
              </select>
              {cat && CATEGORY_INFO[cat] && (
                <div className="help" style={{marginTop:6,lineHeight:1.5}}>
                  <Icon n="info" s={11}/> {CATEGORY_INFO[cat].desc}
                </div>
              )}
            </div>
            <div className="field" style={{ marginBottom: 0 }}>
              <label>
                <Tooltip text="Drives sampling intensity, EQR triggers, and partner review depth.">
                  <span>Risk Level <span className="req">*</span></span>
                </Tooltip>
              </label>
              <select value={riskLevel} onChange={ev => setRiskLevel(ev.target.value)} title={RISK_INFO[riskLevel]?.desc}>
                <option value="">— Select risk level —</option>
                {RISK_LEVELS.map(r => (
                  <option key={r.v} value={r.v} title={r.desc}>{r.label}</option>
                ))}
              </select>
              {riskLevel && <div className="help" style={{marginTop:6,lineHeight:1.5}}><Icon n="info" s={11}/> {RISK_INFO[riskLevel].desc}</div>}
            </div>
          </div>
        </div>

        <div className="sec">
          <div className="sec-head"><span className="sec-title"><Icon n="users" s={14} /> Members</span><span className="badge">{members.length} selected</span></div>
          <div className="sec-body">
            <div className="usr-chips">
              {members.map((uid) => {
                const u = userById(uid);
                return (
                  <span key={uid} className="usr-chip">
                    <Avatar id={uid} name={u.name} size="sm" />
                    {u.name} <span className="muted" style={{ fontSize: 10 }}>· {u.role}</span>
                    <span className="x" onClick={() => {
                      setMembers(members.filter((m) => m !== uid));
                      /* Drop this user from any reviewer slot they were assigned to */
                      setReviewerSlots(prev => prev.map(r => r.userId === uid ? {...r, userId: null} : r));
                    }}><Icon n="x" s={10} /></span>
                  </span>);

              })}
              <span className="usr-picker-add" onClick={() => setPickerOpen(true)}>
                <Icon n="plus" s={11} /> Add member
              </span>
            </div>
            <div className="help" style={{ marginTop: 8 }}>Pick from Supervisors and Staff. The Project Creator (you) is added automatically.</div>
          </div>
        </div>

        <div className="sec">
          <div className="sec-head">
            <span className="sec-title">
              <Tooltip text="Define the reviewer roles that will sign off on every WPID in this project. Each role = one seat held by one reviewer; if a position has two people (e.g. Manager #1 and Manager #2), add two roles. Required roles must sign before a WPID becomes Done; Optional roles can sign but don't block.">
                <span>Reviewer Roles <span className="badge">{reviewerSlots.length}</span></span>
              </Tooltip>
            </span>
            <div className="sec-actions">
              <button className="btn sm" onClick={addSlot}><Icon n="plus" s={12}/> Add role</button>
            </div>
          </div>
          <div className="sec-body">
            <div style={{display:"flex",flexDirection:"column",gap:8}}>
              {reviewerSlots.map((r, i) => (
                <div key={i} style={{
                  display:"grid",
                  gridTemplateColumns:"minmax(140px, 1fr) 180px minmax(180px, 1.2fr) 28px",
                  alignItems:"center",
                  gap:10,
                  padding:"8px 10px",
                  background:"var(--panel-3)",
                  border:"1px solid var(--line)",
                  borderRadius:"var(--radius)",
                }}>
                  <input
                    type="text"
                    value={r.role}
                    onChange={ev => updateSlot(i, { role: ev.target.value })}
                    placeholder="Role name (e.g. Manager #1)"
                    style={{fontWeight:500}}
                  />
                  <div className="seg" style={{display:"flex"}}>
                    <button onClick={() => updateSlot(i, { required: true })}
                      style={{padding:"6px 10px",fontSize:11.5,border:"1px solid var(--line)",borderRadius:"6px 0 0 6px",
                        background:r.required?"var(--ink)":"#fff",color:r.required?"#fff":"var(--ink-2)",cursor:"pointer"}}>
                      Required
                    </button>
                    <button onClick={() => updateSlot(i, { required: false })}
                      style={{padding:"6px 10px",fontSize:11.5,border:"1px solid var(--line)",borderLeft:"none",borderRadius:"0 6px 6px 0",
                        background:!r.required?"var(--ink)":"#fff",color:!r.required?"#fff":"var(--ink-2)",cursor:"pointer"}}>
                      Optional
                    </button>
                  </div>
                  <select value={r.userId || ""} onChange={ev => updateSlot(i, { userId: ev.target.value || null })}>
                    <option value="">— Unassigned —</option>
                    {reviewerCandidates.map(u => (
                      <option key={u.id} value={u.id}>{u.name} · {u.role}</option>
                    ))}
                  </select>
                  <button className="icon-btn" onClick={() => removeSlot(i)} title="Remove role" style={{color:"var(--danger-ink)"}}>
                    <Icon n="trash" s={12}/>
                  </button>
                </div>
              ))}
              {reviewerSlots.length === 0 && (
                <div className="muted" style={{padding:"12px 4px",fontSize:12.5}}>
                  No reviewer roles defined. <button className="btn sm ghost" onClick={addSlot} style={{padding:"2px 6px"}}><Icon n="plus" s={11}/> Add one</button>
                </div>
              )}
            </div>
            <div className="help" style={{marginTop:10}}>
              Reviewer picks are restricted to <b>project members</b> — add members above first if the list of candidates feels short. Assignments can stay unassigned and be filled in later from the Project workspace.
            </div>
          </div>
        </div>

        <div className="sec">
          <div className="sec-head"><span className="sec-title"><Icon n="layers" s={14} /> Structure</span></div>
          <div className="sec-body">
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 14 }}>
              <label style={{
                display: "flex", alignItems: "flex-start", gap: 10, padding: 14, border: `1.5px solid ${!scratch ? "var(--ink)" : "var(--line)"}`,
                background: !scratch ? "var(--panel-3)" : "#fff", borderRadius: "var(--radius-lg)", cursor: "pointer"
              }}>
                <input type="radio" checked={!scratch} onChange={() => setScratch(false)} style={{ marginTop: 3 }} />
                <div>
                  <div style={{ fontWeight: 600, marginBottom: 3 }}>Use an SOP Template</div>
                  <div className="muted" style={{ fontSize: 12 }}>Copy a standard folder + WPID structure into this project.</div>
                </div>
              </label>
              <label style={{
                display: "flex", alignItems: "flex-start", gap: 10, padding: 14, border: `1.5px solid ${scratch ? "var(--ink)" : "var(--line)"}`,
                background: scratch ? "var(--panel-3)" : "#fff", borderRadius: "var(--radius-lg)", cursor: "pointer"
              }}>
                <input type="radio" checked={scratch} onChange={() => setScratch(true)} style={{ marginTop: 3 }} />
                <div>
                  <div style={{ fontWeight: 600, marginBottom: 3 }}>Start from scratch</div>
                  <div className="muted" style={{ fontSize: 12 }}>Empty structure — build folders manually after approval.</div>
                </div>
              </label>
            </div>

            {!scratch &&
            <>
                <div className="field" style={{ marginBottom: 14 }}>
                  <label>
                    <Tooltip text="Template provides the starting folder + WPID structure. Once copied, this Project is independent — later template edits do NOT change this Project.">
                      <span>Template</span>
                    </Tooltip>
                  </label>
                  <select value={tplId} onChange={(e) => setTplId(e.target.value)} title={TEMPLATE_INFO[tplId]}>
                    {TEMPLATES.map((t) =>
                  <option key={t.id} value={t.id} title={TEMPLATE_INFO[t.id]}>{t.name} · {t.v}</option>
                  )}
                  </select>
                  {tplId && TEMPLATE_INFO[tplId] && (
                    <div className="help" style={{marginTop:6}}>
                      <Icon n="info" s={11}/> {TEMPLATE_INFO[tplId]}
                    </div>
                  )}
                </div>
                <div className="section-label" style={{ margin: "14px 0 8px" }}>Preview · {tpl?.folders} folders · {tpl?.wpids} WPIDs</div>
                <div style={{ border: "1px solid var(--line)", borderRadius: "var(--radius)", padding: "8px 10px", background: "var(--panel-3)" }}>
                  <div className="tree">
                    {TEMPLATE_PREVIEW.map((n) =>
                  <div key={n.id}>
                        <div className="tree-node"><Icon n="chev-d" s={12} c="chev" /><Icon n="folder" s={14} c="muted" /><b style={{ fontWeight: 500 }}>{n.name}</b><span className="tree-meta">{n.n}</span></div>
                        {n.kids &&
                    <div className="tree-kids">
                            {n.kids.slice(0, 3).map((k) =>
                      <div key={k.id} className="tree-node"><Icon n="folder" s={13} c="muted" />{k.name}<span className="tree-meta">{k.n}</span></div>
                      )}
                            {n.kids.length > 3 && <div className="tree-node muted" style={{ paddingLeft: 24, fontSize: 11.5 }}>+{n.kids.length - 3} more</div>}
                          </div>
                    }
                      </div>
                  )}
                  </div>
                </div>
              </>
            }
          </div>
        </div>
      </div>

      <div className="formfoot">
        <span style={{ flex: 1 }}></span>
        <button className={isAdmin ? "btn" : "btn primary"} disabled={!valid} onClick={() => save("draft")}>
          <Icon n="file-text" s={13} /> {isEdit ? "Save changes" : "Save as Draft"}
        </button>
        {isAdmin && (
          <button className="btn primary" disabled={!valid} onClick={() => save("publish")}>
            <Icon n="check" s={13} /> {isEdit ? "Save & Publish" : "Publish now"}
          </button>
        )}
      </div>

      {pickerOpen && <MemberPickerModal already={members} onClose={() => setPickerOpen(false)} onSelect={(uid) => {
        setMembers([...members, uid]);
        setPickerOpen(false);
      }} />}

      {isEdit && showDelete && <DeleteDraftModal project={existing} onClose={() => setShowDelete(false)} onConfirm={() => {
        setShowDelete(false);
        nav.deleteProject(existing.id);
      }} />}
    </>);

};

/* ====== Recycle Bin Screen ======
   Per MTG3 §2.4 —
   · Scoped per-project (project picker at top; archive purges per-project)
   · No permanent delete — files are only purged when their project is archived
   · Restore: if original folder no longer exists, prompt to pick a new destination
   · Search + filter (by deleter, by type) */
const RecycleBinScreen = ({ state, nav, scopedProjectId, embedded }) => {
  const [items, setItems] = React.useState(RECYCLE_BIN);
  /* if scoped through props (project workspace), preselect; otherwise let admin pick */
  const projects = React.useMemo(() => {
    const ids = [...new Set(RECYCLE_BIN.map(i => i.project))];
    return ids.map(id => {
      const p = state.projects.find(pp => pp.id === id);
      return { id, name: p?.name || id, count: items.filter(i => i.project === id).length };
    });
  }, [items, state.projects]);

  const [proj, setProj] = React.useState(scopedProjectId || (projects[0]?.id || ""));
  const [q, setQ] = React.useState("");
  const [typeFilter, setTypeFilter] = React.useState("all"); // all | wpid | file | folder

  const scoped = items.filter(i => i.project === proj);
  const filtered = scoped.filter(i => {
    if (typeFilter !== "all" && i.type !== typeFilter) return false;
    if (q && !(`${i.name} ${i.folder} ${i.deletedByName}`).toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  });

  /* Restore picker — if folderExists false, ask for new destination */
  const [pickingFor, setPickingFor] = React.useState(null);
  const [pickDest, setPickDest] = React.useState("");

  const doRestore = (item, destination) => {
    setItems(prev => prev.filter(i => i.id !== item.id));
    nav.toast(`Restored to ${destination}`, "ok");
    nav.log && nav.log({ action:"edit", scope:item.project, obj:item.name, detail:`Restored from Recycle Bin → ${destination}` });
    setPickingFor(null);
    setPickDest("");
  };

  const handleRestore = (item) => {
    if (item.folderExists) {
      doRestore(item, item.folder);
    } else {
      setPickingFor(item);
      setPickDest("");
    }
  };

  return (
    <>
      {!embedded && (
        <div className="page-head tight">
          <div className="page-title-row">
            <h1 className="page-title">Recycle Bin</h1>
            {scoped.length > 0 && <span className="sbadge warn">{scoped.length} item{scoped.length>1?"s":""} in this project</span>}
          </div>
          <div className="page-sub">
            Deletes are per-project and reversible. Items are <b>only purged when the project is archived</b>; there is no permanent-delete control.
          </div>
        </div>
      )}

      <div className="page-body">
        {/* Project picker + search + filter — top-of-project per MTG3 */}
        <div className="card" style={{padding:14,marginBottom:14,display:"flex",gap:10,alignItems:"center",flexWrap:"wrap"}}>
          {!embedded && (
            <div style={{display:"flex",alignItems:"center",gap:6}}>
              <span className="mono" style={{fontSize:10.5,color:"var(--muted)",textTransform:"uppercase",letterSpacing:".05em"}}>Project</span>
              <select value={proj} onChange={e=>setProj(e.target.value)} style={{minWidth:260}}>
                {projects.map(p => <option key={p.id} value={p.id}>{p.name} ({p.count})</option>)}
              </select>
            </div>
          )}
          <div className="input" style={{maxWidth:280, flex:1}}>
            <Icon n="search" s={13} c="muted"/>
            <input placeholder="Search by name, folder, or who deleted…" value={q} onChange={e=>setQ(e.target.value)}/>
          </div>
          <div style={{display:"flex",gap:4}}>
            {["all","wpid","file","folder"].map(t => (
              <button key={t} className={`btn sm ${typeFilter===t?"accent":""}`} onClick={()=>setTypeFilter(t)}>
                {t === "all" ? "All" : t[0].toUpperCase()+t.slice(1)+"s"}
              </button>
            ))}
          </div>
        </div>

        {filtered.length === 0 ? (
          <div className="card">
            <EmptyState icon="trash" title={scoped.length === 0 ? "Nothing deleted in this project" : "No items match filters"} sub={scoped.length === 0 ? "Items deleted here will appear in this project's bin." : "Try clearing the search or type filter."}/>
          </div>
        ) : (
          <div className="card">
            <table className="tbl">
              <thead><tr>
                <th>Name</th>
                <th>Original location</th>
                <th>Type</th>
                <th>Deleted by</th>
                <th>Deleted</th>
                <th style={{width:140,textAlign:"right"}}></th>
              </tr></thead>
              <tbody>
                {filtered.map(item => (
                  <tr key={item.id}>
                    <td>
                      <div style={{display:"flex",alignItems:"center",gap:8}}>
                        <Icon n={item.type==="folder"?"folder":"file-text"} s={14} c="muted"/>
                        <div>
                          <div style={{fontWeight:500}}>{item.name}</div>
                          <span className="mono" style={{fontSize:10,color:"var(--muted)"}}>{item.type} · {item.size}</span>
                        </div>
                      </div>
                    </td>
                    <td>
                      <div style={{display:"flex",alignItems:"center",gap:6}}>
                        <Icon n="folder" s={12} c="muted"/>
                        <span style={{fontSize:12,color: item.folderExists ? "var(--muted)" : "var(--danger-ink)"}}>
                          {item.folder}
                          {!item.folderExists && <span className="badge danger" style={{marginLeft:6,fontSize:9.5}}>missing</span>}
                        </span>
                      </div>
                    </td>
                    <td><span className="badge">{item.type}</span></td>
                    <td>
                      <span style={{fontSize:12}}>{item.deletedByName}</span>
                    </td>
                    <td>
                      <span className="mono" style={{fontSize:11.5}}>{fmtTsShort(item.deletedAt)}</span>
                    </td>
                    <td style={{textAlign:"right"}}>
                      <button className="btn sm primary" onClick={()=>handleRestore(item)}
                        title={item.folderExists ? "Restore to original folder" : "Original folder deleted — pick a new location"}>
                        <Icon n="refresh" s={11}/> Restore
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        <div className="banner muted" style={{marginTop:14}}>
          <div className="b-ico"><Icon n="info" s={14}/></div>
          <div className="b-body">
            <b>No "Permanent delete" button anymore</b> — items live here until their project is archived. The previous permanent-delete control was prone to mistakes and has been removed.
          </div>
        </div>
      </div>

      {/* Restore-to-new-location picker — shown when original folder is missing */}
      {pickingFor && (
        <div className="modal-veil" onClick={()=>setPickingFor(null)}>
          <div className="modal" onClick={e=>e.stopPropagation()}>
            <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="folder" s={16}/>
              </div>
              <h3>Choose restore location</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">
                  The original folder <b>{pickingFor.folder}</b> no longer exists in this project. Pick a new destination for <b>{pickingFor.name}</b>.
                </div>
              </div>
              <div className="field" style={{marginBottom:0}}>
                <label>Restore to <span className="req">*</span></label>
                <select value={pickDest} onChange={e=>setPickDest(e.target.value)} autoFocus>
                  <option value="">— Pick a folder —</option>
                  {PROJECT_STRUCTURE.flatMap(f => [
                    <option key={f.id} value={f.name}>{f.name}</option>,
                    ...(f.children || []).map(c => <option key={c.id} value={`${f.name} / ${c.name}`}>↳ {c.name}</option>),
                  ])}
                </select>
              </div>
            </div>
            <div className="modal-foot">
              <button className="btn" onClick={()=>setPickingFor(null)}>Cancel</button>
              <button className="btn primary" disabled={!pickDest} onClick={()=>doRestore(pickingFor, pickDest)}>
                <Icon n="refresh" s={13}/> Restore here
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

Object.assign(window, { ProjectApprovalDetail, ProjectDraftDetail, ProjectDraftForm, RecycleBinScreen });