/** @jsx React.createElement */
/* ActiveProjectsTable — fully editable table view of the Active Projects
   board. Text cells edit inline; TA / stage / phase / deal are selects;
   status opens a multi-toggle popover. Same state as the chart view. */

function Chev() {
  return <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: .5, flexShrink: 0 }}><path d="M6 9l6 6 6-6"/></svg>;
}

function EditCell({ value, placeholder = '\u2014', bold, strike, onCommit }) {
  const [editing, setEditing] = React.useState(false);
  if (editing) return (
    <input className="apot-input" autoFocus defaultValue={value}
      onBlur={(e) => { setEditing(false); const v = e.target.value.trim(); if (v !== value) onCommit(v); }}
      onKeyDown={(e) => {
        if (e.key === 'Enter') e.currentTarget.blur();
        if (e.key === 'Escape') { e.currentTarget.value = value; e.currentTarget.blur(); }
      }} />
  );
  return (
    <div className="apot-edit" data-strike={strike ? '1' : undefined} title="Click to edit"
      style={{ fontWeight: bold ? 600 : 400, color: bold ? 'var(--ab-navy-700)' : undefined }}
      onClick={() => setEditing(true)}>
      {value || <span className="apot-ph">{placeholder}</span>}
    </div>
  );
}

function PillSelect({ value, options, onChange, pill, fill }) {
  return (
    <span className="apo-sel" style={fill ? { width: '100%' } : undefined}>
      {pill}
      <select value={value} onChange={(e) => onChange(e.target.value)} aria-label="Edit value">
        {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
      </select>
    </span>
  );
}

function StagePill({ stage }) {
  const st = APO_STAGES.find(s => s.key === stage);
  return <span className="apo-pill" style={{ background: st.tint, borderColor: st.head, color: st.headText }}>{st.label}<Chev/></span>;
}
function PhasePill({ phase }) {
  const ph = APO_PHASES[phase];
  return <span className="apo-pill"><span style={{ width: 10, height: 10, borderRadius: 3, background: ph.fill, border: `1px solid ${ph.border}`, flexShrink: 0 }}></span>{ph.label}<Chev/></span>;
}
function TAPill({ ta }) {
  const t = APO_TAS.find(x => x.key === ta);
  return <span className="apo-pill"><span style={{ width: 8, height: 8, borderRadius: '50%', background: t.accent, flexShrink: 0 }}></span>{t.name}<Chev/></span>;
}

function StatusCell({ p, api, notify }) {
  const [pos, setPos] = React.useState(null);
  const ref = React.useRef(null);
  const openPop = () => {
    const z = document.documentElement.currentCSSZoom || 1;
    const r = ref.current.getBoundingClientRect();
    const below = r.bottom / z + 360 < window.innerHeight / z;
    setPos({
      left: Math.max(10, Math.min(r.left / z, window.innerWidth / z - 274)),
      top: below ? r.bottom / z + 6 : r.top / z - 6,
      transform: below ? 'none' : 'translateY(-100%)',
    });
  };
  return (
    <React.Fragment>
      <button type="button" className="apot-status" ref={ref} onClick={openPop} title="Edit status">
        {p.flags.length
          ? p.flags.map(f => <FlagGlyph key={f} flag={f} />)
          : <span className="apot-ph" style={{ fontSize: 12 }}>Set status</span>}
        <Chev />
      </button>
      {pos && (
        <React.Fragment>
          <div className="apo-popback" onClick={() => setPos(null)}></div>
          <div className="apo-pop" style={pos}>
            <StatusPicker flags={p.flags} onToggle={(f) => {
              const on = p.flags.includes(f);
              api.toggleFlag(p.id, f);
              notify(`${p.company} \u2013 ${p.asset}: ${APO_STATUS[f]} ${on ? 'removed' : 'set'}`);
            }} />
          </div>
        </React.Fragment>
      )}
    </React.Fragment>
  );
}

function matchesApoFilter(p, f) {
  if (!f) return true;
  if (f.stages && f.stages.length && !f.stages.includes(p.stage)) return false;
  if (f.stage && p.stage !== f.stage) return false;
  if (f.phase && p.phase !== f.phase) return false;
  if (f.ta && p.ta !== f.ta) return false;
  return true;
}

function leadOptionsFor(p) {
  const base = ['', ...APO_LEADS];
  const list = (p.lead && !APO_LEADS.includes(p.lead)) ? ['', p.lead, ...APO_LEADS] : base;
  return list.map(n => ({ value: n, label: n || 'Unassigned' }));
}

function APORow({ p, api, onOpen, notify, highlight }) {
  const terminated = p.flags.includes('terminated');
  const hlDim = highlight ? !(highlight.type === 'phase' ? p.phase === highlight.key : p.flags.includes(highlight.key)) : false;
  const commit = (patch, msg) => { api.update(p.id, patch); notify(msg || `${p.company} \u2013 ${p.asset} updated`); };
  const moveSel = (patch) => { const msg = apoDescribeMove(p, patch); if (!msg) return; api.move(p.id, patch); notify(msg); };
  const dealList = APO_DEALS.includes(p.deal) ? APO_DEALS : [p.deal, ...APO_DEALS];
  return (
    <tr style={{ opacity: hlDim ? .3 : 1, transition: 'opacity 130ms var(--ab-ease)' }}>
      <td style={{ textAlign: 'center', padding: '5px 2px 5px 8px' }}>
        <button className="apot-open" title="Open details" onClick={() => onOpen(p.id)}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M7 17L17 7M9 7h8v8"/></svg>
        </button>
      </td>
      <td><EditCell value={p.company} bold strike={terminated} onCommit={(v) => commit({ company: v })} /></td>
      <td><EditCell value={p.asset} strike={terminated} onCommit={(v) => commit({ asset: v })} /></td>
      <td><PillSelect value={p.ta} options={APO_TAS.map(t => ({ value: t.key, label: t.name }))} onChange={(v) => moveSel({ ta: v })} pill={<TAPill ta={p.ta} />} /></td>
      <td><PillSelect value={p.stage} options={APO_STAGES.map(s => ({ value: s.key, label: s.label }))} onChange={(v) => moveSel({ stage: v })} pill={<StagePill stage={p.stage} />} /></td>
      <td><PillSelect value={p.phase} options={APO_PHASE_ORDER.map(k => ({ value: k, label: APO_PHASES[k].label }))} onChange={(v) => commit({ phase: v }, `${p.company} \u2013 ${p.asset}: phase \u2192 ${APO_PHASES[v].label}`)} pill={<PhasePill phase={p.phase} />} /></td>
      <td><StatusCell p={p} api={api} notify={notify} /></td>
      <td><EditCell value={p.ind} placeholder="Add indication" onCommit={(v) => commit({ ind: v })} /></td>
      <td><PillSelect fill value={p.deal} options={dealList.map(d => ({ value: d, label: d || '\u2014' }))} onChange={(v) => commit({ deal: v }, `${p.company} \u2013 ${p.asset}: deal type updated`)} pill={<span className="apo-pill" style={{ width: '100%' }}><span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.deal || '\u2014'}</span><Chev/></span>} /></td>
      <td><PillSelect fill value={p.lead || ''} options={leadOptionsFor(p)} onChange={(v) => commit({ lead: v }, `${p.company} \u2013 ${p.asset}: BD lead ${v ? '\u2192 ' + v : 'cleared'}`)} pill={<span className="apo-pill" style={{ width: '100%' }}><span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', color: p.lead ? undefined : 'var(--ab-slate-400)' }}>{p.lead || 'Assign'}</span><Chev/></span>} /></td>
      <td><EditCell value={p.next} placeholder="Add next step" onCommit={(v) => commit({ next: v })} /></td>
      <td><span className="apot-up" data-now={p.up === 'Just now' ? '1' : undefined}>{p.up}</span></td>
    </tr>
  );
}

function APOTable({ projects, api, onOpen, onAdd, notify, filter, onSetFilter, onClearFilter, highlight }) {
  const [widths, setWidths] = React.useState([34, 132, 106, 122, 128, 152, 130, 198, 160, 156, 172, 80]);
  const drag = React.useRef(null);
  React.useEffect(() => {
    const move = (e) => { const d = drag.current; if (!d) return; const z = document.documentElement.currentCSSZoom || 1; const dx = (e.clientX - d.startX) / z; setWidths(w => { const n = [...w]; n[d.i] = Math.max(48, d.startW + dx); return n; }); };
    const up = () => { if (drag.current) { drag.current = null; document.body.style.cursor = ''; document.body.style.userSelect = ''; } };
    window.addEventListener('mousemove', move); window.addEventListener('mouseup', up);
    return () => { window.removeEventListener('mousemove', move); window.removeEventListener('mouseup', up); };
  }, []);
  const startResize = (i, e) => { e.preventDefault(); e.stopPropagation(); drag.current = { i, startX: e.clientX, startW: widths[i] }; document.body.style.cursor = 'col-resize'; document.body.style.userSelect = 'none'; };
  const heads = ['', 'Company', 'Asset', 'TA', 'Stage', 'Phase', 'Status', 'Indication', 'Deal type', 'BD lead', 'Next step', 'Updated'];
  const visible = projects.filter(p => matchesApoFilter(p, filter));
  const stageActive = filter && filter.stage && !filter.phase && !filter.ta;
  const ta = filter && filter.ta ? APO_TAS.find(t => t.key === filter.ta) : null;
  const ph = filter && filter.phase ? APO_PHASES[filter.phase] : null;
  const extraLabel = (ph || (ta && !filter.stage)) ? [ta ? ta.name : null, ph ? ph.label : null].filter(Boolean).join(' \u00b7 ') : null;
  const fpill = (active, extra) => ({ display: 'inline-flex', alignItems: 'center', padding: '3px 10px', borderRadius: 999, fontSize: 12, fontWeight: 600, border: '1px solid', cursor: 'pointer', fontFamily: 'inherit', ...extra });
  const toggleStage = (key) => {
    const base = filter || {};
    const cur = base.stages ? base.stages : (base.stage ? [base.stage] : []);
    const next = cur.includes(key) ? cur.filter(k => k !== key) : [...cur, key];
    const rest = { ...base }; delete rest.stage; delete rest.stages;
    const merged = { ...rest, ...(next.length ? { stages: next } : {}) };
    onSetFilter(Object.keys(merged).length ? merged : null);
  };
  return (
    <div>
      <div data-tour="tabs" style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 7, margin: '2px 0 12px' }}>
        <button type="button" onClick={() => onClearFilter()}
          style={fpill(!filter, !filter ? { background: 'var(--ab-navy-700)', borderColor: 'var(--ab-navy-700)', color: '#fff' } : { background: '#fff', borderColor: 'var(--ab-border)', color: 'var(--ab-slate-700)' })}>
          All&nbsp;<b>{projects.length}</b>
        </button>
        {APO_STAGES.map(st => {
          const active = !!(filter && ((filter.stages && filter.stages.includes(st.key)) || filter.stage === st.key));
          return (
            <button key={st.key} type="button" onClick={() => toggleStage(st.key)}
              style={fpill(active, { background: st.tint, borderColor: active ? st.headText : st.head, color: st.headText, boxShadow: active ? `inset 0 0 0 1.5px ${st.headText}` : 'none' })}>
              {st.label}&nbsp;<b>{apoStageCount(projects, st.key) || '\u2013'}</b>
            </button>
          );
        })}
        {extraLabel && (
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 6px 3px 11px', borderRadius: 999, fontSize: 12, fontWeight: 600, border: '1px solid var(--ab-blue-200)', background: 'var(--ab-blue-50)', color: 'var(--ab-navy-700)' }}>
            {extraLabel}
            <button type="button" onClick={() => onClearFilter()} title="Clear filter" aria-label="Clear filter"
              style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 16, height: 16, borderRadius: '50%', border: 'none', background: 'rgba(11,45,94,.1)', color: 'var(--ab-navy-700)', cursor: 'pointer', padding: 0 }}>
              <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
            </button>
          </span>
        )}
      </div>
      <div className="apo-scroll">
        <table className="apot" style={{ width: '100%', minWidth: widths.reduce((a, b) => a + b, 0) }}>
          <colgroup>{widths.map((w, i) => <col key={i} style={{ width: w }} />)}</colgroup>
          <thead><tr>{heads.map((h, i) => (
            <th key={i} style={{ position: 'relative' }}>{h}
              {i < heads.length - 1 && <span className="apot-resize" onMouseDown={(e) => startResize(i, e)} title="Drag to resize" />}
            </th>
          ))}</tr></thead>
          <tbody>
            {visible.length === 0 && (
              <tr><td colSpan={12} style={{ padding: '30px 12px', textAlign: 'center', color: 'var(--ab-slate-400)', fontSize: 13 }}>
                No active opportunities{extraLabel ? ` in ${extraLabel}` : stageActive ? ` in ${APO_STAGES.find(s => s.key === filter.stage).label}` : ''} yet.
              </td></tr>
            )}
            {APO_TAS.map(ta => {
              const rows = visible.filter(p => p.ta === ta.key);
              if (!rows.length) return null;
              return (
                <React.Fragment key={ta.key}>
                  <tr className="apot-group"><td colSpan={12}>
                    <span style={{ display: 'inline-block', width: 4, height: 12, borderRadius: 2, background: ta.accent, marginRight: 8, verticalAlign: -1 }}></span>
                    {ta.name}
                    <span style={{ marginLeft: 8, color: 'var(--ab-slate-400)', fontWeight: 600 }}>{rows.length}</span>
                  </td></tr>
                  {rows.map(p => <APORow key={p.id} p={p} api={api} onOpen={onOpen} notify={notify} highlight={highlight} />)}
                </React.Fragment>
              );
            })}
            <tr className="apot-addrow"><td colSpan={12}>
              <button className="apo-ghostbtn" onClick={onAdd}>
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M12 5v14M5 12h14"/></svg>
                Add opportunity
              </button>
            </td></tr>
          </tbody>
        </table>
      </div>
    </div>
  );
}

Object.assign(window, { APOTable, EditCell, PillSelect, StatusCell });
