/* src/app.jsx — shell: library, editor, controls, roadmap editor, accounts */
const { useState, useEffect, useLayoutEffect, useMemo, useRef } = React;

// tiny global toast bus — simplest cross-component signal in this no-build setup.
// Editor (cleanup errors) and App (save/rate-limit messages) both call window.showToast().
window.showToast = (message, kind) => {
  window.dispatchEvent(new CustomEvent('onepage:toast', { detail: { message, kind: kind || 'info' } }));
};
function ToastHost() {
  const [toast, setToast] = useState(null);
  const timerRef = useRef(null);
  useEffect(() => {
    const onToast = (e) => {
      setToast({ id: Date.now(), ...e.detail });
      clearTimeout(timerRef.current);
      timerRef.current = setTimeout(() => setToast(null), 5000);
    };
    window.addEventListener('onepage:toast', onToast);
    return () => { window.removeEventListener('onepage:toast', onToast); clearTimeout(timerRef.current); };
  }, []);
  if (!toast) return null;
  return (
    <div className={toast.kind === 'error' ? 'toast toast--error' : 'toast'} role={toast.kind === 'error' ? 'alert' : 'status'}>
      {toast.message}
    </div>
  );
}

function useDialogFocus(cardRef, onClose) {
  const closeRef = useRef(onClose); closeRef.current = onClose;
  useEffect(() => {
    const previous = document.activeElement;
    const preferred = cardRef.current && cardRef.current.querySelector('[autofocus], button, input');
    if (preferred) preferred.focus();
    const onKey = (event) => {
      if (event.key === 'Escape' && closeRef.current) { event.preventDefault(); closeRef.current(); return; }
      if (event.key !== 'Tab' || !cardRef.current) return;
      const focusable = [...cardRef.current.querySelectorAll('button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), a[href]')];
      if (!focusable.length) return;
      const first = focusable[0], last = focusable[focusable.length - 1];
      if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
      else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
    };
    window.addEventListener('keydown', onKey);
    return () => { window.removeEventListener('keydown', onKey); if (previous && previous.focus) previous.focus(); };
  }, []);
}

/* ---------- Confirm dialog (replaces window.confirm for destructive actions) ---------- */
function ConfirmDialog({ title, body, confirmLabel, onConfirm, onCancel }) {
  const cardRef = useRef(null);
  const titleId = React.useId();
  useDialogFocus(cardRef, onCancel);
  return (
    <div className="modal" onMouseDown={onCancel}>
      <div ref={cardRef} className="modal__card" role="dialog" aria-modal="true" aria-labelledby={titleId} onMouseDown={e => e.stopPropagation()}>
        <h3 id={titleId}>{title}</h3>
        {body && <p className="modal__lead">{body}</p>}
        <div className="modal__row">
          <span style={{ flex: 1 }} />
          <button className="btn btn--ghost btn--sm" onClick={onCancel}>Cancel</button>
          <button className="btn btn--danger btn--sm" onClick={onConfirm}>{confirmLabel || 'Delete'}</button>
        </div>
      </div>
    </div>
  );
}

const DYN_OPTS = ['', 'p', 'mp', 'mf', 'f', 'ff'];

// Full key list: chromatic majors + minors, incl. common enharmonic spellings.
const ALL_KEYS = (() => {
  const majors = ['C','C#','Db','D','D#','Eb','E','F','F#','Gb','G','G#','Ab','A','A#','Bb','B'];
  return [...majors, ...majors.map(k => k + 'm')];
})();

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "chordSize": 1,
  "lyricFont": "sans"
}/*EDITMODE-END*/;

const PAGE_H = 1056; // one Letter sheet at the chart's 816px width (8.5 : 11, 0.5in margins)

function FitToWidth({ children, onHideSection, onMeasure, deps }) {
  const outer = useRef(null), inner = useRef(null);
  const onMeasureRef = useRef(onMeasure); onMeasureRef.current = onMeasure;
  const [scale, setScale] = useState(1);
  const [h, setH] = useState(null);
  const [contentH, setContentH] = useState(0);

  // measure TRUE content extent (lowest child bottom), independent of the page's
  // min-height clamp — a page resting at min-height must not report stale overflow.
  const measure = () => {
    if (!outer.current || !inner.current) return;
    const avail = outer.current.clientWidth;
    const w = inner.current.scrollWidth || 1;
    const s = Math.min(1, avail / w);
    const page = inner.current.querySelector('.page');
    let extent = inner.current.scrollHeight;
    if (page) {
      const padB = parseFloat(getComputedStyle(page).paddingBottom) || 0;
      const top = page.getBoundingClientRect().top;
      let maxBottom = 0;
      for (const ch of page.children) {
        const b = ch.getBoundingClientRect().bottom - top;   // scaled px from page top
        if (b > maxBottom) maxBottom = b;
      }
      extent = (s ? maxBottom / s : maxBottom) + padB;        // unscale + bottom padding
    }
    const newH = inner.current.scrollHeight * s;
    if (s !== scale) setScale(s);
    if (Math.abs(extent - contentH) > 0.5) setContentH(extent);
    if (newH !== h) setH(newH);
    if (onMeasureRef.current) onMeasureRef.current(extent);
  };
  const measureRef = useRef(measure); measureRef.current = measure;

  useEffect(() => {
    const run = () => measureRef.current();
    run();
    const ro = new ResizeObserver(run);
    if (outer.current) ro.observe(outer.current);
    if (inner.current) ro.observe(inner.current);
    window.addEventListener('resize', run);
    return () => { ro.disconnect(); window.removeEventListener('resize', run); };
  }, []);

  // re-measure on any layout-affecting change (the clamped box won't always fire the observer)
  useLayoutEffect(() => { measureRef.current(); }, [deps]);

  const pages = Math.max(1, Math.ceil((contentH - 12) / PAGE_H));
  const guides = [];
  for (let k = 1; k < pages; k++) {
    guides.push(
      <div className="page-guide" key={k} style={{ top: (PAGE_H * k * scale) + 'px' }}>
        <span className="page-guide__label">Page {k + 1}</span>
      </div>
    );
  }
  return (
    <div className="fit" ref={outer} style={{ height: h ? h + 'px' : 'auto' }}>
      <div className="fit__inner" ref={inner} style={{ transform: `scale(${scale})` }}>
        {children}
      </div>
      {guides}
    </div>
  );
}

/* ---------- Perform mode: full-screen, chrome-free chart for reading off a stand ---------- */
// Display handle: always exactly one leading @, whatever got stored.
function handle(owner) {
  return '@' + String(owner || '').replace(/^@+/, '');
}

function withParse(song) {
  const { sections, arrangement } = window.Parser.parse(song.raw || '');
  const roadmap = song.roadmap || window.Parser.defaultRoadmap(arrangement);
  return { ...song, sections, roadmap, arrangement };
}

function newSongRecord(extra) {
  return {
    id: 'song-' + crypto.randomUUID(),
    title: 'Untitled Song', artist: '', writers: '', copyrightNotice: '', origKey: 'C', transpose: 0,
    bpm: '', time: '4/4', ccli: '', scripture: '',
    raw: '', nashville: false, diagrams: true, roadmap: null, railSide: 'right',
    mono: true, cols: 2, textScale: 1, chordSize: 1, chordColor: '#245f91', lineSpace: 1, secSpace: 1, railScale: 1, lineFit: true, sectionOrder: null, hiddenSections: [],
    owner: 'You', shared: false, ...extra,
  };
}

/* ---------- Like button (optimistic, session-gated) ---------- */
function LikeButton({ songId, count, liked, session, onNeedAuth }) {
  const [on, setOn] = useState(!!liked);
  const [n, setN] = useState(count || 0);
  useEffect(() => { setOn(!!liked); }, [liked]);
  useEffect(() => { setN(count || 0); }, [count]);
  const click = (e) => {
    e.stopPropagation();
    if (!session) { onNeedAuth(); return; }
    const next = !on;
    setOn(next);
    setN(m => m + (next ? 1 : -1));
    window.DB.toggleLike(songId, next).catch(err => {
      console.error(err);
      setOn(!next);
      setN(m => m + (next ? -1 : 1));
      window.showToast('Could not update like', 'error');
    });
  };
  return (
    <button className={'like-btn' + (on ? ' like-btn--on' : '')} onClick={click} aria-pressed={on} aria-label={(on ? 'Unlike' : 'Like') + ' this chart; ' + n + ' likes'}>
      <span className="like-btn__icon">♥</span>{n}
    </button>
  );
}

/* ---------- Song card (with setlist quick-add menu) ---------- */
function SongCard({ song, setlists, songFolders, onOpen, onDelete, onToggleFolder, onCreateSetlist }) {
  const [menu, setMenu] = useState(false);
  const [newName, setNewName] = useState('');
  const live = withParse(song);
  const key = song.nashville ? 'Nash' : window.Engine.transposeKey(song.origKey, song.transpose || 0);
  const inFolder = (fid) => songFolders.some(sf => sf.song_id === song.id && sf.folder_id === fid);
  const tags = setlists.filter(f => inFolder(f.id));
  return (
    <div className="card" role="button" tabIndex="0" onClick={() => onOpen(song.id)}
      onKeyDown={e => { if (e.target === e.currentTarget && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); onOpen(song.id); } }}>
      <div className="card__mini">
        {live.sections.slice(0, 4).map(sec => (
          <span key={sec.id} className="card__chip">{sec.code}</span>
        ))}
      </div>
      <div className="card__title">{song.title}</div>
      <div className="card__sub">{song.artist || '—'}</div>
      <div className="card__meta"><span>{key}</span>{song.bpm ? <span>{song.bpm} bpm</span> : null}<span>{live.sections.length} sections</span></div>
      {tags.length > 0 && (
        <div className="card__tags">{tags.map(t => <span key={t.id} className="card__tag">{t.name}</span>)}</div>
      )}
      <button className="card__del" aria-label={'Delete ' + song.title} onClick={(e) => { e.stopPropagation(); onDelete(song.id); }}>✕</button>
      <button className="card__fold" aria-label={'Add ' + song.title + ' to folder'} aria-expanded={menu} onClick={(e) => { e.stopPropagation(); setMenu(m => !m); }}>⊞</button>
      {menu && (
        <div className="foldmenu" onClick={e => e.stopPropagation()}>
          <div className="foldmenu__hd">Folders</div>
          {setlists.length === 0 && <div className="foldmenu__empty">No folders yet</div>}
          {setlists.map(f => (
            <label key={f.id} className="foldmenu__row">
              <input type="checkbox" checked={inFolder(f.id)} onChange={() => onToggleFolder(song.id, f.id)} />
              {f.name}
            </label>
          ))}
          <div className="foldmenu__new">
            <input aria-label="New folder name" placeholder="New folder…" value={newName} onChange={e => setNewName(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter' && newName.trim()) { onCreateSetlist(newName.trim()); setNewName(''); } }} />
          </div>
        </div>
      )}
    </div>
  );
}

/* ---------- Setlist reorder row list (compact ordered list, used in Library reorder mode) ---------- */
function SetlistOrderList({ songs, onMove }) {
  return (
    <ul className="ord">
      {songs.map((s, i) => (
        <li key={s.id} className="ord__row">
          <span className="ord__code">{i + 1}</span>
          <span className="ord__name">{s.title} <span className="muted">{s.artist || ''}</span></span>
          <span className="ord__btns">
            <button onClick={() => onMove(i, -1)} disabled={i === 0} aria-label={'Move ' + s.title + ' up'}>▲</button>
            <button onClick={() => onMove(i, 1)} disabled={i === songs.length - 1} aria-label={'Move ' + s.title + ' down'}>▼</button>
          </span>
        </li>
      ))}
    </ul>
  );
}

/* ---------- Library ---------- */
function prepareBatchCandidates(rows, existingSongs) {
  const keyOf = row => ((row.title || '').trim().toLowerCase().replace(/[^a-z0-9]+/g, ' ') + '|' + (row.artist || '').trim().toLowerCase()).trim();
  const existingKeys = new Set(existingSongs.map(keyOf));
  const groups = {};
  rows.forEach((row, index) => {
    if (!row.supported) return;
    const key = keyOf(row);
    (groups[key] || (groups[key] = [])).push(index);
    if (existingKeys.has(key)) {
      row.selected = false;
      row.warnings = [...(row.warnings || []), 'A chart with this title and artist is already in your library.'];
    }
  });
  Object.values(groups).forEach(indexes => {
    if (indexes.length < 2) return;
    const ranked = [...indexes].sort((a, b) => {
      const aa = /(^|\/)all\//i.test(rows[a].sourcePath || '') ? 1 : 0;
      const bb = /(^|\/)all\//i.test(rows[b].sourcePath || '') ? 1 : 0;
      return bb - aa || String(rows[b].sourceModifiedAt || '').localeCompare(String(rows[a].sourceModifiedAt || ''));
    });
    indexes.forEach(index => {
      rows[index].warnings = [...(rows[index].warnings || []), 'Possible duplicate: ' + indexes.length + ' versions found.'];
      if (index !== ranked[0]) rows[index].selected = false;
    });
  });
  return [...rows];
}

function DocxImportModal({ songs, onClose, onCommit }) {
  const [rows, setRows] = useState([]);
  const [progress, setProgress] = useState(null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  const [active, setActive] = useState(0);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [cleaningIndex, setCleaningIndex] = useState(null);
  const abortRef = useRef(null);
  const filesRef = useRef(null);
  const folderRef = useRef(null);
  const cardRef = useRef(null);
  const previewCloseRef = useRef(null);
  const titleId = React.useId();
  useDialogFocus(cardRef, previewOpen ? () => setPreviewOpen(false) : ((busy || cleaningIndex != null) ? null : onClose));
  useEffect(() => { if (previewOpen && previewCloseRef.current) previewCloseRef.current.focus(); }, [previewOpen]);
  useEffect(() => { setPreviewOpen(false); }, [active]);
  const selected = rows.filter(row => row.selected && row.supported);

  const scan = async (fileList) => {
    const files = Array.from(fileList || []);
    if (!files.length || busy) {
      if (!busy) setError('No files were selected. Choose the extracted folder again.');
      return;
    }
    setBusy(true); setError(''); setRows([]);
    const controller = new AbortController(); abortRef.current = controller;
    try {
      const found = await window.DocxImporter.scanFiles(files, { signal: controller.signal, onProgress: setProgress });
      setRows(prepareBatchCandidates(found, songs)); setActive(0);
    } catch (e) {
      if (e.name !== 'AbortError') setError(e.message || 'Could not read those files.');
    }
    abortRef.current = null; setBusy(false); setProgress(null);
  };
  const choose = (ref) => ref.current && ref.current.click();
  const chosen = (e) => {
    // FileList can be live: copy it before clearing the input so the selected
    // folder is not reduced to an empty list in some browsers.
    const files = Array.from(e.target.files || []);
    e.target.value = '';
    scan(files);
  };
  const patchRow = (index, patch) => setRows(prev => prev.map((row, i) => i === index ? { ...row, ...patch } : row));
  const cleanupCurrent = async () => {
    const row = rows[active];
    if (!row || !row.raw || cleaningIndex != null || busy) return;
    setCleaningIndex(active); setError('');
    try {
      const output = await window.AI.complete(row.raw);
      const cleaned = String(output || '').replace(/^```[a-z]*\n?/i, '').replace(/```\s*$/, '').trim();
      if (!cleaned) throw new Error('Gemini returned an empty chart.');
      const parsed = window.Parser.parse(cleaned);
      const hasChords = parsed.sections.some(section => section.lines.some(line => (line.chords || []).length || line.kind === 'bars'));
      const warnings = (row.warnings || []).filter(warning => !/^No parseable chord sections/.test(warning) && !/^DOCX spacing was reconstructed/.test(warning));
      warnings.push('Gemini cleanup was applied. Verify every chord and lyric before saving.');
      if (!hasChords) warnings.push('No parseable chord sections were found after cleanup.');
      patchRow(active, { raw: cleaned, sectionCount: parsed.sections.length, selected: hasChords && !!row.origKey, warnings: [...new Set(warnings)] });
    } catch (e) {
      if (e && e.status === 429) setError("You've reached the cleanup limit. Try again later or save the original chart.");
      else if (e && e.status === 401) setError('Your session expired. Sign in again to use cleanup.');
      else setError((e && e.message) || 'Gemini could not clean this chart. The original import is unchanged.');
    }
    setCleaningIndex(null);
  };
  const commit = async () => {
    if (!selected.length || busy) return;
    setBusy(true); setError(''); setProgress({ phase: 'saving', current: 0, total: selected.length });
    try { await onCommit(selected, done => setProgress({ phase: 'saving', current: done, total: selected.length })); onClose(); }
    catch (e) { setError(e.message || 'The selected charts could not be saved.'); setBusy(false); }
  };
  const current = rows[active];
  const previewSong = current && current.raw ? withParse(newSongRecord({
    title: current.title || 'Untitled Song', artist: current.artist || '', writers: current.writers || '',
    copyrightNotice: current.copyrightNotice || '', origKey: current.origKey || 'C', bpm: current.bpm || '',
    time: current.time || '4/4', ccli: current.ccli || '', scripture: current.scripture || '', raw: current.raw,
    diagrams: false, railSide: 'off', cols: 2,
  })) : null;
  return (
    <div className="modal" onMouseDown={(busy || cleaningIndex != null) ? undefined : onClose}>
      <div ref={cardRef} className="modal__card driveimp" role="dialog" aria-modal="true" aria-labelledby={titleId} onMouseDown={e => e.stopPropagation()}>
        <h3 id={titleId}>Import DOCX charts</h3>
        {!rows.length ? <>
          <p className="modal__lead">Download your Google Drive folder, unzip it, then choose the extracted folder. OnePage reads each chart locally and lets you review it before saving privately to your library.</p>
          <input ref={filesRef} type="file" multiple hidden accept=".docx,.txt,.pro,.cho,.chopro,.chordpro,.crd,.onsong,.xml,.pdf" onChange={chosen} />
          <input ref={folderRef} type="file" multiple hidden webkitdirectory="" directory="" onChange={chosen} />
          <div className="driveimp__choose">
            <button className="btn btn--primary" disabled={busy} onClick={() => choose(folderRef)}>Choose extracted folder</button>
            <button className="btn" disabled={busy} onClick={() => choose(filesRef)}>Choose individual files</button>
          </div>
          <p className="modal__hint">Supported: DOCX, ChordPro, OpenSong, and plain text. PDFs are listed for reference but cannot be imported.</p>
          {progress && <p className="modal__hint" role="status">Reading {progress.current} of {progress.total}: {progress.file}</p>}
        </> : <>
          <div className="driveimp__summary"><b>{selected.length}</b> selected · {rows.filter(r => !r.supported).length} unsupported · {rows.filter(r => (r.warnings || []).length).length} need attention</div>
          <div className="driveimp__body">
            <div className="driveimp__list" role="list">
              {rows.map((row, i) => <div key={row.sourceFileId} role="button" tabIndex="0" className={'driveimp__row' + (i === active ? ' on' : '')} onClick={() => setActive(i)} onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setActive(i); } }}>
                <input type="checkbox" aria-label={'Import ' + (row.title || row.sourcePath)} disabled={!row.supported} checked={!!row.selected} onClick={e => e.stopPropagation()} onChange={e => patchRow(i, { selected: e.target.checked })} />
                <span><b>{row.title || row.sourcePath}</b><small>{row.artist || 'No artist'} · {row.origKey || 'No key'} · {row.sectionCount || 0} sections</small></span>
                {(row.warnings || []).length ? <em title={row.warnings.join('\n')}>!</em> : null}
              </div>)}
            </div>
            {current && <div className="driveimp__detail">
              <div className="fields">
                <label>Title<input value={current.title || ''} disabled={!current.supported} onChange={e => patchRow(active, { title: e.target.value })} /></label>
                <label>Artist / recording<input value={current.artist || ''} disabled={!current.supported} onChange={e => patchRow(active, { artist: e.target.value })} /></label>
                <div className="row2"><label>Chart key<select value={current.origKey || ''} disabled={!current.supported} onChange={e => patchRow(active, { origKey: e.target.value, selected: !!e.target.value, warnings: (current.warnings || []).filter(w => w !== 'Chart key is missing.') })}><option value="">Choose…</option>{ALL_KEYS.map(k => <option key={k}>{k}</option>)}</select></label><label>CCLI<input value={current.ccli || ''} disabled={!current.supported} onChange={e => patchRow(active, { ccli: e.target.value })} /></label></div>
                <label>Writers<input value={current.writers || ''} disabled={!current.supported} onChange={e => patchRow(active, { writers: e.target.value })} /></label>
                <label>Copyright / publishers<input value={current.copyrightNotice || ''} disabled={!current.supported} onChange={e => patchRow(active, { copyrightNotice: e.target.value })} /></label>
              </div>
              {(current.warnings || []).length > 0 && <ul className="driveimp__warnings">{current.warnings.map((w, i) => <li key={i}>{w}</li>)}</ul>}
              {previewSong && <>
                <div className="driveimp__previewbar"><span>Parsed chart preview</span><span className="driveimp__preview-actions"><button className="btn btn--ghost btn--sm" disabled={cleaningIndex != null || busy} onClick={cleanupCurrent}>{cleaningIndex === active ? 'Cleaning…' : '✨ Clean chart'}</button><button className="btn btn--ghost btn--sm" onClick={() => setPreviewOpen(true)}>Open large preview ↗</button></span></div>
                <button type="button" className="driveimp__chart" aria-label="Open large parsed chart preview" onClick={() => setPreviewOpen(true)}>
                  <span className="driveimp__chart-inner"><window.Chart song={previewSong} /></span>
                </button>
              </>}
              {current.raw && <details><summary>Extracted source</summary><pre className="driveimp__preview">{(current.sourceText || current.raw).slice(0, 4000)}</pre></details>}
              <small className="muted">{current.sourcePath}</small>
            </div>}
          </div>
        </>}
        {progress && progress.phase === 'saving' && <p className="modal__hint" role="status">Saving {progress.current} of {progress.total} charts…</p>}
        {error && <p className="auth__err" role="alert">{error}</p>}
        <div className="modal__row">
          <button className="btn btn--ghost btn--sm" disabled={(busy && !abortRef.current) || cleaningIndex != null} onClick={() => abortRef.current ? abortRef.current.abort() : onClose()}>{abortRef.current ? 'Cancel scan' : 'Cancel'}</button>
          <span style={{ flex: 1 }} />
          {rows.length
            ? <button className="btn btn--primary btn--sm" disabled={busy || !selected.length || cleaningIndex != null} onClick={commit}>{busy ? 'Saving…' : 'Save ' + selected.length + ' chart' + (selected.length === 1 ? '' : 's') + ' to library'}</button>
            : null}
        </div>
        {previewOpen && previewSong && (
          <div className="importpreview" role="dialog" aria-modal="true" aria-label={'Large preview of ' + (previewSong.title || 'chart')} onMouseDown={() => setPreviewOpen(false)}>
            <div className="importpreview__card" onMouseDown={e => e.stopPropagation()}>
              <div className="importpreview__head">
                <div><h3>{previewSong.title || 'Chart preview'}</h3><p>Review chord placement and credits before saving.</p></div>
                <button ref={previewCloseRef} className="btn btn--ghost btn--sm" onClick={() => setPreviewOpen(false)}>Close</button>
              </div>
              <div className="importpreview__scroll">
                <div className="importpreview__page"><window.Chart song={previewSong} /></div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function Library({ songs, user, onOpen, onNew, onImport, onBatchImport, canBatchImport, onDelete, folders, songFolders, query, setQuery, keyFilter, setKeyFilter, artistFilter, setArtistFilter, groupBy, setGroupBy, onCreateSetlist, onDeleteSetlist, onToggleFolder, onReorderFolder, onPrintSetlist }) {
  const [newSetlist, setNewSetlist] = useState('');
  const [showBatchImport, setShowBatchImport] = useState(false);
  const importInputRef = useRef(null);
  const handleImportFiles = async (e) => {
    const files = Array.from(e.target.files || []);
    e.target.value = '';
    if (!files.length) return;
    const imported = [];
    for (const file of files) {
      try {
        const text = await file.text();
        const parsed = window.Importer.importText(file.name, text);
        const fallbackTitle = file.name.replace(/\.[^.]+$/, '');
        imported.push({ ...parsed, title: parsed.title || fallbackTitle });
      } catch (err) {
        console.error('Import failed for', file.name, err);
      }
    }
    if (imported.length) onImport(imported);
  };
  const [confirmFolder, setConfirmFolder] = useState(null); // folder pending delete confirmation
  const [reordering, setReordering] = useState({}); // { [folderId]: true }
  const setlists = useMemo(() => folders.filter(f => f.type === 'setlist'), [folders]);
  const artists = useMemo(() => Array.from(new Set(songs.map(s => s.artist || 'Unknown'))).sort(), [songs]);

  const visible = useMemo(() => {
    const q = query.trim().toLowerCase();
    return songs.filter(s => {
      if (q && !((s.title || '').toLowerCase().includes(q) || (s.artist || '').toLowerCase().includes(q))) return false;
      if (keyFilter && s.origKey !== keyFilter) return false;
      if (artistFilter && (s.artist || 'Unknown') !== artistFilter) return false;
      return true;
    });
  }, [songs, query, keyFilter, artistFilter]);

  const renderCard = (s) => (
    <SongCard key={s.id} song={s} setlists={setlists} songFolders={songFolders}
      onOpen={onOpen} onDelete={onDelete} onToggleFolder={onToggleFolder} onCreateSetlist={onCreateSetlist} />
  );

  // build grouped sections
  let groups = null;
  if (groupBy === 'artist') {
    groups = artists.map(a => ({ key: a, label: a, songs: visible.filter(s => (s.artist || 'Unknown') === a) }))
      .filter(g => g.songs.length);
  } else if (groupBy === 'folder') {
    groups = setlists.map(f => {
      const members = visible.filter(s => songFolders.some(sf => sf.song_id === s.id && sf.folder_id === f.id));
      const posOf = (songId) => {
        const sf = songFolders.find(x => x.song_id === songId && x.folder_id === f.id);
        return sf && sf.position != null ? sf.position : 9999;
      };
      const ordered = members
        .map((s, idx) => ({ s, idx, pos: posOf(s.id) }))
        .sort((a, b) => a.pos - b.pos || a.idx - b.idx)
        .map(x => x.s);
      return { key: f.id, label: f.name, folderId: f.id, songs: ordered };
    });
    const unfiled = visible.filter(s => !songFolders.some(sf => sf.song_id === s.id && setlists.some(f => f.id === sf.folder_id)));
    if (unfiled.length) groups.push({ key: '__unfiled', label: 'Unfiled', songs: unfiled });
  }

  return (
    <div className="lib">
      <div className="lib__hero">
        <div>
          <h1>My Library</h1>
          <p>One-page lead sheets, built to read on a stand.</p>
        </div>
        <input ref={importInputRef} type="file" multiple hidden
          accept=".txt,.pro,.cho,.chopro,.chordpro,.crd,.onsong,.xml"
          onChange={handleImportFiles} />
        <div className="lib__actions" role="toolbar" aria-label="Library actions">
          <div className="lib__import-actions">
            <button className="btn" onClick={() => importInputRef.current && importInputRef.current.click()}>Import files</button>
            {canBatchImport && <button className="btn" onClick={() => setShowBatchImport(true)}>Import DOCX folder</button>}
          </div>
          <button className="btn btn--primary lib__new-chart" onClick={onNew}>+ New chart</button>
        </div>
      </div>

      <div className="lib__filters">
        <input className="lib__search" aria-label="Search your charts" placeholder="Search title or artist…" value={query} onChange={e => setQuery(e.target.value)} />
        <select aria-label="Filter your charts by key" value={keyFilter} onChange={e => setKeyFilter(e.target.value)}>
          <option value="">All keys</option>
          {ALL_KEYS.map(k => <option key={k} value={k}>{k}</option>)}
        </select>
        <select aria-label="Filter your charts by artist" value={artistFilter} onChange={e => setArtistFilter(e.target.value)}>
          <option value="">All artists</option>
          {artists.map(a => <option key={a} value={a}>{a}</option>)}
        </select>
        <select aria-label="Group your charts" value={groupBy} onChange={e => setGroupBy(e.target.value)}>
          <option value="flat">No grouping</option>
          <option value="artist">Group by artist</option>
          <option value="folder">Group by folder</option>
        </select>
      </div>

      <div className="lib__setlists">
        <span className="lib__setlists-lbl">Folders:</span>
        {setlists.map(f => (
          <span key={f.id} className="chip-pill">{f.name}
            <button aria-label={'Delete folder ' + f.name} onClick={() => setConfirmFolder(f)}>✕</button>
          </span>
        ))}
        <input className="lib__setlists-new" aria-label="New folder name" placeholder="New folder…" value={newSetlist}
          onChange={e => setNewSetlist(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter' && newSetlist.trim()) { onCreateSetlist(newSetlist.trim()); setNewSetlist(''); } }} />
      </div>

      {songs.length === 0 ? (
        <div className="empty">
          <div className="empty__glyph">♪</div>
          <div className="empty__title">No charts yet</div>
          <div className="empty__hint">Paste your first song to build a one-page chart.</div>
          <button className="btn btn--primary btn--sm" onClick={onNew}>+ New chart</button>
        </div>
      ) : groups
        ? groups.map(g => {
            const isReorderable = !!g.folderId;
            const isReordering = isReorderable && !!reordering[g.folderId];
            const move = (i, dir) => {
              const j = i + dir;
              if (j < 0 || j >= g.songs.length) return;
              const next = [...g.songs];
              [next[i], next[j]] = [next[j], next[i]];
              onReorderFolder(g.folderId, next.map(s => s.id));
            };
            return (
              <div key={g.key} className="lib__group">
                <h2 className="lib__group-hd">
                  {g.label} <span className="lib__group-ct">{g.songs.length}</span>
                  {isReorderable && (
                    <>
                      <button className="btn btn--ghost btn--sm" onClick={() => setReordering(r => ({ ...r, [g.folderId]: !r[g.folderId] }))}>
                        {isReordering ? 'Done' : 'Reorder'}
                      </button>
                      <button className="btn btn--ghost btn--sm" onClick={() => onPrintSetlist(folders.find(f => f.id === g.folderId))}>
                        Print setlist
                      </button>
                    </>
                  )}
                </h2>
                {isReordering
                  ? <SetlistOrderList songs={g.songs} onMove={move} />
                  : <div className="lib__grid">{g.songs.map(renderCard)}</div>}
              </div>
            );
          })
        : visible.length
          ? <div className="lib__grid">{visible.map(renderCard)}</div>
          : <p className="lib__note">No songs match those filters.</p>}

      {confirmFolder && (
        <ConfirmDialog
          title={`Delete folder "${confirmFolder.name}"?`}
          body="Songs inside are not deleted."
          confirmLabel="Delete folder"
          onCancel={() => setConfirmFolder(null)}
          onConfirm={() => { onDeleteSetlist(confirmFolder.id); setConfirmFolder(null); }}
        />
      )}
      {showBatchImport && <DocxImportModal songs={songs} onClose={() => setShowBatchImport(false)} onCommit={onBatchImport} />}
    </div>
  );
}

/* ---------- Roadmap editor ---------- */
function RoadmapEditor({ sections, roadmap, arrangement, onChange }) {
  const update = (i, patch) => {
    const next = roadmap.map((s, idx) => idx === i ? { ...s, ...patch } : s);
    onChange(next);
  };
  const move = (i, dir) => {
    const j = i + dir;
    if (j < 0 || j >= roadmap.length) return;
    const next = [...roadmap];
    [next[i], next[j]] = [next[j], next[i]];
    onChange(next);
  };
  const add = () => onChange([...roadmap, { sectionId: sections[0] ? sections[0].id : '', repeat: 1, dyn: '', cue: '' }]);
  const remove = (i) => onChange(roadmap.filter((_, idx) => idx !== i));
  const reset = () => onChange(window.Parser.defaultRoadmap(arrangement));

  return (
    <div className="rme">
      {roadmap.map((step, i) => (
        <div key={i} className="rme__row">
          <div className="rme__ord">
            <button onClick={() => move(i, -1)} disabled={i === 0} aria-label={'Move road map step ' + (i + 1) + ' up'}>▲</button>
            <button onClick={() => move(i, 1)} disabled={i === roadmap.length - 1} aria-label={'Move road map step ' + (i + 1) + ' down'}>▼</button>
          </div>
          <select aria-label={'Section for road map step ' + (i + 1)} value={step.sectionId} onChange={e => update(i, { sectionId: e.target.value })}>
            {sections.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
          </select>
          <label className="rme__rep">×<input type="number" aria-label={'Repeat count for road map step ' + (i + 1)} min="1" max="9" value={step.repeat} onChange={e => update(i, { repeat: Math.max(1, +e.target.value || 1) })} /></label>
          <select className="rme__dyn" aria-label={'Dynamics for road map step ' + (i + 1)} value={step.dyn} onChange={e => update(i, { dyn: e.target.value })}>
            {DYN_OPTS.map(d => <option key={d} value={d}>{d || 'dyn'}</option>)}
          </select>
          <input className="rme__cue" aria-label={'Cue for road map step ' + (i + 1)} placeholder="cue — e.g. build, drop, piano only" value={step.cue} onChange={e => update(i, { cue: e.target.value })} />
          <button className="rme__rm" onClick={() => remove(i)} aria-label={'Remove road map step ' + (i + 1)}>✕</button>
        </div>
      ))}
      <div className="rme__actions">
        <button className="btn btn--ghost btn--sm" onClick={add}>+ Add step</button>
        <button className="btn btn--ghost btn--sm" onClick={reset}>Reset to song order</button>
      </div>
    </div>
  );
}

/* ---------- Layout editor ---------- */
function Slider({ label, value, min, max, step, toText, fromText, onChange }) {
  const [txt, setTxt] = useState(toText(value));
  useEffect(() => { setTxt(toText(value)); }, [value]);
  const commit = () => {
    const v = fromText(txt);
    if (!isNaN(v) && isFinite(v)) onChange(Math.min(max, Math.max(min, v)));
    else setTxt(toText(value));
  };
  return (
    <label className="lay__ctl">
      <span className="lay__ctl-top">
        <span>{label}</span>
        <input className="lay__num" aria-label={label + ' value'} value={txt}
          onChange={e => setTxt(e.target.value)}
          onBlur={commit}
          onKeyDown={e => { if (e.key === 'Enter') e.target.blur(); }} />
      </span>
      <input type="range" aria-label={label} min={min} max={max} step={step} value={value} onChange={e => onChange(+e.target.value)} />
    </label>
  );
}

function LayoutEditor({ song, sections, set }) {
  const chordColors = [
    { name: 'Black', value: '#1c1c22', mono: true },
    { name: 'Blue', value: '#245f91' },
    { name: 'Purple', value: '#6b4fa1' },
    { name: 'Red', value: '#a33d3d' },
    { name: 'Green', value: '#267056' },
    { name: 'Amber', value: '#8a5a24' },
  ];
  const cols = song.cols || 2;
  const hidden = song.hiddenSections || [];
  const order = (song.sectionOrder && song.sectionOrder.length)
    ? song.sectionOrder.filter(id => sections.some(s => s.id === id))
        .concat(sections.filter(s => !song.sectionOrder.includes(s.id)).map(s => s.id))
    : sections.map(s => s.id);
  const byId = {};
  sections.forEach(s => { byId[s.id] = s; });
  const move = (i, dir) => {
    const j = i + dir;
    if (j < 0 || j >= order.length) return;
    const next = [...order];
    [next[i], next[j]] = [next[j], next[i]];
    set({ sectionOrder: next });
  };
  const toggleHide = (id) => set(prev => {
    const h = prev.hiddenSections || [];
    return { hiddenSections: h.includes(id) ? h.filter(x => x !== id) : [...h, id] };
  });

  return (
    <div className="lay">
      <div className="lay__ctl">
        <span className="lay__ctl-top">
          <span>Road map</span>
          <label className="lay__switch">
            <input type="checkbox" checked={song.railSide !== 'off'} onChange={e => set({ railSide: e.target.checked ? (song.lastRail || 'right') : 'off', lastRail: song.railSide !== 'off' ? song.railSide : (song.lastRail || 'right') })} />
            <span>{song.railSide !== 'off' ? 'shown' : 'hidden'}</span>
          </label>
        </span>
        {song.railSide !== 'off' && (
          <div className="seg">
            {['top', 'right', 'bottom', 'left'].map(p => (
              <button key={p} className={song.railSide === p ? 'on' : ''} onClick={() => set({ railSide: p })}>{p}</button>
            ))}
          </div>
        )}
      </div>

      {song.railSide !== 'off' && (
        <Slider label="Road map size" value={song.railScale || 1} min={0.75} max={1.4} step={0.05}
          toText={v => Math.round(v * 100) + '%'} fromText={t => parseFloat(t) / 100} onChange={v => set({ railScale: v })} />
      )}

      <Slider label="Text size" value={song.textScale || 1} min={0.65} max={1.35} step={0.02}
        toText={v => Math.round(v * 100) + '%'} fromText={t => parseFloat(t) / 100} onChange={v => set({ textScale: v })} />

      <Slider label="Chord size" value={song.chordSize || 1} min={0.8} max={1.6} step={0.05}
        toText={v => Math.round(v * 100) + '%'} fromText={t => parseFloat(t) / 100} onChange={v => set({ chordSize: v })} />

      <div className="lay__ctl">
        <span className="lay__ctl-top"><span>Chord color</span><span className="lay__hint-sm">{song.mono !== false ? 'black & white' : 'color'}</span></span>
        <div className="chord-colors" role="group" aria-label="Chord color">
          {chordColors.map(option => {
            const selected = option.mono ? song.mono !== false : song.mono === false && (song.chordColor || '#245f91') === option.value;
            return <button key={option.name} className={selected ? 'on' : ''} aria-pressed={selected}
              aria-label={option.name + ' chords'} title={option.name}
              onClick={() => set({ mono: !!option.mono, chordColor: option.value })}>
              <span style={{ background: option.value }} />
            </button>;
          })}
        </div>
        <span className="lay__color-hint">Choosing a color turns off B&amp;W for this chart.</span>
      </div>

      <div className="lay__ctl">
        <span className="lay__ctl-top"><span>Long lines</span></span>
        <div className="seg">
          <button className={song.lineFit !== false ? 'on' : ''} onClick={() => set({ lineFit: true })}>One line</button>
          <button className={song.lineFit === false ? 'on' : ''} onClick={() => set({ lineFit: false })}>Wrap</button>
        </div>
      </div>

      <div className="lay__ctl">
        <span className="lay__ctl-top"><span>Columns</span></span>
        <div className="seg">
          {[1, 2, 3].map(n => (
            <button key={n} className={cols === n ? 'on' : ''} onClick={() => set({ cols: n })}>{n}</button>
          ))}
        </div>
      </div>

      <Slider label="Line spacing" value={song.lineSpace || 1} min={0.85} max={1.6} step={0.05}
        toText={v => v.toFixed(2)} fromText={t => parseFloat(t)} onChange={v => set({ lineSpace: v })} />
      <Slider label="Space between sections" value={song.secSpace || 1} min={0.4} max={2} step={0.05}
        toText={v => v.toFixed(2)} fromText={t => parseFloat(t)} onChange={v => set({ secSpace: v })} />

      <div className="lay__reorder">
        <div className="lay__ctl-top"><span>Sections</span><span className="lay__hint-sm">reorder · remove</span></div>
        <ul className="ord">
          {order.map((id, i) => {
            const s = byId[id];
            if (!s) return null;
            const isHidden = hidden.includes(id);
            return (
              <li key={id} className={`ord__row${isHidden ? ' ord__row--hidden' : ''}`}>
                <span className="ord__code">{s.code}</span>
                <span className="ord__name">{s.label}</span>
                <span className="ord__btns">
                  <button onClick={() => move(i, -1)} disabled={i === 0 || isHidden} aria-label={'Move ' + s.label + ' up'}>▲</button>
                  <button onClick={() => move(i, 1)} disabled={i === order.length - 1 || isHidden} aria-label={'Move ' + s.label + ' down'}>▼</button>
                  <button className="ord__del" onClick={() => toggleHide(id)} aria-label={(isHidden ? 'Restore ' : 'Remove ') + s.label}>{isHidden ? '↺' : '✕'}</button>
                </span>
              </li>
            );
          })}
        </ul>
      </div>

      <div className="lay__actions">
        <button className="btn btn--ghost btn--sm" onClick={() => set({ textScale: 1, chordSize: 1, chordColor: '#245f91', mono: true, cols: 2, lineSpace: 1, secSpace: 1, railSide: 'right', railScale: 1, lineFit: true, sectionOrder: null, hiddenSections: [] })}>Reset layout</button>
      </div>
    </div>
  );
}

/* ---------- API key modal (for Clean up paste in production) ---------- */
function ApiKeyModal({ onClose }) {
  const [val, setVal] = useState(window.AI.getKey());
  const cardRef = useRef(null);
  const titleId = React.useId();
  useDialogFocus(cardRef, onClose);
  const save = () => { window.AI.setKey(val); onClose(); };
  return (
    <div className="modal" onMouseDown={onClose}>
      <div ref={cardRef} className="modal__card" role="dialog" aria-modal="true" aria-labelledby={titleId} onMouseDown={e => e.stopPropagation()}>
        <h3 id={titleId}>AI cleanup key</h3>
        <p className="modal__lead">If you’ve deployed the included <b>/api/cleanup</b> proxy, you don’t need this — cleanups use your server key automatically. This key is a fallback for self-hosting without the proxy. It’s stored only in this browser.</p>
        <input className="modal__in" type="password" value={val} autoFocus spellCheck={false}
          placeholder="AIza…" onChange={e => setVal(e.target.value)}
          aria-label="Personal Gemini API key" onKeyDown={e => { if (e.key === 'Enter') save(); }} />
        <p className="modal__hint">Get a free key at <b>aistudio.google.com/apikey</b> — no credit card, ~1,500 cleanups/day.</p>
        {window.AI.hasBuiltin() && !window.AI.hasKey() && (
          <p className="modal__hint">In this preview it already works without a key; you only need one once the app is deployed.</p>
        )}
        <div className="modal__row">
          {window.AI.hasKey() && <button className="btn btn--ghost btn--sm" onClick={() => { window.AI.setKey(''); onClose(); }}>Remove key</button>}
          <span style={{ flex: 1 }} />
          <button className="btn btn--ghost btn--sm" onClick={onClose}>Cancel</button>
          <button className="btn btn--sm" onClick={save}>Save</button>
        </div>
      </div>
    </div>
  );
}

function ProfileSetup({ onSave, onClose }) {
  const [value, setValue] = useState('');
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);
  const titleId = React.useId();
  const cardRef = useRef(null);
  useDialogFocus(cardRef, onClose);
  const normalized = value.trim().replace(/^@+/, '').toLowerCase();
  const valid = /^[a-z0-9](?:[a-z0-9._-]{1,28}[a-z0-9])$/.test(normalized);
  const save = async () => {
    if (!valid || busy) { setError('Use 3–30 lowercase letters, numbers, dots, dashes, or underscores.'); return; }
    setBusy(true); setError('');
    try { await onSave(normalized); }
    catch (e) {
      setError(e && e.code === '23505' ? 'That handle is already taken.' : 'Could not save that handle. Please try again.');
      setBusy(false);
    }
  };
  return (
    <div className="modal" onMouseDown={onClose}>
      <div ref={cardRef} className="modal__card" role="dialog" aria-modal="true" aria-labelledby={titleId} onMouseDown={e => e.stopPropagation()}>
        <h3 id={titleId}>Choose your public handle</h3>
        <p className="modal__lead">This is used only if community sharing returns. Your email is never published.</p>
        <input className="modal__in" aria-label="Public handle" autoFocus value={value} placeholder="your.handle"
          onChange={e => setValue(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') save(); if (e.key === 'Escape') onClose(); }} />
        {error && <p className="auth__err" role="alert">{error}</p>}
        <div className="modal__row">
          <button className="btn btn--ghost btn--sm" onClick={onClose}>Later</button>
          <span style={{ flex: 1 }} />
          <button className="btn btn--primary btn--sm" disabled={!valid || busy} onClick={save}>{busy ? 'Saving…' : 'Save handle'}</button>
        </div>
      </div>
    </div>
  );
}

/* ---------- Setlist field (editor Song info tab) ---------- */
function SetlistField({ song, setlists, songFolders, onToggleFolder, onCreateSetlist }) {
  const [newName, setNewName] = useState('');
  const inFolder = (fid) => songFolders.some(sf => sf.song_id === song.id && sf.folder_id === fid);
  return (
    <div className="setfield">
      <span className="setfield__lbl">Folders</span>
      <div className="setfield__list">
        {setlists.length === 0 && <span className="setfield__empty">No folders yet — create one below.</span>}
        {setlists.map(f => (
          <label key={f.id} className={inFolder(f.id) ? 'setfield__chk on' : 'setfield__chk'}>
            <input type="checkbox" checked={inFolder(f.id)} onChange={() => onToggleFolder(song.id, f.id)} />
            {f.name}
          </label>
        ))}
      </div>
      <input className="setfield__new" aria-label="New folder name" placeholder="New folder…" value={newName}
        onChange={e => setNewName(e.target.value)}
        onKeyDown={e => { if (e.key === 'Enter' && newName.trim()) { onCreateSetlist(newName.trim()); setNewName(''); } }} />
    </div>
  );
}

/* ---------- Editor ---------- */
function Editor({ song, onChange, onBack, onDuplicate, onPrint, onUndo, onRedo, canUndo, canRedo, setlists, songFolders, onToggleFolder, onCreateSetlist, publicHandle, canPublish, onPublish }) {
  const live = useMemo(() => withParse(song), [song.raw, song.roadmap, song.transpose, song.nashville, song.diagrams, song.railSide, song.railScale, song.origKey, song.title, song.artist, song.writers, song.copyrightNotice, song.bpm, song.time, song.ccli, song.scripture, song.mono, song.cols, song.textScale, song.chordSize, song.chordColor, song.lineSpace, song.secSpace, song.lineFit, song.sectionOrder, song.hiddenSections]);
  const set = onChange; // accepts a patch object OR an updater fn (prevSong) => patch
  const targetKey = song.nashville ? 'Nashville numbers' : window.Engine.transposeKey(song.origKey, song.transpose || 0);
  const [tab, setTab] = useState('source');
  const [editMode, setEditMode] = useState(false);
  const [cleaning, setCleaning] = useState(false);
  const [showKey, setShowKey] = useState(false);
  const [contentH, setContentH] = useState(0);
  const [fitting, setFitting] = useState(false);

  // empty chart shows the starter card, which never measures — clear stale page-count
  useEffect(() => { if (!(song.raw || '').trim() && contentH) setContentH(0); }, [song.raw]);

  // "Fit to page": shrink text a notch at a time until the chart fits one sheet
  useEffect(() => {
    if (!fitting || !contentH) return;
    const ts = song.textScale || 1;
    if (contentH <= PAGE_H + 4 || ts <= 0.6) { setFitting(false); return; }
    const id = setTimeout(() => set({ textScale: Math.max(0.6, +(ts - 0.03).toFixed(3)) }), 45);
    return () => clearTimeout(id);
  }, [fitting, contentH, song.textScale]);
  const fitToPage = () => setFitting(true);
  const overPages = Math.max(1, Math.ceil((contentH - 12) / PAGE_H));

  // on-screen chord edit -> re-serialize the whole song back into raw (single source of truth)
  const editLine = (secId, lineIdx, newChords) => set(prev => {
    const parsed = window.Parser.parse(prev.raw || '');
    const sec = parsed.sections.find(s => s.id === secId);
    if (!sec || !sec.lines[lineIdx]) return {};
    sec.lines[lineIdx] = { ...sec.lines[lineIdx], kind: 'pair', chords: newChords };
    return { raw: window.Serialize.serializeSong(parsed.sections) };
  });

  const cleanup = async () => {
    if (!(song.raw || '').trim() || cleaning) return;
    setCleaning(true);
    try {
      const out = await window.AI.complete(song.raw);
      const cleaned = (out || '').replace(/^```[a-z]*\n?/i, '').replace(/```\s*$/, '').trim();
      if (cleaned) set({ raw: cleaned, roadmap: null });
    } catch (e) {
      const errorMsg = e && e.message ? e.message : 'unknown error';
      if (e && e.code === 'NO_PROVIDER') { setShowKey(true); }
      else if (e && e.status === 401) { window.showToast('Your session expired. Log in again to use cleanup.', 'error'); }
      else if (e && e.status === 429) { window.showToast("You've reached the cleanup limit. Please try again later.", 'error'); }
      else if (e && (e.status === 400 || e.status === 403)) { window.showToast('That Gemini API key was rejected. Please check it and try again.', 'error'); setShowKey(true); }
      else { window.showToast('Could not clean up the paste right now — ' + errorMsg + '.', 'error'); }
    }
    setCleaning(false);
  };

  const toggleShare = async () => {
    if (!window.PUBLIC_SHARING_ENABLED) return;
    const on = !song.shared;
    if (on && !publicHandle) { window.showToast('Choose a public handle before sharing.', 'error'); return; }
    if (on && !canPublish) { window.showToast('Public publishing is not enabled for this account.', 'error'); return; }
    if (on) {
      try { await onPublish(song); }
      catch (e) { window.showToast(e.message || 'Could not publish this chart.', 'error'); }
    }
    else { set({ shared: false, sharedAt: null }); window.showToast('Removed from Explore'); }
  };

  return (
    <div className="editor">
      <div className="editor__controls">
        <div className="ctl__top">
          <button className="btn btn--ghost btn--sm" onClick={onBack}>← Library</button>
          <div className="ctl__topright">
            <button className="btn btn--ghost btn--sm icon" onClick={onUndo} disabled={!canUndo} aria-label="Undo chart change">↶</button>
            <button className="btn btn--ghost btn--sm icon" onClick={onRedo} disabled={!canRedo} aria-label="Redo chart change">↷</button>
            <button className="btn btn--ghost btn--sm" onClick={onDuplicate}>Duplicate</button>
            <button className="btn btn--primary btn--sm" onClick={onPrint}>Print / PDF</button>
          </div>
        </div>

        <div className="tabs">
          <button className={tab === 'source' ? 'on' : ''} aria-pressed={tab === 'source'} onClick={() => setTab('source')}>Chords</button>
          <button className={tab === 'info' ? 'on' : ''} aria-pressed={tab === 'info'} onClick={() => setTab('info')}>Song info</button>
          <button className={tab === 'map' ? 'on' : ''} aria-pressed={tab === 'map'} onClick={() => setTab('map')}>Road map</button>
          <button className={tab === 'layout' ? 'on' : ''} aria-pressed={tab === 'layout'} onClick={() => setTab('layout')}>Layout</button>
        </div>

        {tab === 'source' && (
          <div className="pane">
            <div className="raw-tools">
              <p className="hint">Paste chords-above-lyrics or ChordPro-style text. Section headers end with “:”. Use <code>| C | G/B |</code> for instrumental bars.</p>
              <button className="btn btn--ghost btn--sm cleanup" onClick={cleanup} disabled={cleaning || !(song.raw || '').trim()}>
                {cleaning ? <span className="spin" /> : '✨'} {cleaning ? 'Cleaning…' : 'Clean up paste'}
              </button>
            </div>
            <p className="hint hint--ai">Pasted from a website and the chords don’t line up? <b>Clean up paste</b> re-aligns chords over the right syllables, tidies section headers, and collapses repeated choruses/bridges so the sheet stays compact.</p>
            <textarea className="raw" aria-label="Chord chart source" value={song.raw} onChange={e => set({ raw: e.target.value, roadmap: null })} spellCheck={false} placeholder={"Verse 1:\nC            G\nAmazing grace how sweet the sound"} />
            {showKey && <ApiKeyModal onClose={() => setShowKey(false)} />}
          </div>
        )}

        {tab === 'info' && (
          <div className="pane fields">
            <label>Title<input value={song.title} onChange={e => set({ title: e.target.value })} /></label>
            <label>Artist / recording<input value={song.artist} onChange={e => set({ artist: e.target.value })} /></label>
            <label>Writers<input value={song.writers || ''} onChange={e => set({ writers: e.target.value })} placeholder="Songwriter names" /></label>
            <label>Copyright / publishers<input value={song.copyrightNotice || ''} onChange={e => set({ copyrightNotice: e.target.value })} placeholder="© year and publisher information" /></label>
            <div className="row2">
              <label>Original key
                <select value={song.origKey} onChange={e => set({ origKey: e.target.value })}>
                  {ALL_KEYS.map(k => <option key={k}>{k}</option>)}
                </select>
              </label>
              <label>Tempo<input value={song.bpm} onChange={e => set({ bpm: e.target.value })} placeholder="bpm" /></label>
            </div>
            <div className="row2">
              <label>Time<input value={song.time} onChange={e => set({ time: e.target.value })} placeholder="4/4" /></label>
              <label>CCLI #<input value={song.ccli} onChange={e => set({ ccli: e.target.value })} /></label>
            </div>
            <label>Scripture / notes<input value={song.scripture} onChange={e => set({ scripture: e.target.value })} /></label>
            <SetlistField song={song} setlists={setlists} songFolders={songFolders} onToggleFolder={onToggleFolder} onCreateSetlist={onCreateSetlist} />
          </div>
        )}

        {tab === 'map' && (
          <div className="pane">
            <p className="hint">Each section is printed <b>once</b>. The road map is how you actually play it — order, repeats, dynamics &amp; cues.</p>
            <RoadmapEditor sections={live.sections} roadmap={live.roadmap} arrangement={live.arrangement} onChange={(rm) => set({ roadmap: rm })} />
          </div>
        )}

        {tab === 'layout' && (
          <div className="pane">
            <p className="hint">Make it fit on one page. Shrink the text, switch columns, or tighten spacing so wrapped lyrics don't push the chart longer than it needs to be.</p>
            <LayoutEditor song={song} sections={live.sections} set={set} />
          </div>
        )}

        <div className="ctl__bottom">
          <div className="transpose">
            <span className="lbl">Transpose</span>
            <button aria-label="Transpose down one semitone" onClick={() => set(prev => ({ transpose: (prev.transpose || 0) - 1, nashville: false }))}>−</button>
            <span className="keyout">{targetKey}</span>
            <button aria-label="Transpose up one semitone" onClick={() => set(prev => ({ transpose: (prev.transpose || 0) + 1, nashville: false }))}>+</button>
            {song.transpose ? <button className="reset" onClick={() => set({ transpose: 0 })}>reset</button> : null}
          </div>
          <div className="toggles">
            <label className={song.nashville ? 'tg on' : 'tg'}><input type="checkbox" checked={song.nashville} onChange={e => set({ nashville: e.target.checked })} />Nashville #</label>
            <label className={song.diagrams ? 'tg on' : 'tg'}><input type="checkbox" checked={song.diagrams} onChange={e => set({ diagrams: e.target.checked })} />Diagrams</label>
            <label className={(song.mono !== false) ? 'tg on' : 'tg'}><input type="checkbox" checked={song.mono !== false} onChange={e => set({ mono: e.target.checked })} />B&amp;W</label>
          </div>
        </div>
      </div>

      <div className="editor__preview">
        <div className="preview__bar">
          <label className={editMode ? 'tg tg--sm on' : 'tg tg--sm'}>
            <input type="checkbox" checked={editMode} onChange={e => setEditMode(e.target.checked)} />
            Edit chords on chart
          </label>
          <button className="btn btn--ghost btn--sm" onClick={fitToPage} disabled={fitting}>{fitting ? 'Fitting…' : 'Fit to page'}</button>
          {overPages > 1
            ? <span className="bar-warn">⚠ Runs onto {overPages} pages — click <b>Fit to page</b></span>
            : editMode
              ? <span className="preview__bar-hint">Click <b>+</b> above any lyric to add a chord · click a chord to edit · clear it to remove. Changes save into the paste box.</span>
              : <span className="preview__bar-hint">The dashed line marks where a second printed page begins.</span>}
          {window.PUBLIC_SHARING_ENABLED && canPublish
            ? <button className={song.shared ? 'btn btn--sm btn--toggled preview__share' : 'btn btn--ghost btn--sm preview__share'}
                onClick={toggleShare} aria-pressed={!!song.shared}>
                {song.shared ? '● Shared' : 'Share'}
              </button>
            : window.PUBLIC_SHARING_ENABLED
              ? <button className="btn btn--ghost btn--sm preview__share" disabled title="Publishing is currently limited to curator accounts">Private chart</button>
              : <button className="btn btn--ghost btn--sm preview__share" disabled title="Public sharing is paused">Sharing paused</button>}
        </div>
        <div className="preview__scroll">
          {(song.raw || '').trim() === '' ? (
            <div className="starter">
              <div className="starter__title">Your chart appears here</div>
              <ol className="starter__steps">
                <li className="starter__step">
                  <span className="starter__num">1</span>
                  <div>
                    <div className="starter__step-title">Paste your song</div>
                    <div className="starter__step-hint">Any format works — Ultimate Guitar, ChordPro, or plain text. Paste it into the <b>Chords</b> tab on the left.</div>
                  </div>
                </li>
                <li className="starter__step">
                  <span className="starter__num">2</span>
                  <div>
                    <div className="starter__step-title">Clean up paste</div>
                    <div className="starter__step-hint">The ✨ button fixes messy formatting automatically.</div>
                  </div>
                </li>
                <li className="starter__step">
                  <span className="starter__num">3</span>
                  <div>
                    <div className="starter__step-title">Print it</div>
                    <div className="starter__step-hint">One clean page, ready for the music stand.</div>
                  </div>
                </li>
              </ol>
            </div>
          ) : (
            <FitToWidth onMeasure={setContentH}
              deps={[song.textScale, song.chordSize, song.chordColor, song.mono, song.lineSpace, song.secSpace, song.cols, song.railScale, song.railSide, song.lineFit, editMode, song.diagrams, song.transpose, song.nashville, (song.raw || '').length, (song.hiddenSections || []).length, (song.sectionOrder || []).join(',')].join('|')}
              onHideSection={(id) => set(prev => ({ hiddenSections: [...(prev.hiddenSections || []), id] }))}>
              <window.Chart song={live} editable={editMode}
                onEditLine={editLine}
                onHideSection={(id) => set(prev => ({ hiddenSections: [...(prev.hiddenSections || []), id] }))} />
            </FitToWidth>
          )}
        </div>
      </div>
    </div>
  );
}

/* ---------- Sidebar ---------- */
function Sidebar({ page, onNavigate, session }) {
  const lock = (
    <svg className="nav__lock" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" aria-label="Log in to access">
      <rect x="4" y="11" width="16" height="9" rx="2" /><path d="M8 11V7a4 4 0 0 1 8 0v4" />
    </svg>
  );
  const item = (id, label, locked) => (
    <button className={page === id ? 'nav__item on' : 'nav__item'} onClick={() => onNavigate(id)}>
      {label}{locked && lock}
    </button>
  );
  return (
    <nav className="nav" id="primary-navigation" aria-label="Primary navigation">
      <div className="nav__group">Browse</div>
      {item('explore', 'Explore', false)}
      {item('library', 'My Library', !session)}
    </nav>
  );
}

/* ---------- Explore (community / discovery) ---------- */
function Explore({ onOpenViewer, onOpenProfile, session, onNeedAuth }) {
  const [query, setQuery] = useState('');
  const [keyFilter, setKeyFilter] = useState('');
  const [artistFilter, setArtistFilter] = useState('');
  const [shared, setShared] = useState(null); // null = not loaded yet, [] = loaded but empty, [...] = real songs
  const [myLikes, setMyLikes] = useState(new Set());
  const [loadError, setLoadError] = useState('');
  const [retry, setRetry] = useState(0);

  useEffect(() => {
    if (!window.PUBLIC_SHARING_ENABLED) { setShared([]); return; }
    let cancelled = false;
    setLoadError(''); setShared(null);
    window.DB.fetchSharedSongs()
      .then(rows => { if (!cancelled) setShared(rows); })
      .catch(e => { console.warn('fetchSharedSongs failed', e); if (!cancelled) { setLoadError('Could not load shared charts.'); setShared([]); } });
    return () => { cancelled = true; };
  }, [retry]);

  useEffect(() => {
    if (!shared || !shared.length || !session) { setMyLikes(new Set()); return; }
    let cancelled = false;
    window.DB.fetchMyLikes(shared.map(s => s.id))
      .then(ids => { if (!cancelled) setMyLikes(new Set(ids)); })
      .catch(e => console.warn('fetchMyLikes failed', e));
    return () => { cancelled = true; };
  }, [shared, session]);

  const all = shared || [];
  const artists = useMemo(() => Array.from(new Set(all.map(c => c.artist).filter(Boolean))).sort(), [all]);

  const visible = useMemo(() => {
    const q = query.trim().toLowerCase();
    return all.filter(c => {
      if (q && !((c.title || '').toLowerCase().includes(q) || (c.artist || '').toLowerCase().includes(q))) return false;
      if (keyFilter && c.origKey !== keyFilter) return false;
      if (artistFilter && c.artist !== artistFilter) return false;
      return true;
    });
  }, [all, query, keyFilter, artistFilter]);

  const featured = useMemo(() => [...all].sort((a, b) => (b.likeCount || 0) - (a.likeCount || 0)).slice(0, 4), [all]);

  const filtering = query.trim() || keyFilter || artistFilter;
  const card = (c) => (
    <div key={c.id} className="card card--community" role="button" tabIndex="0" onClick={() => onOpenViewer(c)}
      onKeyDown={e => { if (e.target === e.currentTarget && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); onOpenViewer(c); } }}>
      <div className="card__title">{c.title}</div>
      <div className="card__sub">{c.artist}</div>
      <div className="card__meta"><span>Key {c.origKey}</span>{c.bpm ? <span>{c.bpm} bpm</span> : null}
        <span>Chart by <button className="handle-link" onClick={(e) => { e.stopPropagation(); onOpenProfile(c.contributorHandle); }}>{handle(c.contributorHandle)}</button></span>
        <LikeButton songId={c.id} count={c.likeCount || 0} liked={myLikes.has(c.id)} session={session} onNeedAuth={onNeedAuth} />
      </div>
    </div>
  );
  const section = (label, tag, items) => (
    <div className="lib__group">
      <h2 className="lib__group-hd">{label} <span className="tag">{tag}</span></h2>
      <div className="lib__grid lib__grid--community">{items.map(card)}</div>
    </div>
  );

  return (
    <div className="lib">
      <div className="lib__hero">
        <div>
          <h1>Explore</h1>
          <p>Find songs shared by other leaders. Click any sheet to preview it.</p>
        </div>
      </div>

      {window.PUBLIC_SHARING_ENABLED && <div className="lib__filters">
        <input className="lib__search" aria-label="Search shared charts" placeholder="Search any song or artist…" value={query} onChange={e => setQuery(e.target.value)} />
        <select aria-label="Filter shared charts by key" value={keyFilter} onChange={e => setKeyFilter(e.target.value)}>
          <option value="">All keys</option>
          {ALL_KEYS.map(k => <option key={k} value={k}>{k}</option>)}
        </select>
        <select aria-label="Filter shared charts by artist" value={artistFilter} onChange={e => setArtistFilter(e.target.value)}>
          <option value="">All artists</option>
          {artists.map(a => <option key={a} value={a}>{a}</option>)}
        </select>
      </div>}

      {!window.PUBLIC_SHARING_ENABLED ? (
        <div className="empty">
          <div className="empty__glyph">♪</div>
          <div className="empty__title">Community sharing is paused</div>
          <div className="empty__hint">Private chart libraries remain available while we complete a lyrics-licensing review.</div>
        </div>
      ) : loadError ? (
        <div className="empty" role="alert">
          <div className="empty__title">Shared charts could not be loaded</div>
          <div className="empty__hint">Check your connection and try again.</div>
          <button className="btn btn--ghost btn--sm" onClick={() => setRetry(n => n + 1)}>Retry</button>
        </div>
      ) : shared === null ? (
        <div className="empty"><span className="spin" /> Loading shared charts…</div>
      ) : shared.length === 0 ? (
        <div className="empty">
          <div className="empty__glyph">♪</div>
          <div className="empty__title">No charts shared yet</div>
          <div className="empty__hint">Curated charts will appear here as they are published.</div>
        </div>
      ) : filtering
        ? (visible.length
            ? <div className="lib__grid lib__grid--community">{visible.map(card)}</div>
            : <p className="lib__note">No songs match those filters.</p>)
        : <>
            {section('Featured', 'most liked', featured)}
            {section('Recently shared', 'newest', all)}
          </>}
    </div>
  );
}

/* ---------- Sheet viewer (read-only, others' songs) ---------- */
function SheetViewer({ song, onBack, backLabel, onAdd, canAdd, onOpenProfile, session, onNeedAuth }) {
  const [zoom, setZoom] = useState(1);
  const [dark, setDark] = useState(() => {
    try { return localStorage.getItem('chart-dark') === '1'; } catch (e) { return false; }
  });
  const toggleDark = () => setDark(d => {
    const next = !d;
    try { localStorage.setItem('chart-dark', next ? '1' : ''); } catch (e) {}
    return next;
  });
  const live = useMemo(
    () => withParse({ ...song, raw: song.raw || '', textScale: (song.textScale || 1) * zoom }),
    [song, zoom]
  );
  const hasContent = (song.raw || '').trim().length > 0;
  const [liked, setLiked] = useState(false);
  useEffect(() => {
    let cancelled = false;
    if (!session) { setLiked(false); return; }
    window.DB.fetchMyLikes([song.id])
      .then(ids => { if (!cancelled) setLiked(ids.includes(song.id)); })
      .catch(e => console.warn('fetchMyLikes failed', e));
    return () => { cancelled = true; };
  }, [song.id, session]);
  return (
    <div className="viewer">
      <div className="viewer__bar">
        <button className="btn btn--ghost btn--sm" onClick={onBack}>← {backLabel || 'Explore'}</button>
        <div className="viewer__meta">
          <strong>{song.title}</strong><span className="muted">{song.artist} · Key {song.origKey}{song.bpm ? ' · ' + song.bpm + ' bpm' : ''} · Chart by <button className="handle-link" onClick={() => onOpenProfile(song.contributorHandle)}>{handle(song.contributorHandle)}</button></span>
        </div>
        <LikeButton songId={song.id} count={song.likeCount || 0} liked={liked} session={session} onNeedAuth={onNeedAuth} />
        {hasContent && (
          <span className="viewctl">
            <button onClick={() => setZoom(z => Math.max(0.7, +(z - 0.1).toFixed(2)))} aria-label="Use smaller chart text">A−</button>
            <button onClick={() => setZoom(z => Math.min(1.6, +(z + 0.1).toFixed(2)))} aria-label="Use larger chart text">A+</button>
            <button onClick={toggleDark} aria-pressed={dark} aria-label={dark ? 'Use light chart background' : 'Use dark chart background'}>{dark ? '☀' : '☾'}</button>
          </span>
        )}
        <button className="btn btn--primary btn--sm" onClick={() => onAdd(song)}>{canAdd ? 'Add to my library' : 'Log in to save'}</button>
      </div>
      <div className={dark ? 'viewer__scroll chartdark' : 'viewer__scroll'}>
        {hasContent
          ? <window.Chart song={live} editable={false} />
          : <div className="viewer__placeholder">
              <p>This is a shared listing — its chord chart hasn’t been published yet.</p>
              <p className="muted">Use <b>Add to my library</b> to create your own copy and paste in the chords.</p>
            </div>}
      </div>
    </div>
  );
}

/* ---------- Profile (public @handle page) ---------- */
function ProfileView({ handle: bareHandle, onOpenSong, onBack, session, onNeedAuth }) {
  const [songs, setSongs] = useState(null); // null = loading, [] = loaded but empty, [...] = real songs
  const [myLikes, setMyLikes] = useState(new Set());
  const [loadError, setLoadError] = useState('');
  const [retry, setRetry] = useState(0);

  useEffect(() => {
    let cancelled = false;
    setSongs(null); setLoadError('');
    window.DB.fetchSharedSongsByOwner(bareHandle)
      .then(rows => { if (!cancelled) setSongs(rows); })
      .catch(e => { console.warn('fetchSharedSongsByOwner failed', e); if (!cancelled) { setLoadError('Could not load this profile.'); setSongs([]); } });
    return () => { cancelled = true; };
  }, [bareHandle, retry]);

  useEffect(() => {
    if (!songs || !songs.length || !session) { setMyLikes(new Set()); return; }
    let cancelled = false;
    window.DB.fetchMyLikes(songs.map(s => s.id))
      .then(ids => { if (!cancelled) setMyLikes(new Set(ids)); })
      .catch(e => console.warn('fetchMyLikes failed', e));
    return () => { cancelled = true; };
  }, [songs, session]);

  const count = songs ? songs.length : 0;

  return (
    <div className="profile">
      <div className="viewer__bar">
        <button className="btn btn--ghost btn--sm" onClick={onBack}>← Explore</button>
      </div>
      <div className="profile__hero">
        <span className="profile__avatar">{bareHandle.slice(0, 1).toUpperCase()}</span>
        <div>
          <h1>@{bareHandle}</h1>
          <p className="muted">{count} contributed chart{count === 1 ? '' : 's'}</p>
        </div>
      </div>
      {bareHandle === 'onepage.library' && <p className="profile__about">Starter charts curated for OnePage. Artist and songwriter credits refer to the underlying songs; this profile prepared the OnePage chart versions.</p>}
      {loadError ? (
        <div className="empty" role="alert"><div className="empty__title">Profile charts could not be loaded</div><button className="btn btn--ghost btn--sm" onClick={() => setRetry(n => n + 1)}>Retry</button></div>
      ) : songs === null ? (
        <div className="empty"><span className="spin" /> Loading charts…</div>
      ) : songs.length === 0 ? (
        <div className="empty">
          <div className="empty__glyph">♪</div>
          <div className="empty__title">No shared charts yet</div>
          <div className="empty__hint">Charts this user shares to Explore will show up here.</div>
        </div>
      ) : (
        <div className="lib__grid lib__grid--community">
          {songs.map(c => (
            <div key={c.id} className="card card--community" role="button" tabIndex="0" onClick={() => onOpenSong(c)}
              onKeyDown={e => { if (e.target === e.currentTarget && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); onOpenSong(c); } }}>
              <div className="card__title">{c.title}</div>
              <div className="card__sub">{c.artist}</div>
              <div className="card__meta"><span>Key {c.origKey}</span>{c.bpm ? <span>{c.bpm} bpm</span> : null}
                <span>Chart by @{c.contributorHandle}</span>
                <LikeButton songId={c.id} count={c.likeCount || 0} liked={myLikes.has(c.id)} session={session} onNeedAuth={onNeedAuth} />
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/* ---------- Setlist print view ---------- */
function SetprintView({ folder, songs, songFolders, onBack }) {
  const members = useMemo(() => {
    const posOf = (songId) => {
      const sf = songFolders.find(x => x.song_id === songId && x.folder_id === folder.id);
      return sf && sf.position != null ? sf.position : 9999;
    };
    return songs
      .filter(s => songFolders.some(sf => sf.song_id === s.id && sf.folder_id === folder.id))
      .map((s, idx) => ({ s, idx, pos: posOf(s.id) }))
      .sort((a, b) => a.pos - b.pos || a.idx - b.idx)
      .map(x => x.s);
  }, [folder, songs, songFolders]);

  return (
    <div className="setprint">
      <div className="setprint__bar">
        <button className="btn btn--ghost btn--sm" onClick={onBack}>← Back</button>
        <div className="setprint__meta"><strong>{folder.name}</strong><span className="muted">{members.length} song{members.length === 1 ? '' : 's'}</span></div>
        <button className="btn btn--primary btn--sm" onClick={() => window.print()}>Print</button>
      </div>
      <div className="setprint__body">
        {members.map(s => <window.Chart key={s.id} song={withParse(s)} editable={false} />)}
      </div>
    </div>
  );
}

/* ---------- Auth screen (email + password) ---------- */
function AuthScreen({ onBack }) {
  const [mode, setMode] = useState('signin'); // 'signin' | 'signup'
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const [notice, setNotice] = useState('');

  const submit = async (e) => {
    e.preventDefault();
    setErr(''); setNotice(''); setBusy(true);
    try {
      if (mode === 'signup') {
        const data = await window.DB.signUp(email.trim(), password);
        // if email confirmations are on, there's no session yet
        if (!data.session) setNotice('Check your email to confirm your account, then sign in.');
      } else {
        await window.DB.signIn(email.trim(), password);
      }
    } catch (e2) {
      setErr(e2.message || 'Something went wrong.');
    }
    setBusy(false);
  };

  return (
    <div className="auth">
      <div className="auth__card">
        {onBack && <button className="btn btn--ghost btn--sm auth__back" onClick={onBack}>← Back to Explore</button>}
        <div className="brand auth__brand"><span className="brand__mark">◷</span> OnePage <em>charts</em></div>
        <h1>{mode === 'signup' ? 'Create your account' : 'Welcome back'}</h1>
        <p className="auth__lead">{mode === 'signup' ? 'Your charts sync to the cloud and stay private to you.' : 'Sign in to your library.'}</p>
        <form onSubmit={submit}>
          <label>Email<input type="email" value={email} autoFocus required autoComplete="email"
            onChange={e => setEmail(e.target.value)} placeholder="you@example.com" /></label>
          <label>Password<input type="password" value={password} required minLength={6} autoComplete={mode === 'signup' ? 'new-password' : 'current-password'}
            onChange={e => setPassword(e.target.value)} placeholder="••••••••" /></label>
          {err && <div className="auth__err">{err}</div>}
          {notice && <div className="auth__notice">{notice}</div>}
          <button className="btn btn--primary auth__submit" type="submit" disabled={busy}>
            {busy ? 'Please wait…' : mode === 'signup' ? 'Sign up' : 'Sign in'}
          </button>
        </form>
        <div className="auth__switch">
          {mode === 'signup'
            ? <>Already have an account? <button className="btn btn--ghost btn--sm" onClick={() => { setMode('signin'); setErr(''); setNotice(''); }}>Sign in</button></>
            : <>New here? <button className="btn btn--ghost btn--sm" onClick={() => { setMode('signup'); setErr(''); setNotice(''); }}>Create an account</button></>}
        </div>
      </div>
    </div>
  );
}

/* ---------- Root ---------- */
function App() {
  const [songs, setSongs] = useState([]);
  const [loaded, setLoaded] = useState(false);
  const [dbError, setDbError] = useState(null);
  const [saveError, setSaveError] = useState(null);
  const [folders, setFolders] = useState([]);
  const [songFolders, setSongFolders] = useState([]);
  const [query, setQuery] = useState('');
  const [keyFilter, setKeyFilter] = useState('');
  const [artistFilter, setArtistFilter] = useState('');
  const [groupBy, setGroupBy] = useState('flat');
  const [view, setView] = useState('explore');
  const [viewerSong, setViewerSong] = useState(null);
  const [viewerFrom, setViewerFrom] = useState('explore'); // 'explore' | 'profile' — where the viewer's back button returns to
  const [profileHandle, setProfileHandle] = useState(null);
  const [printFolder, setPrintFolder] = useState(null);
  const [navOpen, setNavOpen] = useState(() => typeof window === 'undefined' || window.innerWidth > 860);
  const [confirmDeleteId, setConfirmDeleteId] = useState(null);
  const [currentId, setCurrentId] = useState(null);
  const [session, setSession] = useState(null);
  const [authReady, setAuthReady] = useState(false);
  const [profile, setProfile] = useState(null);
  const [entitlements, setEntitlements] = useState(new Set());
  const [showProfileSetup, setShowProfileSetup] = useState(false);
  const [recoveryQueue, setRecoveryQueue] = useState([]);
  const [loadAttempt, setLoadAttempt] = useState(0);
  const [saveState, setSaveState] = useState('saved');
  const [history, setHistory] = useState({ past: [], future: [] });
  const [tw] = useState(TWEAK_DEFAULTS);
  const songsRef = useRef(songs); songsRef.current = songs;
  const lastPushRef = useRef(0);
  const revisionRef = useRef({});
  const saveChainsRef = useRef({});
  const serverUpdatedRef = useRef({});
  const draftWritesRef = useRef({});
  const user = session ? session.user.email : null;

  // track the auth session
  useEffect(() => {
    let unsub = () => {};
    (async () => {
      setSession(await window.DB.getSession());
      setAuthReady(true);
      unsub = window.DB.onAuthChange(s => setSession(s));
    })();
    return () => unsub();
  }, []);

  useEffect(() => {
    let cancelled = false;
    if (!session) { setProfile(null); setEntitlements(new Set()); return; }
    Promise.all([window.DB.fetchMyProfile(), window.DB.fetchEntitlements()])
      .then(([row, features]) => {
        if (cancelled) return;
        setProfile(row);
        setEntitlements(new Set(features));
        if (!row) setShowProfileSetup(true);
      })
      .catch(error => { console.warn('profile/entitlement load failed', error); setEntitlements(new Set()); });
    return () => { cancelled = true; };
  }, [session]);

  // load this user's library whenever they sign in; clear it on sign-out
  useEffect(() => {
    if (!session) { setSongs([]); setFolders([]); setSongFolders([]); setLoaded(false); return; }
    let cancelled = false;
    (async () => {
      setLoaded(false);
      try {
        const [remoteSongs, remoteFolders, remoteSongFolders] = await Promise.all([
          window.DB.fetchSongs(), window.DB.fetchFolders(), window.DB.fetchSongFolders(),
        ]);
        if (cancelled) return;
        let finalSongs = remoteSongs;
        const userId = session.user.id;
        const seedFlag = 'onepage-seeded:' + userId;
        let alreadySeeded = true;
        try { alreadySeeded = !!localStorage.getItem(seedFlag); } catch (e) {}
        if (remoteSongs.length === 0 && !alreadySeeded) {
          const sample = window.AppData.samples[0];
          const demo = newSongRecord({
            title: sample.title, artist: sample.artist, origKey: sample.origKey, bpm: sample.bpm, raw: sample.raw,
            scripture: 'Demo chart — explore it, edit it, or delete it.',
          });
          finalSongs = [demo, ...remoteSongs];
          window.DB.upsertSong(demo)
            .then(() => { try { localStorage.setItem(seedFlag, '1'); } catch (e) {} })
            .catch(e => console.error(e));
          window.showToast('We added a demo chart to get you started');
        }
        let drafts = [];
        try { drafts = await window.Drafts.list(userId); }
        catch (error) { console.warn('draft recovery unavailable', error); }
        const conflicts = [];
        const restoredDrafts = [];
        for (const draft of drafts) {
          const remote = finalSongs.find(song => song.id === draft.songId);
          if (remote && remote.updatedAt && draft.song.updatedAt && remote.updatedAt !== draft.song.updatedAt) {
            conflicts.push({ ...draft, remote });
            continue;
          }
          revisionRef.current[draft.songId] = draft.revision || 1;
          finalSongs = [draft.song, ...finalSongs.filter(song => song.id !== draft.songId)];
          restoredDrafts.push(draft);
        }
        setRecoveryQueue(conflicts);
        setSongs(finalSongs);
        restoredDrafts.forEach(draft => queueSongSave(draft.song, draft.revision || 1).catch(() => {}));
        setFolders(remoteFolders);
        setSongFolders(remoteSongFolders);
        setDbError(null);
      } catch (e) {
        if (cancelled) return;
        console.error(e);
        setDbError(e.message || String(e));
      }
      if (!cancelled) setLoaded(true);
    })();
    return () => { cancelled = true; };
  }, [session, loadAttempt]);

  // Wrap every cloud write: clear the warning on success, surface it on failure.
  const persist = (p, rollback) => p.then(() => setSaveError(null)).catch(e => {
    console.error(e);
    if (rollback) rollback();
    setSaveError("Couldn't save to the cloud — your latest change may not be synced.");
  });

  const createSetlist = (name) => {
    const nm = (name || '').trim();
    if (!nm) return;
    const folder = { id: 'folder-' + crypto.randomUUID(), name: nm, type: 'setlist' };
    setFolders(prev => [...prev, folder]);
    persist(window.DB.createFolder(folder), () => setFolders(prev => prev.filter(f => f.id !== folder.id)));
  };
  const deleteSetlist = (id) => {
    const removedFolder = folders.find(f => f.id === id);
    const removedMemberships = songFolders.filter(sf => sf.folder_id === id);
    setFolders(prev => prev.filter(f => f.id !== id));
    setSongFolders(prev => prev.filter(sf => sf.folder_id !== id));
    persist(window.DB.deleteFolder(id), () => {
      if (removedFolder) setFolders(prev => [...prev, removedFolder]);
      setSongFolders(prev => [...prev, ...removedMemberships]);
    });
  };
  const toggleSongFolder = (songId, folderId) => {
    const existing = songFolders.find(sf => sf.song_id === songId && sf.folder_id === folderId);
    const enabled = !existing;
    setSongFolders(prev => enabled
      ? [...prev, { song_id: songId, folder_id: folderId, position: 9999 }]
      : prev.filter(sf => !(sf.song_id === songId && sf.folder_id === folderId)));
    persist(window.DB.setSongFolder(songId, folderId, enabled), () => {
      setSongFolders(prev => enabled
        ? prev.filter(sf => !(sf.song_id === songId && sf.folder_id === folderId))
        : [...prev, existing]);
    });
  };
  const reorderFolder = (folderId, orderedSongIds) => {
    const previous = songFolders.filter(sf => sf.folder_id === folderId);
    setSongFolders(prev => {
      const others = prev.filter(sf => sf.folder_id !== folderId || !orderedSongIds.includes(sf.song_id));
      const reordered = orderedSongIds.map((songId, index) => {
        const existing = prev.find(sf => sf.song_id === songId && sf.folder_id === folderId);
        return { ...(existing || { song_id: songId, folder_id: folderId }), position: index };
      });
      return [...others, ...reordered];
    });
    persist(window.DB.saveFolderOrder(folderId, orderedSongIds), () => {
      setSongFolders(prev => [...prev.filter(sf => sf.folder_id !== folderId), ...previous]);
    });
  };
  const openSetprint = (folder) => { setPrintFolder(folder); setView('setprint'); };

  const current = songs.find(s => s.id === currentId);
  const resetHistory = () => { setHistory({ past: [], future: [] }); lastPushRef.current = 0; };
  const recordRecovery = (song) => {
    const revision = (revisionRef.current[song.id] || 0) + 1;
    revisionRef.current[song.id] = revision;
    if (session) {
      draftWritesRef.current[song.id] = window.Drafts.put(session.user.id, song, revision)
        .catch(error => console.warn('draft save failed', error));
    }
    return revision;
  };

  // functional patch so rapid/back-to-back edits never clobber each other; snapshots feed undo.
  // rapid edits within 500ms coalesce into ONE undo step (so dragging a slider isn't 40 undos).
  const patchCurrent = (patchOrFn) => {
    const cur = songsRef.current.find(s => s.id === currentId);
    if (!cur) return;
    const patch = typeof patchOrFn === 'function' ? patchOrFn(cur) : patchOrFn;
    if (!patch || !Object.keys(patch).length) return;
    const now = Date.now();
    const coalesce = now - lastPushRef.current < 500;
    lastPushRef.current = now;
    setHistory(h => ({ past: (coalesce && h.past.length ? h.past : [...h.past, cur]).slice(-120), future: [] }));
    const nextSong = { ...cur, ...patch, updatedAt: serverUpdatedRef.current[cur.id] || cur.updatedAt };
    recordRecovery(nextSong);
    setSongs(prev => prev.map(s => s.id === currentId ? nextSong : s));
  };
  const undo = () => {
    if (!history.past.length) return;
    const cur = songsRef.current.find(s => s.id === currentId);
    const snap = history.past[history.past.length - 1];
    recordRecovery(snap);
    setSongs(ss => ss.map(s => s.id === currentId ? snap : s));
    setHistory({ past: history.past.slice(0, -1), future: cur ? [...history.future, cur] : history.future });
    lastPushRef.current = 0;
  };
  const redo = () => {
    if (!history.future.length) return;
    const cur = songsRef.current.find(s => s.id === currentId);
    const snap = history.future[history.future.length - 1];
    recordRecovery(snap);
    setSongs(ss => ss.map(s => s.id === currentId ? snap : s));
    setHistory({ past: cur ? [...history.past, cur] : history.past, future: history.future.slice(0, -1) });
    lastPushRef.current = 0;
  };
  useEffect(() => {
    if (view !== 'editor') return;
    const onKey = (e) => {
      if (!(e.metaKey || e.ctrlKey) || (e.key !== 'z' && e.key !== 'Z')) return;
      const t = e.target;
      if (t && (t.tagName === 'TEXTAREA' || t.tagName === 'INPUT')) return;   // let native text undo work
      e.preventDefault();
      if (e.shiftKey) redo(); else undo();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [view, history, currentId]);

  // Serialize saves per song. A failed request leaves its exact IndexedDB draft
  // intact; later revisions continue after it instead of racing it.
  const saveTimerRef = useRef(null);
  const pendingSaveRef = useRef(null);
  const queueSongSave = (song, revision) => {
    if (!session || !song) return Promise.resolve();
    setSaveState('saving'); setSaveError(null);
    const previous = saveChainsRef.current[song.id] || Promise.resolve();
    const chain = previous.catch(() => {})
      .then(() => draftWritesRef.current[song.id])
      .then(() => window.DB.upsertSong(song))
      .then(async result => {
        if (result && result.updated_at) serverUpdatedRef.current[song.id] = result.updated_at;
        try { await window.Drafts.remove(session.user.id, song.id, revision); }
        catch (error) { console.warn('could not clear recovery draft', error); }
      })
      .then(() => {
        if (saveChainsRef.current[song.id] === chain) { setSaveState('saved'); setSaveError(null); }
      })
      .catch(error => {
        console.error(error);
        if (saveChainsRef.current[song.id] === chain) {
          setSaveState('error');
          setSaveError("Couldn't save to the cloud — a recovery draft is stored on this device.");
        }
        throw error;
      });
    saveChainsRef.current[song.id] = chain;
    return chain;
  };
  useEffect(() => {
    if (!loaded || !current) return;
    const revision = revisionRef.current[current.id] || 0;
    if (!revision) return;
    pendingSaveRef.current = { song: current, revision };
    clearTimeout(saveTimerRef.current);
    saveTimerRef.current = setTimeout(() => {
      const pending = pendingSaveRef.current;
      pendingSaveRef.current = null;
      if (pending) queueSongSave(pending.song, pending.revision).catch(() => {});
    }, 600);
    return () => clearTimeout(saveTimerRef.current);
  }, [current, loaded]);

  // push any pending edit immediately (leaving the editor, closing the tab)
  const flushPendingSave = () => {
    if (!pendingSaveRef.current) return Promise.resolve();
    clearTimeout(saveTimerRef.current);
    const pending = pendingSaveRef.current;
    pendingSaveRef.current = null;
    return queueSongSave(pending.song, pending.revision);
  };
  const flushRef = useRef(flushPendingSave); flushRef.current = flushPendingSave;
  useEffect(() => {
    const onUnload = () => flushRef.current().catch(() => {});
    window.addEventListener('beforeunload', onUnload);
    return () => window.removeEventListener('beforeunload', onUnload);
  }, []);

  const openSong = (id) => { resetHistory(); setCurrentId(id); setView('editor'); };
  const newSong = () => {
    resetHistory();
    const r = newSongRecord();
    setSongs(prev => [r, ...prev]); setCurrentId(r.id); setView('editor');
    const revision = recordRecovery(r);
    queueSongSave(r, revision).catch(() => {});
  };
  const importSongs = (imported) => {
    resetHistory();
    const records = imported.map(imp => {
      const extra = { raw: imp.raw || '' };
      if (imp.title) extra.title = imp.title;
      if (imp.artist) extra.artist = imp.artist;
      if (imp.writers) extra.writers = imp.writers;
      if (imp.copyrightNotice) extra.copyrightNotice = imp.copyrightNotice;
      if (imp.ccli) extra.ccli = imp.ccli;
      if (imp.bpm) extra.bpm = imp.bpm;
      if (imp.time) extra.time = imp.time;
      if (imp.scripture) extra.scripture = imp.scripture;
      if (imp.origKey) extra.origKey = imp.origKey;
      return newSongRecord(extra);
    });
    setSongs(prev => [...records, ...prev]);
    records.forEach(r => { const revision = recordRecovery(r); queueSongSave(r, revision).catch(() => {}); });
    window.showToast('Imported ' + records.length + ' chart' + (records.length === 1 ? '' : 's'));
    if (records.length === 1) { setCurrentId(records[0].id); setView('editor'); }
  };
  const importBatchSongs = async (candidates, onProgress) => {
    if (!session || !entitlements.has('drive_import')) throw new Error('This account is not allowed to batch import charts.');
    const jobs = candidates.map(candidate => ({ candidate, record: newSongRecord({
      title: candidate.title || 'Untitled Song', artist: candidate.artist || '', writers: candidate.writers || '',
      copyrightNotice: candidate.copyrightNotice || '', origKey: candidate.origKey, bpm: candidate.bpm || '', time: candidate.time || '4/4',
      ccli: candidate.ccli || '', scripture: candidate.scripture || '', raw: candidate.raw || '', shared: false,
    }) }));
    const saved = [];
    let next = 0;
    let firstError = null;
    const worker = async () => {
      while (next < jobs.length) {
        const job = jobs[next++];
        try {
          await window.DB.upsertSong(job.record);
          saved.push(job.record);
          await window.DB.saveSongSource(job.record.id, job.candidate);
          onProgress(saved.length);
        } catch (e) { firstError = firstError || e; }
      }
    };
    await Promise.all(Array.from({ length: Math.min(3, jobs.length) }, worker));
    if (saved.length) setSongs(prev => [...saved, ...prev.filter(song => !saved.some(row => row.id === song.id))]);
    if (firstError || saved.length !== jobs.length) throw new Error('Some charts could not be saved. Saved charts remain private; review your library and retry the failed files.');
    window.showToast('Saved ' + saved.length + ' private chart' + (saved.length === 1 ? '' : 's') + ' to your library');
    setView('library');
  };
  const dupSong = () => {
    if (!current) return;
    const r = { ...current, id: 'song-' + crypto.randomUUID(), title: current.title + ' (copy)' };
    setSongs(prev => [r, ...prev]); resetHistory(); setCurrentId(r.id);
    const revision = recordRecovery(r);
    queueSongSave(r, revision).catch(() => {});
  };
  const delSong = (id) => setConfirmDeleteId(id);
  const confirmDeleteSong = () => {
    const id = confirmDeleteId;
    setConfirmDeleteId(null);
    if (!id) return;
    const removed = songsRef.current.find(song => song.id === id);
    setSongs(prev => prev.filter(s => s.id !== id));
    persist(window.DB.deleteSong(id), () => { if (removed) setSongs(prev => [removed, ...prev]); });
  };
  const addCommunity = (c) => {
    if (!session) { setView('auth'); return; }  // need an account to save a copy
    resetHistory();
    const r = newSongRecord({
      title: c.title, artist: c.artist, writers: c.writers, copyrightNotice: c.copyrightNotice, origKey: c.origKey, bpm: c.bpm,
      time: c.time, ccli: c.ccli, scripture: c.scripture, raw: c.raw,
      nashville: c.nashville, diagrams: c.diagrams, railSide: c.railSide, roadmap: c.roadmap,
      mono: c.mono, cols: c.cols, textScale: c.textScale, chordSize: c.chordSize, chordColor: c.chordColor, lineSpace: c.lineSpace, secSpace: c.secSpace,
      railScale: c.railScale, lineFit: c.lineFit, sectionOrder: c.sectionOrder, hiddenSections: c.hiddenSections,
      owner: 'You', shared: false,
    });
    setSongs(prev => [r, ...prev]); setCurrentId(r.id); setViewerSong(null); setView('editor');
    const revision = recordRecovery(r);
    queueSongSave(r, revision).catch(() => {});
  };
  const openViewer = (c) => { setViewerSong(c); setViewerFrom(view === 'profile' ? 'profile' : 'explore'); setView('viewer'); };
  const doPrint = () => window.print();
  const publishCurrent = async song => {
    await flushPendingSave();
    if (saveChainsRef.current[song.id]) await saveChainsRef.current[song.id];
    await window.DB.publishSongs([song.id], true);
    const now = new Date().toISOString();
    setSongs(prev => prev.map(row => row.id === song.id ? { ...row, shared: true, sharedAt: now, publicationAttestedAt: now, contributorHandle: profile && profile.handle } : row));
    window.showToast('Shared to Explore — anyone can view this chart');
  };

  // ---- hash routing: #/@handle → public profile page ----
  const HASH_RE = /^#\/@([\w.\-]+)$/;
  const applyHash = () => {
    const m = window.location.hash.match(HASH_RE);
    if (m) { setProfileHandle(m[1]); setView('profile'); }
    else { setProfileHandle(null); setView(v => v === 'profile' ? 'explore' : v); }
  };
  useEffect(() => {
    applyHash();
    window.addEventListener('hashchange', applyHash);
    return () => window.removeEventListener('hashchange', applyHash);
  }, []);
  const openProfile = (ownerHandle) => {
    const bare = String(ownerHandle || '').replace(/^@+/, '');
    setProfileHandle(bare);
    setView('profile');
    if (window.location.hash !== '#/@' + bare) {
      window.location.hash = '/@' + bare;
    }
  };
  const leaveProfile = () => {
    if (window.location.hash) window.history.replaceState(null, '', window.location.pathname + window.location.search);
    setView('explore');
  };
  const leaveEditor = () => { flushPendingSave(); setView('library'); };
  const signOut = () => { flushPendingSave(); window.DB.signOut(); setView('explore'); };
  const createPublicProfile = async (handleValue) => {
    const row = await window.DB.createProfile(handleValue);
    setProfile(row); setShowProfileSetup(false);
    window.showToast('Public handle saved');
  };
  const recovery = recoveryQueue[0] || null;
  const useRecoveryDraft = () => {
    if (!recovery) return;
    revisionRef.current[recovery.songId] = recovery.revision || 1;
    setSongs(prev => [recovery.song, ...prev.filter(song => song.id !== recovery.songId)]);
    setRecoveryQueue(prev => prev.slice(1));
    queueSongSave(recovery.song, recovery.revision || 1).catch(() => {});
  };
  const keepCloudCopy = () => {
    if (!recovery || !session) return;
    window.Drafts.remove(session.user.id, recovery.songId).catch(error => console.warn(error));
    setRecoveryQueue(prev => prev.slice(1));
  };
  // My Library / editing require an account; Explore + viewer are public.
  const navigate = (target) => {
    if ((target === 'library' || target === 'editor') && !session) { setView('auth'); return; }
    setView(target);
  };
  // after a successful login from the auth screen, land in the library
  useEffect(() => { if (session && view === 'auth') setView('library'); }, [session]);

  const rootVars = { '--ch-size': tw.chordSize, '--ly-font': tw.lyricFont === 'serif' ? 'var(--serif)' : 'var(--ui)' };

  if (!authReady) return <div className="empty">Loading…</div>;
  if (view === 'auth') return <AuthScreen onBack={() => setView('explore')} />;

  const isList = view === 'explore' || view === 'library';
  return (
    <div className="app" style={rootVars}>
      <div className="topbar">
        <div className="topbar__left">
          {isList && (
            <button className="navtoggle" aria-label={navOpen ? 'Hide sidebar' : 'Show sidebar'} aria-expanded={navOpen} aria-controls="primary-navigation" onClick={() => setNavOpen(o => !o)}>
              <span /><span /><span />
            </button>
          )}
          <div className="brand"><span className="brand__mark">◷</span> OnePage <em>charts</em></div>
        </div>
        <div className="brand__right">
          {session
            ? <>
                {saveState === 'saving'
                  ? <span className="muted" role="status">Saving…</span>
                  : saveError
                    ? <span className="save-warn" title={saveError}>Not saved — recovery copy kept <button onClick={() => setSaveError(null)} aria-label="Dismiss save warning">✕</button></span>
                    : <span className="muted">All changes saved</span>}
                <button className="userchip" onClick={() => { if (!profile) setShowProfileSetup(true); }} aria-label={profile ? 'Public handle @' + profile.handle : 'Set a public handle'}>
                  <span className="avatar">{user.slice(0,1).toUpperCase()}</span><span className="userchip__text">{profile ? '@' + profile.handle : user}</span>
                </button>
                <button className="btn btn--ghost btn--sm" onClick={signOut}>Sign out</button>
              </>
            : <button className="btn btn--primary btn--sm" onClick={() => setView('auth')}>Log in</button>}
        </div>
      </div>
      {isList
        ? <div className={navOpen ? 'shell navdrawer-open' : 'shell'}>
            <div className="navdrawer-overlay" onClick={() => setNavOpen(false)} />
            {navOpen && <Sidebar page={view} onNavigate={(t) => { navigate(t); if (window.innerWidth <= 860) setNavOpen(false); }} session={!!session} />}
            <div className="shell__content">
              {view === 'explore'
                ? <Explore onOpenViewer={openViewer} onOpenProfile={openProfile} session={session} onNeedAuth={() => setView('auth')} />
                : !loaded
                  ? <div className="empty"><span className="spin" /> Loading your library…</div>
                  : dbError
                    ? <div className="empty" role="alert"><div className="empty__title">Your library could not be loaded</div><div className="empty__hint">Check your connection and try again.</div><button className="btn btn--ghost btn--sm" onClick={() => setLoadAttempt(n => n + 1)}>Retry</button></div>
                    : <Library songs={songs} user={user} onOpen={openSong} onNew={newSong} onImport={importSongs} onBatchImport={importBatchSongs} canBatchImport={entitlements.has('drive_import')} onDelete={delSong}
                        folders={folders} songFolders={songFolders} query={query} setQuery={setQuery}
                        keyFilter={keyFilter} setKeyFilter={setKeyFilter} artistFilter={artistFilter} setArtistFilter={setArtistFilter}
                        groupBy={groupBy} setGroupBy={setGroupBy} onCreateSetlist={createSetlist} onDeleteSetlist={deleteSetlist} onToggleFolder={toggleSongFolder}
                        onReorderFolder={reorderFolder} onPrintSetlist={openSetprint} />}
            </div>
          </div>
        : view === 'viewer' && viewerSong
          ? <SheetViewer song={viewerSong} onAdd={addCommunity} canAdd={!!session} onOpenProfile={openProfile}
              session={session} onNeedAuth={() => setView('auth')}
              backLabel={viewerFrom === 'profile' ? 'Profile' : 'Explore'}
              onBack={() => { if (viewerFrom === 'profile' && profileHandle) setView('profile'); else setView('explore'); }} />
        : view === 'profile' && profileHandle
          ? <ProfileView handle={profileHandle} onOpenSong={openViewer} onBack={leaveProfile} session={session} onNeedAuth={() => setView('auth')} />
        : view === 'setprint' && printFolder
          ? <SetprintView folder={printFolder} songs={songs} songFolders={songFolders} onBack={() => setView('library')} />
        : current
          ? <Editor song={current} onChange={patchCurrent} onBack={leaveEditor} onDuplicate={dupSong} onPrint={doPrint}
              onUndo={undo} onRedo={redo} canUndo={history.past.length > 0} canRedo={history.future.length > 0}
              setlists={folders.filter(f => f.type === 'setlist')} songFolders={songFolders} onToggleFolder={toggleSongFolder} onCreateSetlist={createSetlist}
              publicHandle={profile && profile.handle} canPublish={entitlements.has('public_publish')} onPublish={publishCurrent} />
          : <div className="empty">
              <div className="empty__title">Song not found</div>
              <button className="btn btn--ghost btn--sm" onClick={() => setView(session ? 'library' : 'explore')}>Back to {session ? 'library' : 'Explore'}</button>
            </div>}

      {confirmDeleteId && (
        <ConfirmDialog
          title="Delete this chart?"
          body="This can't be undone."
          confirmLabel="Delete chart"
          onCancel={() => setConfirmDeleteId(null)}
          onConfirm={confirmDeleteSong}
        />
      )}
      {showProfileSetup && session && !profile && <ProfileSetup onSave={createPublicProfile} onClose={() => setShowProfileSetup(false)} />}
      {recovery && (
        <ConfirmDialog title="Unsaved edits found" body={'A recovery copy of “' + recovery.song.title + '” differs from the cloud copy.'}
          confirmLabel="Use local draft" onConfirm={useRecoveryDraft} onCancel={keepCloudCopy} />
      )}
      <ToastHost />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
