/* ========================================================================
   WORKSHEETS PAGE — library (workbooks + recents), sheet spreadsheet,
   record drill-in (records panel + JSON-drawer detail). Port of the
   rendering half of js/15-worksheets.js.
   ======================================================================== */

function WsBadge({ p }) {
  const [cls, label] = wsPermInfo(p);
  return <span className={cx('ws-badge', cls)}>{label}</span>;
}

/* ---- library ------------------------------------------------------------- */
function WorksheetsLibrary() {
  useAppState();
  const [newMenuOpen, setNewMenuOpen] = React.useState(false);
  const splitRef = React.useRef(null);
  React.useEffect(() => {
    if (!newMenuOpen) return;
    const onDown = (e) => {
      if (splitRef.current && splitRef.current.contains(e.target)) return;
      setNewMenuOpen(false);
    };
    document.addEventListener('click', onDown);
    return () => document.removeEventListener('click', onDown);
  }, [newMenuOpen]);

  const openSheet = (id) => {state.worksheetRecord = null;state.worksheetId = id;notify();};
  const toggleWb = (id) => {
    if (state.worksheetExpanded.has(id)) state.worksheetExpanded.delete(id);else
    state.worksheetExpanded.add(id);
    notify();
  };

  const SheetRow = ({ s, nested }) =>
  <tr className={cx('ws-row', 'is-sheet', nested && 'nested')} onClick={(e) => {if (e.target.closest('.ws-of')) return;openSheet(s.id);}}>
      <td className="ws-name-cell">
        <span className="ws-name-inner">
          {nested ? <span className="ws-sheet-indent"></span> : <span className="ws-chev-spacer"></span>}
          <span className={cx('ws-row-ico', `ws-ent-${s.type}`)}><Icon name={WS_ENTITY_ICON[s.type]} size={14} /></span>
          <span className="ws-name-text">{s.name}</span>
        </span>
      </td>
      <td>{nested ? <span className="ws-muted">—</span> : <WsBadge p={s.permission} />}</td>
      <td className="ws-num"><span className="ws-muted">—</span></td>
      <td className="ws-num ws-records">{s.records}</td>
      <td className="ws-num">{s.aiCols}</td>
      <td><span className="ws-muted">—</span></td>
      <td className="ws-updated">{s.updated}{s.by ? ` · ${s.by}` : ''}</td>
      <td className="ws-of-cell">
        <button className="ws-of" type="button" aria-label="More"
      onClick={(e) => {e.stopPropagation();showToast({ message: 'Rename · Duplicate · Move · Delete', icon: 'ellipsis-vertical' });}}>
          <Icon name="ellipsis-vertical" size={16} />
        </button>
      </td>
    </tr>;


  return (
    <div className="ws-page">
      <div className="ws-lib-head">
        <h1 className="ws-lib-title">Worksheets</h1>
        <p className="ws-lib-sub">Access past work, start new research</p>
      </div>

      <p className="ws-overline">Pick up where you left off</p>
      <div className="ws-recents">
        {WS_RECENTS.map((r) =>
        <button className="ws-recent" type="button" key={r.sheetId} onClick={() => openSheet(r.sheetId)}>
            <span className={cx('ws-recent-ico', `ws-ent-${r.type}`)}><Icon name={WS_ENTITY_ICON[r.type]} size={20} /></span>
            <span className="ws-recent-body">
              <span className="ws-recent-name">{r.name}</span>
              <span className="ws-recent-meta">{r.workbook}</span>
            </span>
            <span className="ws-recent-count">{r.count}</span>
            <span className="ws-recent-arrow"><Icon name="arrow-right" size={18} /></span>
          </button>
        )}
      </div>

      <div className="ws-divider"></div>

      <div className="ws-wb-head">
        <h2>All Workbooks</h2>
        <span className="ws-count-pill">{WORKBOOKS.length} workbooks</span>
        <span className="ws-wb-head-spacer"></span>
        <div className="ws-split-wrap" ref={splitRef}>
          <div className="ws-split">
            <button className="ws-split-main" type="button" onClick={() => showToast({ message: 'New workbook created', icon: 'book-plus' })}>
              <Icon name="plus" size={14} /> New Workbook
            </button>
            <span className="ws-split-div"></span>
            <button className="ws-split-trig" type="button" aria-label="More create options"
            onClick={(e) => {e.stopPropagation();setNewMenuOpen((o) => !o);}}>
              <Icon name="chevron-down" size={14} />
            </button>
          </div>
          {newMenuOpen ?
          <div className="ws-menu">
              {[['file-plus-2', 'New blank worksheet'], ['upload', 'Import a CSV'], ['search', 'Start from a search…']].map(([icon, label]) =>
            <button className="ws-menu-item" type="button" key={label}
            onClick={() => {setNewMenuOpen(false);showToast({ message: 'Starting new research…', icon: 'sparkles' });}}>
                  <Icon name={icon} size={14} /> {label}
                </button>
            )}
            </div> :
          null}
        </div>
      </div>

      <div className="ws-table-card">
        <table className="ws-table">
          <thead>
            <tr>
              <th className="ws-th-name">Name</th>
              <th>Permissions</th>
              <th className="ws-num">Sheets</th>
              <th className="ws-num">Records</th>
              <th className="ws-num">AI Cols</th>
              <th>Schedule</th>
              <th>Updated</th>
              <th className="ws-of-cell"></th>
            </tr>
          </thead>
          <tbody>
            {WS_SHEETS.filter((s) => s.wb === null).map((s) => <SheetRow s={s} nested={false} key={s.id} />)}
            {WORKBOOKS.map((wb) => {
              const open = state.worksheetExpanded.has(wb.id);
              return (
                <React.Fragment key={wb.id}>
                  <tr className={cx('ws-row', 'is-workbook', open && 'expanded')} onClick={(e) => {if (e.target.closest('.ws-of')) return;toggleWb(wb.id);}}>
                    <td className="ws-name-cell">
                      <span className="ws-name-inner">
                        <span className={cx('ws-chev', open && 'open')}><Icon name="chevron-right" size={16} /></span>
                        <span className="ws-row-ico ws-ico-wb"><Icon name={open ? 'book-open' : 'book'} size={14} /></span>
                        <span className="ws-name-text">{wb.name}</span>
                      </span>
                    </td>
                    <td><WsBadge p={wb.permission} /></td>
                    <td className="ws-num">{wb.sheets}</td>
                    <td className="ws-num ws-records">{wb.records}</td>
                    <td className="ws-num">{wb.aiCols}</td>
                    <td>{wb.schedule ? <span className="ws-sched-link">{wb.schedule}</span> : <span className="ws-muted">—</span>}</td>
                    <td className="ws-updated">{wb.updated}{wb.by ? ` · ${wb.by}` : ''}</td>
                    <td className="ws-of-cell">
                      <button className="ws-of" type="button" aria-label="More"
                      onClick={(e) => {e.stopPropagation();showToast({ message: 'Rename · Duplicate · Move · Delete', icon: 'ellipsis-vertical' });}}>
                        <Icon name="ellipsis-vertical" size={16} />
                      </button>
                    </td>
                  </tr>
                  {open ? wsSheetsInWorkbook(wb.id).map((s) => <SheetRow s={s} nested key={s.id} />) : null}
                </React.Fragment>);

            })}
          </tbody>
        </table>
      </div>

      <div className="ws-dropzone" onClick={() => showToast({ message: 'Choose a CSV to import', icon: 'upload' })}>
        <Icon name="upload" size={16} />
        <span>Drag a CSV here to start new research · <span className="ws-dz-link">or Browse files</span></span>
      </div>
    </div>);

}

/* ---- sheet spreadsheet ------------------------------------------------------ */
function WorksheetSheet({ sheet }) {
  useAppState();
  const [selected, setSelected] = React.useState(() => new Set());
  const [q, setQ] = React.useState('');
  const isAccounts = sheet.type === 'accounts';
  const rows = isAccounts ? wsAccountRecords() : wsContactRecords();
  const srcRecords = (isAccounts ? WS_ACCOUNT_IDS : WS_CONTACT_IDS).
  map((id) => ACCOUNTS.find((a) => a.accountId === id)).filter(Boolean);
  // Merge seeded demo AI columns with user-added ones. A seeded column whose
  // stable id now has a real added column is "claimed" and renders the added
  // column in the seed's original position (re-running keeps placement).
  const seedLabels = (srcRecords[0] ? wsAiSummariesFor(sheet, srcRecords[0]) : []).map((x) => x.label);
  const wsAdded = typeof wsGetAddedColumns === 'function' ? wsGetAddedColumns(sheet.id) : [];
  const addedById = new Map(wsAdded.map((c) => [c.id, c]));
  const claimedSeedIds = new Set(seedLabels.map(wsSeedColId).filter((id) => addedById.has(id)));
  const orderedAi = [];
  seedLabels.forEach((label) => {
    const id = wsSeedColId(label);
    if (addedById.has(id)) orderedAi.push({ kind: 'added', col: addedById.get(id) });else
    orderedAi.push({ kind: 'seed', label });
  });
  wsAdded.forEach((c) => {if (!claimedSeedIds.has(c.id)) orderedAi.push({ kind: 'added', col: c });});

  const toggleRow = (i) => setSelected((prev) => {
    const nx = new Set(prev);
    if (nx.has(i)) nx.delete(i);else nx.add(i);
    return nx;
  });
  const toggleAll = () => setSelected((prev) => {
    if (prev.size === rows.length) return new Set();
    return new Set(rows.map((_, i) => i));
  });
  const allOn = selected.size === rows.length && rows.length > 0;
  const someOn = selected.size > 0 && !allOn;
  const ql = q.toLowerCase().trim();

  const openRecord = (i) => {
    state.worksheetRecord = { sheetId: state.worksheetId, rowIndex: i };
    state.worksheetSelected = new Set();
    state.worksheetDetailSection = 'worksheet';
    notify();
  };

  // Click an AI column header → re-open the modal on its config. Added columns
  // carry real config; seeded demo columns synthesize a (legacy) one. Notes
  // columns aren't editable through the modal.
  const editAiColumn = (it) => {
    if (typeof openAiColumnEditor !== 'function') return;
    let config;
    if (it.kind === 'added') {
      const c = it.col;
      if (c.kind === 'notes') return;
      config = { name: c.name, prompt: c.prompt || '', product: c.product || '', outputType: c.outputType || 'auto', schema: c.schema || [], colId: c.id, legacy: c.legacy };
    } else {
      config = wsSeedAiColumnConfig(it.label, sheet);
    }
    openAiColumnEditor(sheet, config);
  };

  const addedCell = (c, rec, k) => {
    if (c.kind === 'notes') {
      const nv = c.values[rec.accountId];
      return (
        <td className="ws-note-cell" data-notecol={c.id} data-notecol-acct={rec.accountId} key={'c' + k} onClick={(e) => e.stopPropagation()}>
          <span
            className="ws-note-edit" contentEditable suppressContentEditableWarning data-note-input data-placeholder="Add a note…"
            onBlur={(e) => {if (window.wsSetNoteValue) window.wsSetNoteValue(c.id, rec.accountId, e.currentTarget.textContent.trim());}}
            onKeyDown={(e) => {if (e.key === 'Enter' && !e.shiftKey) {e.preventDefault();e.currentTarget.blur();}}}>
            {nv == null ? '' : String(nv)}</span>
        </td>);

    }
    const v = c.values[rec.accountId];
    if (v === undefined) {
      return <td className="ws-ai-cell" data-aicol={c.id} data-aicol-acct={rec.accountId} key={'c' + k}><span className="aic-skel" style={{ display: 'block', width: '80%' }}></span></td>;
    }
    const disp = window.wsFormatAiCell ? window.wsFormatAiCell(v, c.outputType) : String(v);
    return (
      <td className="ws-ai-cell" data-aicol={c.id} data-aicol-acct={rec.accountId} key={'c' + k}>
        <span className="ws-ai-val" title={Array.isArray(v) ? v.join('; ') : String(v)} dangerouslySetInnerHTML={{ __html: disp }}></span>
      </td>);

  };
  const aiCellsFor = (i) => {
    const rec = srcRecords[i];
    const summaries = wsAiSummariesFor(sheet, rec);
    return orderedAi.map((it, k) => {
      if (it.kind === 'added') return addedCell(it.col, rec, k);
      const s = summaries.find((x) => x.label === it.label);
      const txt = s ? s.summary : '';
      return <td className="ws-ai-cell" key={'c' + k}><span className="ws-ai-val" title={txt}>{txt}</span></td>;
    });
  };

  const matches = (r) => !ql || Object.values(r).some((v) => String(v).toLowerCase().includes(ql));

  // AI cells inject raw HTML (some formats carry <i data-lucide> glyphs) —
  // hydrate icons after each render.
  React.useEffect(() => {if (window.lucide) {try {lucide.createIcons();} catch (e) {}}});

  return (
    <div className="ws-page ws-page--sheet">
      <div className="ws-det-head">
        <div><h1 className="ws-det-title">{sheet.name}</h1></div>
        <button className="btn-ghost btn" type="button" onClick={() => showToast({ message: 'Share this worksheet', icon: 'share' })}>
          <Icon name="share" size={14} /> Share
        </button>
      </div>

      <div className="ws-toolbar">
        <button className="ws-tool-btn" type="button" onClick={() => showToast({ message: 'Filter these records', icon: 'sliders-horizontal' })}><Icon name="sliders-horizontal" size={14} /> Filters</button>
        <label className="ws-tool-search">
          <Icon name="search" size={14} />
          <input type="text" placeholder={isAccounts ? 'Search these accounts…' : 'Search these contacts…'} value={q} onChange={(e) => setQ(e.target.value)} />
        </label>
        <button className="ws-tool-btn" type="button" onClick={() => showToast({ message: 'Show / hide columns', icon: 'columns-3' })}><Icon name="columns-3" size={14} /> Columns</button>
        <button className="ws-tool-btn ws-tool-ai" type="button"
        onClick={() => {if (typeof openAiColumnModal === 'function') openAiColumnModal(sheet);}}>
          <Icon name="sparkles" size={14} /> Add Column
        </button>
      </div>

      <div className="ws-sheet-card">
        <table className="ws-grid">
          <thead>
            <tr>
              <th className="ws-cb-cell">
                <label className="cb-wrap">
                  <input type="checkbox" className="row-check" checked={allOn} onChange={toggleAll} />
                  <span className={cx('cb-box', allOn && 'checked', someOn && 'indeterminate')}>
                    {allOn ? <Icon name="check" size={12} /> : someOn ? <Icon name="minus" size={12} /> : null}
                  </span>
                </label>
              </th>
              {isAccounts ?
              <React.Fragment>
                  <th className="ws-th-name">Name</th><th>State</th><th className="ws-num">Population</th><th>Account Type</th><th>Website</th>
                </React.Fragment> :

              <React.Fragment>
                  <th className="ws-th-name ws-col-fit">First Name</th><th className="ws-col-fit">Last Name</th><th>Title</th><th>Department</th><th>Email</th><th className="ws-col-fit">Phone</th><th>Confidence Score</th><th>Account Name</th>
                </React.Fragment>
              }
              {orderedAi.map((it, k) => {
                if (it.kind === 'seed') {
                  return <th key={'h' + k} className="ws-ai-head ws-ai-head-edit" title="Edit AI column" onClick={() => editAiColumn(it)}><Icon name="sparkles" className="ws-ai-head-ico" size={13} />{it.label}</th>;
                }
                const c = it.col;
                if (c.kind === 'notes') {
                  return <th key={'h' + k} className="ws-ai-head"><Icon name="pencil" className="ws-ai-head-ico ws-note-head-ico" size={13} />{c.name}</th>;
                }
                return <th key={'h' + k} className="ws-ai-head ws-ai-head-edit" title="Edit AI column" onClick={() => editAiColumn(it)}><Icon name="sparkles" className="ws-ai-head-ico" size={13} />{c.name}</th>;
              })}
              <th className="ws-of-head"></th>
            </tr>
          </thead>
          <tbody>
            {rows.map((r, i) => {
              if (!matches(r)) return null;
              const checked = selected.has(i);
              return (
                <tr key={i} className={checked ? 'selected' : undefined} onClick={(e) => {if (e.target.closest('.ws-cb-cell')) return;openRecord(i);}}>
                  <td className="ws-cb-cell">
                    <label className="cb-wrap">
                      <input type="checkbox" className="row-check" checked={checked} onChange={() => toggleRow(i)} />
                      <span className={cx('cb-box', checked && 'checked')}>{checked ? <Icon name="check" size={12} /> : null}</span>
                    </label>
                  </td>
                  {isAccounts ?
                  <React.Fragment>
                      <td>
                        <span className="ws-grid-name">
                          <span className="ws-row-ico ws-ent-accounts"><Icon name={WS_ACCT_ICON[r.type] || 'building-2'} size={14} /></span>
                          <span className="nm">{r.name}</span>
                        </span>
                      </td>
                      <td>{r.state}</td>
                      <td className="ws-num">{r.population}</td>
                      <td>{r.type}</td>
                      <td><span className="ws-link">{r.website}</span></td>
                    </React.Fragment> :

                  <React.Fragment>
                      <td className="ws-col-fit">
                        <span className="ws-grid-name">
                          <span className="ws-row-ico ws-ent-contacts"><Icon name="user" size={14} /></span>
                          <span className="nm">{r.firstName}</span>
                        </span>
                      </td>
                      <td className="ws-col-fit">{r.lastName}</td>
                      <td>{r.title}</td>
                      <td>{r.department}</td>
                      <td><span className="ws-link">{r.email}</span></td>
                      <td className="ws-col-fit">{r.phone}</td>
                      <td>{r.confidence}</td>
                      <td>{r.account}</td>
                    </React.Fragment>
                  }
                  {aiCellsFor(i)}
                  <td></td>
                </tr>);

            })}
          </tbody>
        </table>
      </div>
    </div>);

}

/* ---- record drill-in --------------------------------------------------------- */
function WorksheetRecordDetail({ sheet }) {
  useAppState();
  const drawerRef = React.useRef(null);
  const isAccounts = sheet.type === 'accounts';
  const ids = isAccounts ? WS_ACCOUNT_IDS : WS_CONTACT_IDS;
  let idx = state.worksheetRecord.rowIndex;
  if (!(idx >= 0 && idx < ids.length)) idx = 0;
  const a = ACCOUNTS.find((x) => x.accountId === ids[idx]);

  const entity = isAccounts ? 'accounts' : 'contacts';
  const c = a ? (a.contacts || [])[0] || {} : {};
  const record = a ? isAccounts ? a : { ...c, account: a } : null;

  // Fill the Worksheet-tab drawer imperatively (JSON-drawer renderer).
  React.useEffect(() => {
    const el = drawerRef.current;
    if (!el || !record || typeof jdRenderInto !== 'function') return;
    const colObj = wsDedupeColumns(entity, record, isAccounts ?
    wsAccountDetailObject(a, sheet.aiCols) :
    wsContactDetailObject(a, sheet.aiCols));
    el.innerHTML = '';
    jdRenderInto(el, colObj);
    (typeof wsGetAddedColumns === 'function' ? wsGetAddedColumns(sheet.id) : []).forEach((col) => {
      el.appendChild(wsAddedColumnCard(col, col.values[a.accountId], a.accountId));
    });
    el.querySelectorAll(':scope > .jd-card > .jd-card-header > .jd-card-header-title').forEach((t) => {
      if (t.querySelector('.wsd-ai-spark')) return;
      const isNote = t.closest('.jd-card') && t.closest('.jd-card').dataset.noteCard === '1';
      const ico = document.createElement('i');
      ico.setAttribute('data-lucide', isNote ? 'pencil' : 'sparkles');
      ico.className = 'wsd-ai-spark';
      t.prepend(ico);
    });
    if (window.lucide) lucide.createIcons();
  });

  // Keyboard ↑/↓.
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return;
      if (e.metaKey || e.ctrlKey || e.altKey) return;
      const ae = document.activeElement;
      if (ae && ae !== document.body) {
        const t = ae.tagName;
        if (t === 'INPUT' || t === 'TEXTAREA' || t === 'SELECT' || ae.isContentEditable) return;
      }
      e.preventDefault();
      const cur = state.worksheetRecord.rowIndex;
      let n = cur + (e.key === 'ArrowDown' ? 1 : -1);
      if (n < 0) n = 0;
      if (n >= ids.length) n = ids.length - 1;
      if (n === cur) return;
      state.worksheetRecord.rowIndex = n;
      notify();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [ids.length]);

  if (!a || !record) return null;

  const navRows = isAccounts ? wsAccountRecords() : wsContactRecords();
  const worksheetTab = {
    id: 'worksheet',
    label: 'Worksheet',
    render: () => <div className="wsd-drawer" ref={drawerRef}></div>
  };

  return (
    <div className="body">
      <div className="floating-widget-spacer">
        <div className="floating-widget">
          <div className="records-nav" id="records-nav">
            <button className="rn-back" type="button" onClick={() => {state.worksheetRecord = null;notify();}}>
              <Icon name="arrow-left" size={14} />
              <span className="rn-back-label">Back to {sheet.name}</span>
            </button>
            <div className="rn-head">
              <span className="rn-head-title">{isAccounts ? 'Accounts' : 'Contacts'}</span>
              <span className="rn-head-count">{navRows.length} {navRows.length === 1 ? 'record' : 'records'}</span>
            </div>
            <div className="rn-sel-row">
              {state.worksheetSelected.size > 0 ?
              <span className="rn-sel-badge"><Icon name="square-check" size={11} />{state.worksheetSelected.size} selected</span> :
              null}
            </div>
            <div className="rn-list">
              {navRows.map((r, i) => {
                const checked = state.worksheetSelected.has(i);
                return (
                  <button key={i} className={cx('rn-item', i === idx && 'active')} data-wsd-key={i} type="button"
                  onClick={(e) => {
                    if (e.target.closest('.rn-item-check')) return;
                    state.worksheetRecord = { sheetId: sheet.id, rowIndex: i };
                    notify();
                  }}>
                    <span className={cx('rn-item-check', checked && 'checked')}
                    onClick={(e) => {
                      e.stopPropagation();
                      if (checked) state.worksheetSelected.delete(i);else state.worksheetSelected.add(i);
                      notify();
                    }}>{checked ? <Icon name="check" size={12} /> : null}</span>
                    <span className="rn-item-body">
                      <span className="rn-item-name">{r.name}</span>
                      <span className="rn-item-meta">{isAccounts ? r.type : `${r.title} · ${r.account}`}</span>
                    </span>
                  </button>);

              })}
            </div>
          </div>
        </div>
      </div>
      <div className="content-panel">
        <div id="work-area">
          <div data-role="detail">
            <DetailBody
              entity={entity}
              record={record}
              extraSections={[worksheetTab]}
              activeSectionId={state.worksheetDetailSection}
              onSelectSection={(id) => {state.worksheetDetailSection = id;notify();}} />
            
          </div>
        </div>
      </div>
    </div>);

}

/* ---- page dispatcher ----------------------------------------------------------- */
function WorksheetsPage() {
  useAppState();
  const sheet = state.worksheetId ? wsSheetById(state.worksheetId) : null;
  React.useEffect(() => {if (sheet) wsMarkViewed(sheet.id);}, [sheet ? sheet.id : null]);

  if (sheet && state.worksheetRecord && state.worksheetRecord.sheetId === sheet.id) {
    return <WorksheetRecordDetail sheet={sheet} />;
  }
  return (
    <div className="body">
      {!sheet ? <LandingParallelo /> : null}
      <div className="content-panel">
        <div id="work-area">
          <div data-role="agent">
            {sheet ? <WorksheetSheet sheet={sheet} key={sheet.id} /> : <WorksheetsLibrary />}
          </div>
        </div>
      </div>
    </div>);

}

/* ---- sidebar tree ----------------------------------------------------------------- */
function NavWorksheetsChildren({ inFlyout }) {
  useAppState();
  // Inline (expanded sidebar): only while on the Worksheets page — Mk7
  // parity. In the collapsed-rail flyout it's the only way to reach a
  // worksheet, so always render the tree (recents when off-page).
  if (state.page !== 'worksheets' && !inFlyout) return null;
  const current = state.worksheetId ? wsSheetById(state.worksheetId) : null;
  const currentWbId = current ? current.wb : null;
  const go = (id) => {
    state.worksheetRecord = null;
    state.worksheetId = id;
    if (state.page !== 'worksheets') switchPage('worksheets');else
    notify();
  };
  const SheetRow = ({ s }) =>
  <button
    className={cx('nav-child-item', 'nav-child-link', s.id === state.worksheetId && 'active')}
    type="button" onClick={() => go(s.id)}>
    
      <Icon name={WS_ENTITY_ICON[s.type] || 'table-2'} size={14} />
      <span className="nm">{s.name}</span>
    </button>;

  const recents = wsRecentViewed().
  filter((id) => id !== state.worksheetId).
  map(wsSheetById).
  filter((s) => s && (!currentWbId || s.wb !== currentWbId)).
  slice(0, 4);
  return (
    <div className="nav-children">
      {current ?
      currentWbId ?
      <React.Fragment>
            <div className="nav-workbook" role="button" tabIndex={0}
        onClick={() => {const first = wsSheetsInWorkbook(currentWbId)[0];if (first) go(first.id);}}>
              <Icon name="book" className="wb-folder" size={15} />
              <span className="nm">{(wsWorkbookById(currentWbId) || {}).name || 'Workbook'}</span>
            </div>
            <div className="nav-workbook-children">
              {wsSheetsInWorkbook(currentWbId).map((s) => <SheetRow s={s} key={s.id} />)}
            </div>
          </React.Fragment> :
      <SheetRow s={current} /> :
      null}
      {recents.length ?
      <React.Fragment>
          <div className="nav-child-label">Recent</div>
          {recents.map((s) => <SheetRow s={s} key={s.id} />)}
        </React.Fragment> :
      null}
    </div>);

}

/* ---- breadcrumbs ------------------------------------------------------------------- */
function WorksheetsBreadcrumbs() {
  useAppState();
  const sheet = state.worksheetId ? wsSheetById(state.worksheetId) : null;
  const inRecord = sheet && state.worksheetRecord && state.worksheetRecord.sheetId === sheet.id;
  let recordName = null;
  if (inRecord) {
    const isAccounts = sheet.type === 'accounts';
    const ids = isAccounts ? WS_ACCOUNT_IDS : WS_CONTACT_IDS;
    const a = ACCOUNTS.find((x) => x.accountId === ids[state.worksheetRecord.rowIndex]);
    recordName = a ? isAccounts ? a.name : ((a.contacts || [])[0] || {}).name || '—' : '—';
  }
  return (
    <div className="breadcrumbs">
      <img src={(window.__resources&&window.__resources.logoColor)||"react/assets/logo-color.svg"} alt="Pursuit" width="14" height="17" />
      <Icon name="chevron-right" className="breadcrumb-sep" size={14} />
      {sheet ?
      <React.Fragment>
          <button className="breadcrumb-link" type="button"
        onClick={() => {state.worksheetId = null;state.worksheetRecord = null;notify();}}>Worksheets</button>
          <Icon name="chevron-right" className="breadcrumb-sep" size={14} />
          {inRecord ?
        <React.Fragment>
              <button className="breadcrumb-link" type="button" onClick={() => {state.worksheetRecord = null;notify();}}>{sheet.name}</button>
              <Icon name="chevron-right" className="breadcrumb-sep" size={14} />
              <span className="breadcrumb-item current">{recordName}</span>
            </React.Fragment> :

        <span className="breadcrumb-item current">{sheet.name}</span>
        }
        </React.Fragment> :

      <span className="breadcrumb-item current">Worksheets</span>
      }
    </div>);

}

/* ---- header actions (Ask AI + Save split) ------------------------------------------ */
function HeaderTplActions() {
  useAppState();
  const [menuOpen, setMenuOpen] = React.useState(false);
  const splitRef = React.useRef(null);
  React.useEffect(() => {
    if (!menuOpen) return;
    const onDown = (e) => { if (splitRef.current && splitRef.current.contains(e.target)) return; setMenuOpen(false); };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [menuOpen]);

  if (state.page !== 'worksheets') return null;
  const sheet = state.worksheetId ? wsSheetById(state.worksheetId) : null;
  if (!sheet) return null;
  const inRecord = state.worksheetRecord && state.worksheetRecord.sheetId === sheet.id;
  const n = inRecord ? state.worksheetSelected.size : 0;
  const entity = sheet.type;
  const count = inRecord ? (n || 1) : 24;

  const doAction = (action) => {
    setMenuOpen(false);
    if (action === 'worksheet' && typeof openSaveToWorksheetModal === 'function') {
      openSaveToWorksheetModal({ count, entity });
    } else if ((action === 'crm-salesforce' || action === 'crm-hubspot') && typeof openExportModal === 'function') {
      // Only this sheet's actual columns are exportable.
      const provider = action === 'crm-hubspot' ? 'hubspot' : 'salesforce';
      const s = typeof wsCrmSampleFor === 'function' ? wsCrmSampleFor(sheet) : {};
      openExportModal('crm', { count, entity, provider, sample: s.sample, record: s.record, recordName: s.recordName });
    } else if (action === 'csv' && typeof openExportModal === 'function') {
      // Same source as CRM: AI columns reflect exactly what's on this sheet.
      const s = typeof wsCrmSampleFor === 'function' ? wsCrmSampleFor(sheet) : {};
      openExportModal('csv', { count, entity, sample: s.sample, record: s.record, recordName: s.recordName });
    }
  };

  const menuItems = [
    ['crm-salesforce', 'brand-salesforce', 'Save to Salesforce'],
    ['crm-hubspot', 'brand-hubspot', 'Save to HubSpot'],
    ['csv', 'file-down', 'Save to CSV'],
  ];

  return (
    <div className="header-actions-slot" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <button className="btn-secondary-cta ws-ask-ai" type="button"
      onClick={() => showToast({ message: 'Ask AI — coming soon', icon: 'sparkles' })}>
        <span className="icon-frame"><Icon name="sparkles" size={16} /></span>
        Ask AI
      </button>
      <div className="card-split-btn card-split-btn--primary" ref={splitRef}>
        <button className="card-split-main" onClick={() => doAction('worksheet')}>
          <span className="icon-frame"><Icon name="arrow-down-to-line" size={16} /></span>
          {n > 0 ? `Save to Worksheet (${n})` : 'Save to Worksheet'}
        </button>
        <div className="card-split-divider"></div>
        <button className="card-split-trigger" aria-label="More save options"
          onClick={(e) => { e.preventDefault(); e.stopPropagation(); setMenuOpen(o => !o); }}>
          <Icon name="chevron-down" size={16} />
        </button>
        {menuOpen ? (
          <div className="btn-split-menu">
            {menuItems.map(([k, icon, label]) => (
              <button className="btn-split-item" key={k} onClick={() => doAction(k)}>
                <Icon name={icon} size={14} /> {label}
              </button>
            ))}
          </div>
        ) : null}
      </div>
    </div>);

}

window.PAGES.worksheets = WorksheetsPage;
window.PAGE_BREADCRUMBS = window.PAGE_BREADCRUMBS || {};
window.PAGE_BREADCRUMBS.worksheets = WorksheetsBreadcrumbs;
Object.assign(window, {
  WorksheetsPage, WorksheetsLibrary, WorksheetSheet, WorksheetRecordDetail,
  NavWorksheetsChildren, WorksheetsBreadcrumbs, HeaderTplActions
});