(() => {
  const LIST_TYPES = [
    { value: '', label: 'Choose list type' },
    { value: 'numbered', label: 'Numbered List' },
    { value: 'named', label: 'Named List' }
  ];

  let sections = [];
  let lastProjectIdentity = { name: '', location: '' };
  let activeProjectMeta = { name: '', location: '', summary: '', notes: '', projectMode: 'project_select', isBackstage: false };

  async function requestProject() {
    const data = await api('/projects');
    const projects = Array.isArray(data?.projects) ? data.projects : [];
    const activeName = String(data?.projectMode === 'system' || data?.isBackstage ? 'System' : data?.projectMode === 'project' ? data?.activeProject : '').trim();
    const activeSerial = String(data?.projectSerial || '').trim();
    const record = projects.find(project => String(project?.serialNo || '').trim() === activeSerial)
      || projects.find(project => String(project?.name || '').trim() === activeName)
      || null;

    activeProjectMeta = {
      name: activeName,
      location: String(record?.location || record?.path || '').trim(),
      summary: String(record?.summary || record?.description || '').trim(),
      notes: String(record?.notes || '').trim(),
      projectMode: String(data?.projectMode || 'project_select').trim(),
      isBackstage: Boolean(data?.isBackstage)
    };
    return activeProjectMeta;
  }

  function byId(id) { return document.getElementById(id); }

  function getActiveProjectMeta() {
    return {
      name: String(activeProjectMeta?.name || '').trim(),
      location: String(activeProjectMeta?.location || '').trim(),
      summary: String(activeProjectMeta?.summary || '').trim(),
      notes: String(activeProjectMeta?.notes || '').trim(),
      projectMode: String(activeProjectMeta?.projectMode || 'project_select').trim(),
      isBackstage: Boolean(activeProjectMeta?.isBackstage)
    };
  }

  function isUniversalProjectName(name) {
    return String(name || '').trim().toLowerCase() === 'universal';
  }

  function isSystemMode(meta = getActiveProjectMeta()) {
    return Boolean(meta?.isBackstage || String(meta?.projectMode || '').trim() === 'system' || String(meta?.name || '').trim().toLowerCase() === 'system');
  }

  function normalizeProjectDetails(details, fallback = getActiveProjectMeta()) {
    const name = String(details?.name || fallback.name || '').trim();
    return {
      name,
      location: isUniversalProjectName(name)
        ? './projects'
        : String(details?.location || fallback.location || '').trim(),
      summary: String(details?.summary || '').trim(),
      notes: String(details?.notes || '').trim()
    };
  }

  function projectFilePath(meta = getActiveProjectMeta()) {
    return isSystemMode(meta) ? 'projects/system.json' : 'project.json';
  }

  function updateOutlineFileLabel() {
    const el = byId('project-outline-file');
    if (el) el.textContent = projectFilePath();
  }

  function makeBlankProjectDocument(meta = getActiveProjectMeta()) {
    return {
      name: meta.name,
      location: meta.location,
      summary: '',
      notes: '',
      version: 2,
      savedAt: new Date().toISOString(),
      details: {
        name: meta.name,
        location: meta.location,
        summary: '',
        notes: ''
      },
      sections: []
    };
  }

  function normalizeNamedItem(item) {
    return {
      label: String(item?.label || item?.name || '').slice(0, 40),
      description: String(item?.description || item?.text || '')
    };
  }

  function normalizeSection(section) {
    const type = section?.type === 'named' ? 'named' : 'numbered';
    const title = String(section?.title || section?.name || '').trim();
    const favorite = Boolean(section?.favorite);
    const intentRepo = Boolean(section?.intentRepo);
    const rawItems = Array.isArray(section?.items) ? section.items : [];
    const items = type === 'named'
      ? rawItems.map(normalizeNamedItem)
      : rawItems.map(item => String(typeof item === 'string' ? item : item?.text || ''));
    return { title, type, favorite, intentRepo, items };
  }

  function normalizeDocument(parsed, meta = getActiveProjectMeta()) {
    const base = makeBlankProjectDocument(meta);
    const details = parsed?.details && typeof parsed.details === 'object' ? parsed.details : {};
    const canonical = {
      name: String(meta.name || parsed?.name || details?.name || '').trim(),
      location: String(meta.location || parsed?.location || details?.location || '').trim(),
      summary: String(parsed?.summary ?? details?.summary ?? '').trim(),
      notes: String(parsed?.notes ?? details?.notes ?? '').trim()
    };
    const listSections = Array.isArray(parsed?.sections)
      ? parsed.sections.map(normalizeSection).filter(section => section.title)
      : Array.isArray(parsed?.lists)
        ? parsed.lists.map(normalizeSection).filter(section => section.title)
        : base.sections;
    return {
      name: canonical.name,
      location: canonical.location,
      summary: canonical.summary,
      notes: canonical.notes,
      version: Number(parsed?.version || 2),
      savedAt: String(parsed?.savedAt || new Date().toISOString()),
      details: { ...details, ...canonical },
      sections: listSections
    };
  }

  function applyDetailsToInputs(details) {
    const setVal = (id, value) => {
      const el = byId(id);
      if (el) el.value = value || '';
    };
    setVal('proj-name', details?.name || '');
    setVal('proj-location', details?.location || '');
    setVal('proj-summary', details?.summary || '');
    setVal('proj-notes', details?.notes || '');
  }

  function syncProjectData(details) {
    activeProjectMeta = {
      ...activeProjectMeta,
      name: String(details?.name || activeProjectMeta.name || '').trim(),
      location: String(details?.location || activeProjectMeta.location || '').trim(),
      summary: String(details?.summary || '').trim(),
      notes: String(details?.notes || '').trim()
    };
  }

  function readDetailsFromInputs() {
    return {
      name: String(byId('proj-name')?.value || '').trim(),
      location: String(byId('proj-location')?.value || '').trim(),
      summary: String(byId('proj-summary')?.value || '').trim(),
      notes: String(byId('proj-notes')?.value || '').trim()
    };
  }

  function rememberProjectIdentity(details) {
    lastProjectIdentity = {
      name: String(details?.name || '').trim(),
      location: String(details?.location || '').trim()
    };
  }

  function showIdentityWarning(message) {
    const el = byId('project-identity-warning');
    if (!el) return;
    const text = String(message || '').trim();
    el.textContent = text;
    el.style.display = text ? 'block' : 'none';
  }

  function currentDetailsWithLocation(location) {
    return {
      ...readDetailsFromInputs(),
      location: String(location || '').trim()
    };
  }

  function closeLocationPicker() {
    const picker = byId('project-location-picker');
    if (picker) {
      picker.style.display = 'none';
      picker.innerHTML = '';
    }
  }

  async function openLocationPicker() {
    const picker = byId('project-location-picker');
    if (!picker) return;

    const details = readDetailsFromInputs();
    if (isSystemMode()) {
      showIdentityWarning('System location is managed by the system.');
      return;
    }
    if (!details.name || isUniversalProjectName(details.name)) {
      showIdentityWarning('Universal project location is managed by the system.');
      return;
    }

    const data = await api('/projects/eligible-folders', 'GET');
    const folders = Array.isArray(data?.folders) ? data.folders : [];
    picker.innerHTML = '';

    if (!data.ok || !folders.length) {
      picker.textContent = 'No eligible project folders found.';
      picker.style.display = 'block';
      return;
    }

    folders.forEach(folder => {
      const btn = document.createElement('button');
      btn.className = 'project-location-option';
      btn.type = 'button';
      const label = document.createElement('span');
      label.textContent = folder.location;
      const meta = document.createElement('span');
      meta.className = 'project-location-option-meta';
      meta.textContent = folder.registered ? 'registered' : (folder.hasProjectFile ? 'project.json' : 'folder');
      btn.appendChild(label);
      btn.appendChild(meta);
      btn.addEventListener('click', async () => {
        const result = await api('/projects/repair-location', 'POST', {
          name: details.name,
          location: folder.location
        });
        if (!result.ok || !result.project) {
          showIdentityWarning('Project location repair failed. Choose a valid project folder.');
          return;
        }
        const next = currentDetailsWithLocation(folder.location);
        next.name = String(result.project.name || next.name).trim();
        applyDetailsToInputs(next);
        syncProjectData(next);
        rememberProjectIdentity(next);
        closeLocationPicker();
        showIdentityWarning('');
        await saveOutlineToFile();
      });
      picker.appendChild(btn);
    });

    picker.style.display = 'block';
  }

  async function refreshProjectHealthWarning() {
    const details = readDetailsFromInputs();
    if (isSystemMode() || !details.name || isUniversalProjectName(details.name)) {
      showIdentityWarning('');
      return;
    }

    const data = await api('/projects/health', 'GET');
    const issues = Array.isArray(data?.issues) ? data.issues : [];
    const key = details.name.trim().toLowerCase();
    const match = issues.find(issue => String(issue?.name || '').trim().toLowerCase() === key);
    showIdentityWarning(match ? match.message : '');
  }

  async function saveProjectIdentityIfChanged(details) {
    const next = {
      name: String(details?.name || '').trim(),
      location: String(details?.location || '').trim(),
      summary: String(details?.summary || '').trim(),
      notes: String(details?.notes || '').trim()
    };

    if (!next.name || isUniversalProjectName(lastProjectIdentity.name)) {
      return next;
    }

    if (next.name && next.name !== lastProjectIdentity.name) {
      const result = await api('/projects/rename', 'POST', {
        currentName: lastProjectIdentity.name,
        nextName: next.name
      });

      if (!result.ok || !result.project) {
        const fallback = { ...next, name: lastProjectIdentity.name, location: lastProjectIdentity.location };
        const message = String(result.message || result.error || 'Project rename failed.').trim();
        toast(message);
        showIdentityWarning(`${message} The name was restored to the last valid project name.`);
        applyDetailsToInputs(fallback);
        return fallback;
      }

      next.name = String(result.project.name || next.name).trim();
      next.location = String(result.project.location || result.project.path || next.location).trim();
      applyDetailsToInputs(next);
      syncProjectData(next);
      rememberProjectIdentity(next);
      showIdentityWarning('');
    }

    return next;
  }

  function sectionSortScore(section) {
    if (section.favorite) return 0;
    if (section.intentRepo) return 1;
    return 2;
  }

  function activeRegisteredProject() {
    return activeProjectMeta?.name ? { ...activeProjectMeta, path: activeProjectMeta.location } : null;
  }

  function resolveRegisteredDetails(details) {
    const registered = activeRegisteredProject();
    const registeredName = String(registered?.name || '').trim();
    const registeredLocation = String(registered?.location || registered?.path || '').trim();
    const next = {
      name: registeredName || String(details?.name || '').trim(),
      location: registeredLocation || String(details?.location || '').trim(),
      summary: String(details?.summary || '').trim(),
      notes: String(details?.notes || '').trim()
    };
    if (isUniversalProjectName(next.name)) next.location = './projects';
    return next;
  }

  function sortSectionsInPlace() {
    sections.sort((a, b) => {
      const scoreDelta = sectionSortScore(a) - sectionSortScore(b);
      if (scoreDelta !== 0) return scoreDelta;
      return String(a.title || '').localeCompare(String(b.title || ''), undefined, { sensitivity: 'base' });
    });
  }

  function ensureTrailingBlank(section) {
    let changed = false;

    if (section.type === 'named') {
      if (!section.items.length || String(section.items[section.items.length - 1]?.label || '').trim() || String(section.items[section.items.length - 1]?.description || '').trim()) {
        section.items.push({ label: '', description: '' });
        changed = true;
      }
      while (
        section.items.length > 1 &&
        !String(section.items[section.items.length - 1]?.label || '').trim() &&
        !String(section.items[section.items.length - 1]?.description || '').trim() &&
        !String(section.items[section.items.length - 2]?.label || '').trim() &&
        !String(section.items[section.items.length - 2]?.description || '').trim()
      ) {
        section.items.pop();
        changed = true;
      }
      return changed;
    }

    if (!section.items.length || String(section.items[section.items.length - 1] || '').trim()) {
      section.items.push('');
      changed = true;
    }
    while (
      section.items.length > 1 &&
      !String(section.items[section.items.length - 1] || '').trim() &&
      !String(section.items[section.items.length - 2] || '').trim()
    ) {
      section.items.pop();
      changed = true;
    }
    return changed;
  }

  function ensureAllTrailingBlanks() {
    let changed = false;
    sections.forEach(section => {
      if (ensureTrailingBlank(section)) changed = true;
    });
    return changed;
  }

  function sectionExists(name, skipIndex = -1) {
    const wanted = String(name || '').trim().toLowerCase();
    if (!wanted) return false;
    return sections.some((section, index) => index !== skipIndex && String(section.title || '').trim().toLowerCase() === wanted);
  }

  function serializableSections() {
    sortSectionsInPlace();
    return sections
      .map(section => ({
        title: section.title,
        type: section.type,
        favorite: Boolean(section.favorite),
        intentRepo: Boolean(section.intentRepo),
        items: section.type === 'named'
          ? section.items.filter(item => String(item?.label || '').trim() || String(item?.description || '').trim())
          : section.items.filter(item => String(item || '').trim())
      }))
      .filter(section => section.title && section.items.length);
  }

  async function saveOutlineToFile() {
    ensureAllTrailingBlanks();
    const meta = getActiveProjectMeta();
    const systemMode = isSystemMode(meta);
    if (!systemMode && (meta.projectMode !== 'project' || !meta.name)) {
      showIdentityWarning('Select or create a project before editing project overview.');
      return { ok: false, error: 'project_overview_requires_active_project' };
    }
    sortSectionsInPlace();

    const details = systemMode
      ? { ...readDetailsFromInputs(), name: 'System', location: 'NV/' }
      : resolveRegisteredDetails(await saveProjectIdentityIfChanged(readDetailsFromInputs()));
    const listSections = serializableSections();
    const canonicalDetails = {
      name: details.name,
      location: details.location,
      summary: details.summary,
      notes: details.notes
    };
    const payload = {
      name: canonicalDetails.name,
      location: canonicalDetails.location,
      summary: canonicalDetails.summary,
      notes: canonicalDetails.notes,
      version: 2,
      savedAt: new Date().toISOString(),
      sections: listSections
    };

    syncProjectData(details);
    updateOutlineFileLabel();

    const path = projectFilePath();
    const result = await api('/projects/document/save', 'POST', {
      filePath: path,
      content: JSON.stringify(payload, null, 2)
    });

    if (!result.ok) toast('Project save failed');
    return result;
  }

  function importLegacyChecklist(parsed) {
    const legacyChecklist = Array.isArray(parsed?.checklist) ? parsed.checklist : [];
    if (!legacyChecklist.length) return;
    if (sections.some(section => String(section.title || '').trim().toLowerCase() === 'checklist')) return;
    sections.push({
      title: 'Checklist',
      type: 'numbered',
      favorite: false,
      intentRepo: false,
      items: legacyChecklist.map(item => String(item?.text || item || ''))
    });
  }

  async function loadOutlineFromFile() {
    await requestProject();
    updateOutlineFileLabel();
    const path = projectFilePath();
    if (typeof api !== 'function') { console.warn('[projectOutline] api not ready, skipping loadOutlineFromFile'); return; }

    const meta = getActiveProjectMeta();
    const systemMode = isSystemMode(meta);
    if (!systemMode && (meta.projectMode !== 'project' || !meta.name)) {
      applyDetailsToInputs({ name: '', location: '', summary: '', notes: '' });
      sections = [];
      renderLists();
      showIdentityWarning('Select or create a project to edit project overview.');
      return;
    }
    const data = await api('/read/file', 'POST', { path });
    const file = data.files?.[0];
    let parsed = null;

    if (data.ok && file?.ok && file.content) {
      try { parsed = JSON.parse(file.content); } catch { parsed = null; }
    }

    const doc = parsed ? normalizeDocument(parsed, meta) : makeBlankProjectDocument(meta);
    applyDetailsToInputs(doc.details);
    syncProjectData(doc.details);
    rememberProjectIdentity(doc.details);

    sections = Array.isArray(doc.sections) ? doc.sections.map(normalizeSection).filter(section => section.title) : [];
    importLegacyChecklist(parsed || {});
    ensureAllTrailingBlanks();
    sortSectionsInPlace();
    renderLists();
    await refreshProjectHealthWarning();
  }

  async function resetProjectOutlineToBlank() {
    const meta = getActiveProjectMeta();
    const doc = makeBlankProjectDocument(meta);
    applyDetailsToInputs(doc.details);
    syncProjectData(doc.details);
    rememberProjectIdentity(doc.details);
    sections = [];
    renderLists();
    updateOutlineFileLabel();
  }

  function removeSection(index) {
    sections.splice(index, 1);
    renderLists();
    saveOutlineToFile();
  }

  function clearSection(index) {
    const section = sections[index];
    if (!section) return;
    section.items = section.type === 'named' ? [{ label: '', description: '' }] : [''];
    renderLists();
    saveOutlineToFile();
  }

  function autoRow(section) {
    return ensureTrailingBlank(section);
  }

  function isBlankItem(section, item) {
    if (section.type === 'named') {
      return !String(item?.label || '').trim() && !String(item?.description || '').trim();
    }
    return !String(item || '').trim();
  }

  function addItemToSection(sectionIndex) {
    const section = sections[sectionIndex];
    if (!section) return;
    const last = section.items[section.items.length - 1];
    if (!section.items.length || !isBlankItem(section, last)) {
      section.items.push(section.type === 'named' ? { label: '', description: '' } : '');
    }
    renderLists();
  }

  function buildCreatorRow(atTop) {
    const wrap = document.createElement('div');
    wrap.className = 'project-lists-creator';

    const label = document.createElement('div');
    label.className = 'project-lists-add-link';
    label.textContent = '+ add list section';
    wrap.appendChild(label);

    const form = document.createElement('div');
    form.className = 'project-lists-creator-form';

    const nameInput = document.createElement('input');
    nameInput.className = 'field-input';
    nameInput.placeholder = 'List name';

    const typeSelect = document.createElement('select');
    typeSelect.className = 'field-input';
    typeSelect.innerHTML = LIST_TYPES.map(opt => `<option value="${opt.value}">${opt.label}</option>`).join('');

    const okBtn = document.createElement('button');
    okBtn.className = 'inp-btn primary';
    okBtn.textContent = 'OK';

    const cancelBtn = document.createElement('button');
    cancelBtn.className = 'inp-btn';
    cancelBtn.textContent = 'Cancel';

    const error = document.createElement('div');
    error.className = 'project-lists-error';

    function closeForm() {
      form.classList.remove('open');
      error.textContent = '';
      nameInput.value = '';
      typeSelect.value = '';
    }

    function openForm() {
      form.classList.add('open');
      setTimeout(() => nameInput.focus(), 0);
    }

    label.addEventListener('click', openForm);
    cancelBtn.addEventListener('click', closeForm);

    okBtn.addEventListener('click', async () => {
      const title = String(nameInput.value || '').trim();
      const type = String(typeSelect.value || '').trim();
      if (!title) { error.textContent = 'Name required'; return; }
      if (!type) { error.textContent = 'Choose numbered or named'; return; }
      if (sectionExists(title)) { error.textContent = 'List names must be unique'; return; }

      sections.push({
        title,
        type,
        favorite: false,
        intentRepo: false,
        items: type === 'named' ? [{ label: '', description: '' }] : ['']
      });
      closeForm();
      sortSectionsInPlace();
      renderLists();
      await saveOutlineToFile();
    });

    form.appendChild(nameInput);
    form.appendChild(typeSelect);
    form.appendChild(okBtn);
    form.appendChild(cancelBtn);
    form.appendChild(error);
    wrap.appendChild(form);

    if (atTop) openForm();
    return wrap;
  }

  function buildFlagCheckbox(labelText, checked, onChange) {
    const wrap = document.createElement('label');
    wrap.className = 'project-list-flag';

    const input = document.createElement('input');
    input.type = 'checkbox';
    input.checked = Boolean(checked);
    input.addEventListener('change', onChange);

    const text = document.createElement('span');
    text.textContent = labelText;

    wrap.appendChild(input);
    wrap.appendChild(text);
    return wrap;
  }

  function buildNamedRow(section, sectionIndex, item, itemIndex) {
    const row = document.createElement('div');
    row.className = 'project-list-row named';

    const label = document.createElement('input');
    label.className = 'field-input';
    label.placeholder = 'name';
    label.maxLength = 24;
    label.value = item?.label || '';
    label.addEventListener('input', () => {
      section.items[itemIndex] = { ...section.items[itemIndex], label: label.value };
    });
    label.addEventListener('blur', () => saveOutlineToFile());

    const desc = document.createElement('textarea');
    desc.className = 'field-textarea project-list-description-text';
    desc.placeholder = 'Description';
    desc.value = item?.description || '';
    desc.rows = 1;
    setTimeout(() => autosizeProjectListTextArea(desc), 0);
    desc.addEventListener('input', () => {
      section.items[itemIndex] = { ...section.items[itemIndex], description: desc.value };
      autosizeProjectListTextArea(desc);
    });
    desc.addEventListener('blur', () => saveOutlineToFile());

    row.appendChild(label);
    row.appendChild(desc);
    return row;
  }

  function autosizeProjectListTextArea(el) {
    if (!el) return;
    const lineHeight = 18;
    const maxLines = 3;
    el.style.height = 'auto';
    const next = Math.min(el.scrollHeight, lineHeight * maxLines + 12);
    el.style.height = `${next}px`;
  }

  function buildNumberedRow(section, sectionIndex, value, itemIndex) {
    const row = document.createElement('div');
    row.className = 'project-list-row numbered';

    const index = document.createElement('div');
    index.className = 'project-list-index';
    index.textContent = String(itemIndex + 1);

    const input = document.createElement('textarea');
    input.className = 'field-textarea project-list-numbered-text';
    input.placeholder = 'Add checklist item...';
    input.value = value || '';
    input.rows = 1;
    input.maxLength = 240;
    setTimeout(() => autosizeProjectListTextArea(input), 0);
    input.addEventListener('input', () => {
      section.items[itemIndex] = input.value;
      autosizeProjectListTextArea(input);
    });
    input.addEventListener('blur', () => saveOutlineToFile());

    row.appendChild(index);
    row.appendChild(input);
    return row;
  }

  function buildSection(section, sectionIndex) {
    const wrap = document.createElement('div');
    wrap.className = 'project-list-section';

    const head = document.createElement('div');
    head.className = 'project-list-head';

    const title = document.createElement('input');
    title.className = 'project-list-title-input';
    title.value = section.title;
    title.placeholder = 'List title';
    title.addEventListener('input', () => {
      section.title = title.value;
    });
    title.addEventListener('blur', async () => {
      const next = String(title.value || '').trim();
      if (!next) {
        title.value = section.title;
        return;
      }
      if (sectionExists(next, sectionIndex)) {
        toast('List names must be unique');
        title.value = section.title;
        return;
      }
      section.title = next;
      title.value = next;
      sortSectionsInPlace();
      renderLists();
      await saveOutlineToFile();
    });

    const actions = document.createElement('div');
    actions.className = 'project-list-actions';

    const favoriteToggle = buildFlagCheckbox('favorite', section.favorite, async () => {
      section.favorite = !section.favorite;
      sortSectionsInPlace();
      renderLists();
      await saveOutlineToFile();
    });

    const intentToggle = buildFlagCheckbox('intent repo', section.intentRepo, async () => {
      section.intentRepo = !section.intentRepo;
      sortSectionsInPlace();
      renderLists();
      await saveOutlineToFile();
    });

    const clearLink = document.createElement('button');
    clearLink.className = 'outline-link';
    clearLink.textContent = 'clear';
    clearLink.addEventListener('click', () => clearSection(sectionIndex));

    const removeLink = document.createElement('button');
    removeLink.className = 'outline-link';
    removeLink.textContent = 'remove section';
    removeLink.addEventListener('click', () => removeSection(sectionIndex));

    actions.appendChild(favoriteToggle);
    actions.appendChild(intentToggle);
    actions.appendChild(clearLink);
    actions.appendChild(removeLink);

    head.appendChild(title);
    head.appendChild(actions);
    wrap.appendChild(head);

    const body = document.createElement('div');
    body.className = 'project-list-body';
    ensureTrailingBlank(section);

    section.items.forEach((item, itemIndex) => {
      body.appendChild(section.type === 'named'
        ? buildNamedRow(section, sectionIndex, item, itemIndex)
        : buildNumberedRow(section, sectionIndex, item, itemIndex));
    });

    wrap.appendChild(body);

    const addItemBtn = document.createElement('button');
    addItemBtn.className = 'outline-link';
    addItemBtn.type = 'button';
    addItemBtn.textContent = '+ item';
    addItemBtn.addEventListener('click', () => addItemToSection(sectionIndex));
    wrap.appendChild(addItemBtn);

    return wrap;
  }

  function renderLists() {
    const root = byId('project-outline-sections');
    const addLink = byId('project-outline-add-link');
    const checklistLabel = byId('project-checklist-label');
    const checklistList = byId('project-checklist-list');
    if (!root) return;

    sortSectionsInPlace();

    root.innerHTML = '';
    if (checklistLabel) checklistLabel.style.display = 'none';
    if (checklistList) checklistList.style.display = 'none';
    if (addLink) addLink.style.display = 'none';

    root.appendChild(buildCreatorRow(sections.length === 0));
    sections.forEach((section, index) => root.appendChild(buildSection(section, index)));
    if (sections.length > 0) root.appendChild(buildCreatorRow(false));
  }

  function bootProjectOutline() {
    const locationInput = byId('proj-location');
    if (locationInput) {
      locationInput.readOnly = true;
      locationInput.title = 'Project location is managed by project settings.';
    }

    byId('proj-location-choose-btn')?.addEventListener('click', openLocationPicker);
    byId('proj-name')?.addEventListener('blur', () => saveOutlineToFile());
    byId('proj-summary')?.addEventListener('blur', () => saveOutlineToFile());
    byId('proj-notes')?.addEventListener('blur', () => saveOutlineToFile());
    loadOutlineFromFile();
  }

  window.ProjectOutline = { requestProject, loadProject: loadOutlineFromFile };
  window.reloadProjectOutlineFromFile = loadOutlineFromFile;
  window.saveProjectOutlineToFile = saveOutlineToFile;
  window.resetProjectOutlineToBlank = resetProjectOutlineToBlank;

  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', bootProjectOutline);
  else bootProjectOutline();
})();