/* ============ SOP Templates — builder + flows (no version / no status / no project linkage) ============ */

const TEMPLATES_SEED = [
  { id:"T-FS-STD",    name:"FS Audit — Standard",         description:"Standard statutory financial-statement audit. Use for FS audits across all industries.", updated:"2026-05-20T15:00:00" },
  { id:"T-TAX-PND50", name:"Tax Compliance — Thai PND50", description:"Annual tax compliance filing PND50 for Thai corporates.",                                  updated:"2026-05-15T11:00:00" },
  { id:"T-IC-SOX",    name:"Internal Control — SOX-lite", description:"Lightweight SOX walkthrough — revenue, treasury, payroll.",                               updated:"2026-05-22T06:30:00" },
  { id:"T-INT-QTR",   name:"Interim Review — Quarterly",  description:"Quarterly interim review focused on cut-off testing and aging.",                          updated:"2026-04-22T10:00:00" },
];

/* Folders per template — Proud Workpapers PDF slide 7 (CA / RA / RAR / AC / AR).
   Supports nesting via parentId. */
const FOLDERS_SEED = {
  "T-FS-STD": [
    { id:"f-ca",          name:"01 — Client Acceptance (CA)",            parentId:null },
    { id:"f-ca-ind",      name:"01.1 — Independence Check",              parentId:"f-ca" },
    { id:"f-ca-letter",   name:"01.2 — Engagement Letter",               parentId:"f-ca" },
    { id:"f-ra",          name:"02 — Risk Assessment (RA)",              parentId:null },
    { id:"f-ra-strat",    name:"02.1 — Strategy & Risk Memo",            parentId:"f-ra" },
    { id:"f-ra-mat",      name:"02.2 — Materiality",                     parentId:"f-ra" },
    { id:"f-ra-risk",     name:"02.3 — Risk Identification",             parentId:"f-ra" },
    { id:"f-rar",         name:"03 — Response to Assessed Risks (RAR)",  parentId:null },
    { id:"f-ac",          name:"04 — Audit Conclusion (AC)",             parentId:null },
    { id:"f-ar",          name:"05 — Audit Reporting (AR)",              parentId:null },
  ],
  "T-TAX-PND50": [
    { id:"f-tax-prep",   name:"Tax Preparation",  parentId:null },
    { id:"f-tax-review", name:"Review & Filing",  parentId:null },
  ],
  "T-IC-SOX": [
    { id:"f-ic-rev",  name:"Revenue Controls",  parentId:null },
    { id:"f-ic-trsy", name:"Treasury Controls", parentId:null },
    { id:"f-ic-pay",  name:"Payroll Controls",  parentId:null },
  ],
  "T-INT-QTR": [
    { id:"f-int-pln", name:"Planning",  parentId:null },
    { id:"f-int-fld", name:"Fieldwork", parentId:null },
  ],
};

/* WPIDs by folder id — re-keyed to the new CA/RA folder IDs */
const WPIDS_SEED = {
  "f-ra-mat": [
    { id:"w-001", name:"Overall audit strategy memo",  type:"docx" },
    { id:"w-002", name:"Materiality calculation",       type:"xlsx" },
    { id:"w-003", name:"Risk & response matrix",        type:"xlsx" },
    { id:"w-004", name:"Team briefing minutes",         type:"pdf"  },
    { id:"w-005", name:"Prior year engagement summary", type:"docx" },
    { id:"w-006", name:"Client org chart",              type:"pdf"  },
  ],
  "f-ca-ind": [
    { id:"w-010", name:"Independence declaration",   type:"pdf"  },
    { id:"w-011", name:"Conflict-of-interest check", type:"docx" },
  ],
  "f-ca-letter": [
    { id:"w-012", name:"Engagement letter", type:"pdf"  },
    { id:"w-013", name:"Fee schedule",      type:"xlsx" },
  ],
};

const FILE_TYPES = [
  { v:"docx", label:"Word document (.docx)" },
  { v:"xlsx", label:"Excel spreadsheet (.xlsx)" },
  { v:"pdf",  label:"PDF (.pdf)" },
  { v:"pptx", label:"PowerPoint (.pptx)" },
  { v:"txt",  label:"Plain text (.txt)" },
  { v:"any",  label:"Any file" },
];
const fileLabel = (t) => (FILE_TYPES.find(f => f.v===t) || {label:`.${t}`}).label;
const fileIc = (t) => t==="xlsx" ? "grid" : (t==="docx" || t==="pptx") ? "file-text" : "file";

const uid = (p) => p + "-" + Math.random().toString(36).slice(2,7);

/* ====== Modals ====== */

const NewTemplateModal = ({ onClose, onCreate }) => {
  const [name, setName] = React.useState("");
  const [desc, setDesc] = React.useState("");
  const valid = name.trim().length >= 2;
  return (
    <div className="modal-veil" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <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="template" s={16} />
          </div>
          <h3>New SOP Template</h3>
        </div>
        <div className="modal-body">
          <div className="banner muted" style={{ marginBottom:16 }}>
            <div className="b-ico"><Icon n="info" s={14}/></div>
            <div className="b-body">
              The new template starts <b>empty</b> — add folders, subfolders, and WPIDs in the builder. It's usable immediately once you save.
            </div>
          </div>
          <div className="field">
            <label>Template name <span className="req">*</span></label>
            <input type="text" value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Quarterly Interim Review" autoFocus />
          </div>
          <div className="field" style={{ marginBottom:0 }}>
            <label>Description</label>
            <textarea value={desc} onChange={e => setDesc(e.target.value)} placeholder="What is this template for, and when should it be used?" />
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn primary" disabled={!valid} onClick={() => onCreate({ name:name.trim(), description:desc.trim() })}>
            <Icon n="plus" s={13}/> Create template
          </button>
        </div>
      </div>
    </div>
  );
};

const DuplicateTemplateModal = ({ source, onClose, onDuplicate }) => {
  const [name, setName] = React.useState(`${source.name} (copy)`);
  const [desc, setDesc] = React.useState(source.description || "");
  const valid = name.trim().length >= 2;
  return (
    <div className="modal-veil" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div style={{ width:32, height:32, borderRadius:8, background:"var(--panel-2)", color:"var(--ink-2)", display:"grid", placeItems:"center" }}>
            <Icon n="copy" s={16} />
          </div>
          <h3>Duplicate template</h3>
        </div>
        <div className="modal-body">
          <div className="banner muted" style={{ marginBottom:16 }}>
            <div className="b-ico"><Icon n="info" s={14} /></div>
            <div className="b-body">
              All folders, subfolders, and WPIDs from <b>{source.name}</b> will be copied. Edit the name and description below — the copy is usable immediately.
            </div>
          </div>
          <div className="field">
            <label>Name <span className="req">*</span></label>
            <input type="text" value={name} onChange={e => setName(e.target.value)} autoFocus />
          </div>
          <div className="field" style={{ marginBottom:0 }}>
            <label>Description</label>
            <textarea value={desc} onChange={e => setDesc(e.target.value)} />
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn primary" disabled={!valid} onClick={() => onDuplicate({ name:name.trim(), description:desc.trim() })}>
            <Icon n="copy" s={13}/> Duplicate
          </button>
        </div>
      </div>
    </div>
  );
};

const EditTemplateModal = ({ source, onClose, onSave }) => {
  const [name, setName] = React.useState(source.name);
  const [desc, setDesc] = React.useState(source.description || "");
  const valid = name.trim().length >= 2;
  return (
    <div className="modal-veil" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <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="edit-3" s={16} />
          </div>
          <h3>Edit template</h3>
        </div>
        <div className="modal-body">
          <div className="field">
            <label>Name <span className="req">*</span></label>
            <input type="text" value={name} onChange={e => setName(e.target.value)} autoFocus />
          </div>
          <div className="field" style={{ marginBottom:0 }}>
            <label>Description</label>
            <textarea value={desc} onChange={e => setDesc(e.target.value)} />
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn primary" disabled={!valid} onClick={() => onSave({ name:name.trim(), description:desc.trim() })}>
            <Icon n="check" s={13}/> Save changes
          </button>
        </div>
      </div>
    </div>
  );
};

/* Folder create/rename — supports picking a parent (for subfolders) */
const FolderFormModal = ({ mode, initial, parentChain, allFolders, defaultParentId, onClose, onSave }) => {
  const [name, setName] = React.useState(initial?.name || "");
  const [parentId, setParentId] = React.useState(initial?.parentId ?? defaultParentId ?? null);
  const valid = name.trim().length >= 2;

  // For rename mode, we only allow editing the name (not moving).
  const isRename = mode === "rename";
  const title = mode === "subfolder"
    ? "New subfolder"
    : mode === "rename"
      ? "Rename folder"
      : "New folder";

  return (
    <div className="modal-veil" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <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={mode==="rename" ? "edit-3" : "folder"} s={16}/>
          </div>
          <h3>{title}</h3>
        </div>
        <div className="modal-body">
          {!isRename && (
            <div className="field">
              <label>Parent folder</label>
              <select value={parentId || ""} onChange={e => setParentId(e.target.value || null)}>
                <option value="">— Root (top-level)</option>
                {allFolders.map(f => (
                  <option key={f.id} value={f.id}>
                    {"\u2003".repeat((parentChain[f.id] || 0))}↳ {f.name}
                  </option>
                ))}
              </select>
              <div className="help">Pick a parent to create a subfolder, or leave as Root for a top-level folder.</div>
            </div>
          )}
          <div className="field" style={{ marginBottom:0 }}>
            <label>Folder name <span className="req">*</span></label>
            <input type="text" value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Audit Plan" autoFocus />
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn primary" disabled={!valid} onClick={() => onSave({ name:name.trim(), parentId })}>
            <Icon n="check" s={13}/> {mode==="rename" ? "Save" : "Create folder"}
          </button>
        </div>
      </div>
    </div>
  );
};

/* WPID add / edit */
const WpidFormModal = ({ initial, folderName, onClose, onSave, mode = "add" }) => {
  const [name, setName] = React.useState(initial?.name || "");
  const [type, setType] = React.useState(initial?.type || "docx");
  const valid = name.trim().length >= 2;
  return (
    <div className="modal-veil" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <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={mode === "add" ? "plus" : "edit-3"} s={16} />
          </div>
          <h3>{mode === "add" ? "Add WPID" : "Edit WPID"}</h3>
        </div>
        <div className="modal-body">
          <div className="field">
            <label>WPID name <span className="req">*</span></label>
            <input type="text" value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Materiality calculation" autoFocus />
            <div className="help">Will be added to folder: <b>{folderName}</b></div>
          </div>
          <div className="field" style={{ marginBottom:0 }}>
            <label>File type <span className="req">*</span></label>
            <select value={type} onChange={e => setType(e.target.value)}>
              {FILE_TYPES.map(f => <option key={f.v} value={f.v}>{f.label}</option>)}
            </select>
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn primary" disabled={!valid} onClick={() => onSave({ name:name.trim(), type })}>
            <Icon n="check" s={13}/> {mode === "add" ? "Add WPID" : "Save changes"}
          </button>
        </div>
      </div>
    </div>
  );
};

/* ====== Folder tree (recursive) ====== */
const FolderNode = ({ node, depth, expanded, setExpanded, selected, setSelected, wpidsByFolder, onAddSub, onRename, onDelete }) => {
  const hasKids = node.children && node.children.length > 0;
  const isOpen = expanded[node.id] ?? true;
  const isActive = selected === node.id;
  const count = (wpidsByFolder[node.id] || []).length;

  return (
    <>
      <div className={"tpl-folder " + (isActive ? "active" : "")} style={{ paddingLeft: 10 + depth*14 }}>
        <button className="tpl-folder-chev" onClick={(e)=>{ e.stopPropagation(); if (hasKids) setExpanded({ ...expanded, [node.id]: !isOpen }); }}>
          {hasKids ? <Icon n={isOpen ? "chev-d" : "chev-r"} s={11} c="muted"/> : <span style={{display:"inline-block",width:11}}/>}
        </button>
        <button className="tpl-folder-body" onClick={()=>setSelected(node.id)}>
          <Icon n={hasKids && isOpen ? "folder-open" : "folder"} s={14} c="muted"/>
          <span style={{ flex:1, textAlign:"left", minWidth:0 }} className="truncate">{node.name}</span>
          <span className="mono tpl-folder-count">{count}</span>
        </button>
        <div className="tpl-folder-actions">
          <button className="icon-btn-xs" title="Add subfolder" onClick={()=>onAddSub(node.id)}><Icon n="plus" s={11}/></button>
          <button className="icon-btn-xs" title="Rename" onClick={()=>onRename(node)}><Icon n="edit-3" s={11}/></button>
          <button className="icon-btn-xs danger" title="Delete" onClick={()=>onDelete(node)}><Icon n="trash" s={11}/></button>
        </div>
      </div>
      {hasKids && isOpen && node.children.map(child => (
        <FolderNode
          key={child.id}
          node={child}
          depth={depth+1}
          expanded={expanded}
          setExpanded={setExpanded}
          selected={selected}
          setSelected={setSelected}
          wpidsByFolder={wpidsByFolder}
          onAddSub={onAddSub}
          onRename={onRename}
          onDelete={onDelete}
        />
      ))}
    </>
  );
};

/* ====== Templates Screen ====== */
const TemplatesScreen = ({ state, nav }) => {
  const [templates, setTemplates] = React.useState(TEMPLATES_SEED);
  const [foldersByTpl, setFoldersByTpl] = React.useState(FOLDERS_SEED);
  const [wpidsByFolder, setWpidsByFolder] = React.useState(WPIDS_SEED);

  const [tplId, setTplId] = React.useState("T-FS-STD");
  const [selectedFolder, setSelectedFolder] = React.useState("f-plan-audit");
  const [expanded, setExpanded] = React.useState({});

  const [showNew, setShowNew] = React.useState(false);
  const [showDup, setShowDup] = React.useState(false);
  const [showEdit, setShowEdit] = React.useState(false);
  const [folderModal, setFolderModal] = React.useState(null); // {mode, initial?, defaultParentId?}
  const [wpidModal, setWpidModal] = React.useState(null);

  const tpl = templates.find(t => t.id === tplId) || templates[0];
  const flatFolders = foldersByTpl[tplId] || [];
  const currentFolder = flatFolders.find(f => f.id === selectedFolder);
  const currentWpids = wpidsByFolder[selectedFolder] || [];

  /* Build a tree from flat folders */
  const buildTree = (flat) => {
    const byId = Object.fromEntries(flat.map(f => [f.id, { ...f, children:[] }]));
    const roots = [];
    flat.forEach(f => {
      if (f.parentId && byId[f.parentId]) byId[f.parentId].children.push(byId[f.id]);
      else roots.push(byId[f.id]);
    });
    return roots;
  };
  const tree = React.useMemo(() => buildTree(flatFolders), [flatFolders]);

  /* Depth map (for parent-picker indentation) */
  const depthOf = (id, chain={}) => {
    const f = flatFolders.find(x => x.id === id);
    if (!f) return 0;
    if (chain[id] !== undefined) return chain[id];
    const d = f.parentId ? depthOf(f.parentId, chain) + 1 : 0;
    chain[id] = d;
    return d;
  };
  const depthMap = {};
  flatFolders.forEach(f => depthOf(f.id, depthMap));

  /* Counts (derived) */
  const folderCount = flatFolders.length;
  const wpidCount = flatFolders.reduce((sum, f) => sum + (wpidsByFolder[f.id]?.length || 0), 0);

  /* ====== Mutations ====== */
  const now = () => new Date('2026-05-22T10:00:00').toISOString();

  const touchTemplate = () => setTemplates(ts => ts.map(t => t.id === tplId ? { ...t, updated: now() } : t));

  const createTemplate = ({ name, description }) => {
    const id = "T-" + uid("NEW").toUpperCase();
    setTemplates(ts => [{ id, name, description, updated: now() }, ...ts]);
    setFoldersByTpl(fs => ({ ...fs, [id]: [] }));
    setTplId(id);
    setSelectedFolder(null);
    nav.toast(`Template "${name}" created`, "ok");
  };

  const duplicateTemplate = ({ name, description }) => {
    const newId = "T-" + uid("DUP").toUpperCase();
    /* Deep-copy folders & wpids with new ids */
    const srcFolders = foldersByTpl[tplId] || [];
    const idMap = {};
    const newFolders = srcFolders.map(f => {
      const newFid = uid("f");
      idMap[f.id] = newFid;
      return { id:newFid, name:f.name, parentId: null };
    });
    /* Fix parent references */
    srcFolders.forEach((f, i) => {
      if (f.parentId) newFolders[i].parentId = idMap[f.parentId];
    });
    /* Copy wpids per folder */
    const newWpidsByFolder = {};
    srcFolders.forEach(f => {
      const src = wpidsByFolder[f.id] || [];
      if (src.length) newWpidsByFolder[idMap[f.id]] = src.map(w => ({ ...w, id: uid("w") }));
    });

    setTemplates(ts => [{ id:newId, name, description, updated:now() }, ...ts]);
    setFoldersByTpl(fs => ({ ...fs, [newId]: newFolders }));
    setWpidsByFolder(ws => ({ ...ws, ...newWpidsByFolder }));
    setTplId(newId);
    setSelectedFolder(newFolders[0]?.id || null);
    nav.toast(`Duplicated to "${name}"`, "ok");
  };

  const saveTemplateMeta = ({ name, description }) => {
    setTemplates(ts => ts.map(t => t.id === tplId ? { ...t, name, description, updated: now() } : t));
    nav.toast("Template updated", "ok");
  };

  /* Folder ops */
  const createFolder = ({ name, parentId }) => {
    const id = uid("f");
    setFoldersByTpl(fs => ({ ...fs, [tplId]: [...(fs[tplId] || []), { id, name, parentId: parentId || null }] }));
    if (parentId) setExpanded(e => ({ ...e, [parentId]: true }));
    setSelectedFolder(id);
    touchTemplate();
    nav.toast(parentId ? "Subfolder added" : "Folder added", "ok");
  };
  const renameFolder = (id, { name }) => {
    setFoldersByTpl(fs => ({ ...fs, [tplId]: fs[tplId].map(f => f.id === id ? { ...f, name } : f) }));
    touchTemplate();
    nav.toast("Folder renamed", "ok");
  };
  const deleteFolder = (id) => {
    /* Collect this folder + all descendants */
    const removeIds = new Set([id]);
    let added = true;
    while (added) {
      added = false;
      flatFolders.forEach(f => { if (f.parentId && removeIds.has(f.parentId) && !removeIds.has(f.id)) { removeIds.add(f.id); added = true; } });
    }
    setFoldersByTpl(fs => ({ ...fs, [tplId]: fs[tplId].filter(f => !removeIds.has(f.id)) }));
    setWpidsByFolder(ws => {
      const out = { ...ws };
      removeIds.forEach(fid => delete out[fid]);
      return out;
    });
    if (removeIds.has(selectedFolder)) setSelectedFolder(null);
    touchTemplate();
    nav.toast("Folder removed", "warn");
  };

  /* WPID ops */
  const addWpid = ({ name, type }) => {
    const id = uid("w");
    setWpidsByFolder(prev => ({ ...prev, [selectedFolder]: [...(prev[selectedFolder] || []), { id, name, type }] }));
    touchTemplate();
    nav.toast("WPID added", "ok");
  };
  const updateWpid = (id, patch) => {
    setWpidsByFolder(prev => ({
      ...prev,
      [selectedFolder]: prev[selectedFolder].map(w => w.id === id ? { ...w, ...patch } : w),
    }));
    touchTemplate();
    nav.toast("WPID updated", "ok");
  };
  const removeWpid = (id) => {
    setWpidsByFolder(prev => ({
      ...prev,
      [selectedFolder]: prev[selectedFolder].filter(w => w.id !== id),
    }));
    touchTemplate();
    nav.toast("WPID removed", "warn");
  };

  return (
    <>
      <div className="page-head tight">
        <div className="page-title-row">
          <h1 className="page-title">SOP Templates</h1>
          <span className="badge mono">{templates.length} templates</span>
          <div className="page-actions">
            <button className="btn primary" onClick={() => setShowNew(true)}><Icon n="plus" s={13}/> New template</button>
          </div>
        </div>
      </div>

      {/* Template chooser tabs — the catalog is small, so no search box */}
      <div className="tabbar tpl-tabbar">
        {templates.map(t => (
          <button key={t.id} className={"tab " + (tplId === t.id ? "active" : "")} onClick={() => setTplId(t.id)}>
            <Icon n="template" s={12}/>
            {t.name}
          </button>
        ))}
        <button className="tab" style={{ color:"var(--muted)" }} onClick={() => setShowNew(true)}>
          <Icon n="plus" s={12}/>
        </button>
      </div>

      <div className="page-body">
        {/* Summary card — no Version, no Status, no In-use */}
        <div className="card tpl-summary">
          <div className="tpl-summary-main">
            <div style={{ fontSize:16, fontWeight:600 }}>{tpl.name}</div>
            <div style={{ fontSize:12.5, color:"var(--ink-2)", marginTop:6, lineHeight:1.5, maxWidth:680 }}>
              {tpl.description || <span className="muted">No description.</span>}
            </div>
            <div className="mono" style={{ fontSize:11, color:"var(--muted)", marginTop:8 }}>
              Last edited {fmtTs(tpl.updated)}
            </div>
          </div>
          <div className="tpl-summary-cell">
            <div className="section-label">Folders</div>
            <div className="tpl-stat mono">{folderCount}</div>
          </div>
          <div className="tpl-summary-cell">
            <div className="section-label">WPIDs</div>
            <div className="tpl-stat mono">{wpidCount}</div>
          </div>
          <div className="tpl-summary-actions">
            <button className="btn sm" onClick={() => setShowDup(true)}><Icon n="copy" s={12}/> Duplicate</button>
            <button className="btn sm primary" onClick={() => setShowEdit(true)}><Icon n="edit-3" s={12}/> Edit</button>
          </div>
        </div>

        <div className="tpl-builder">
            {/* Folders tree */}
            <div className="card">
              <div className="card-head">
                <div className="card-title">Folders</div>
                <button className="btn sm primary" onClick={() => setFolderModal({ mode:"folder", defaultParentId:null })}>
                  <Icon n="plus" s={12}/> New folder
                </button>
              </div>
              <div className="tpl-folder-tree">
                {tree.length === 0 ? (
                  <div style={{ padding:"28px 16px", textAlign:"center", color:"var(--muted)", fontSize:12.5 }}>
                    <div style={{ marginBottom:10, fontWeight:600, color:"var(--ink)" }}>No folders yet</div>
                    <div style={{ marginBottom:14 }}>Build the structure by adding folders — each can hold subfolders and WPIDs.</div>
                    <button className="btn primary sm" onClick={() => setFolderModal({ mode:"folder", defaultParentId:null })}>
                      <Icon n="plus" s={12}/> Add first folder
                    </button>
                  </div>
                ) : (
                  tree.map(node => (
                    <FolderNode
                      key={node.id}
                      node={node}
                      depth={0}
                      expanded={expanded}
                      setExpanded={setExpanded}
                      selected={selectedFolder}
                      setSelected={setSelectedFolder}
                      wpidsByFolder={wpidsByFolder}
                      onAddSub={(parentId) => setFolderModal({ mode:"subfolder", defaultParentId:parentId })}
                      onRename={(node) => setFolderModal({ mode:"rename", initial:node })}
                      onDelete={(node) => deleteFolder(node.id)}
                    />
                  ))
                )}
              </div>
            </div>

            {/* WPIDs in selected folder */}
            <div className="card">
              {currentFolder ? (
                <>
                  <div className="card-head">
                    <div style={{ minWidth:0 }}>
                      <div className="card-title">{currentFolder.name}</div>
                      <div className="card-sub">{currentWpids.length} WPID{currentWpids.length !== 1 ? "s" : ""} · each is a working-paper slot in projects using this template</div>
                    </div>
                    <div style={{ display:"flex", gap:6 }}>
                      <button className="btn sm" onClick={() => setFolderModal({ mode:"rename", initial: currentFolder })}>
                        <Icon n="edit-3" s={12}/> Rename folder
                      </button>
                      <button className="btn sm primary" onClick={() => setWpidModal({ mode:"add" })}>
                        <Icon n="plus" s={12}/> Add WPID
                      </button>
                    </div>
                  </div>
                  {currentWpids.length === 0 ? (
                    <EmptyState
                      icon="file"
                      title="No WPIDs in this folder yet"
                      sub="A WPID is a working-paper slot — give it a name and pick the expected file type."
                      cta={<button className="btn primary" onClick={() => setWpidModal({ mode:"add" })}><Icon n="plus" s={13}/> Add first WPID</button>}
                    />
                  ) : (
                    <table className="tbl">
                      <thead><tr>
                        <th style={{ width:40 }}></th>
                        <th>Name</th>
                        <th style={{ width:240 }}>File type</th>
                        <th style={{ width:120, textAlign:"right" }}></th>
                      </tr></thead>
                      <tbody>
                        {currentWpids.map(w => (
                          <tr key={w.id}>
                            <td><Icon n={fileIc(w.type)} s={15} c="muted"/></td>
                            <td style={{ fontWeight:500 }}>{w.name}</td>
                            <td><span style={{ fontSize:12, color:"var(--ink-2)" }}>{fileLabel(w.type)}</span></td>
                            <td style={{ textAlign:"right" }}>
                              <div style={{ display:"inline-flex", gap:6 }}>
                                <button className="btn sm ghost" title="Edit" onClick={() => setWpidModal({ mode:"edit", target:w })}><Icon n="edit-3" s={12}/></button>
                                <button className="btn sm ghost" title="Remove" onClick={() => removeWpid(w.id)} style={{ color:"var(--danger-ink)" }}><Icon n="trash" s={12}/></button>
                              </div>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  )}
                </>
              ) : (
                <EmptyState
                  icon="folder"
                  title="Pick a folder"
                  sub="Select a folder from the tree on the left to view and edit its WPIDs."
                />
              )}
            </div>
          </div>
      </div>

      {/* Modals */}
      {showNew && <NewTemplateModal onClose={() => setShowNew(false)} onCreate={(p) => { setShowNew(false); createTemplate(p); }} />}
      {showDup && <DuplicateTemplateModal source={tpl} onClose={() => setShowDup(false)} onDuplicate={(p) => { setShowDup(false); duplicateTemplate(p); }} />}
      {showEdit && <EditTemplateModal source={tpl} onClose={() => setShowEdit(false)} onSave={(p) => { setShowEdit(false); saveTemplateMeta(p); }} />}

      {folderModal && <FolderFormModal
        mode={folderModal.mode}
        initial={folderModal.initial}
        allFolders={flatFolders}
        parentChain={depthMap}
        defaultParentId={folderModal.defaultParentId}
        onClose={() => setFolderModal(null)}
        onSave={(p) => {
          if (folderModal.mode === "rename") renameFolder(folderModal.initial.id, p);
          else createFolder(p);
          setFolderModal(null);
        }}
      />}

      {wpidModal && <WpidFormModal
        mode={wpidModal.mode}
        initial={wpidModal.target}
        folderName={currentFolder?.name || ""}
        onClose={() => setWpidModal(null)}
        onSave={(p) => {
          if (wpidModal.mode === "add") addWpid(p);
          else updateWpid(wpidModal.target.id, p);
          setWpidModal(null);
        }}
      />}
    </>
  );
};

Object.assign(window, { TemplatesScreen });
