/** @jsx React.createElement */
/* OpportunityDrawer — slide-in editor for one opportunity. Assessment stage
   and weekly status lead (Ipsen's primary edits), then the full record.
   Every change lands in shared state. */

function DrawerSection({ title, children }) {
  return (
    <div className="apo-sec">
      <div className="apo-lab" style={{ marginBottom: 9 }}>{title}</div>
      {children}
    </div>
  );
}

// Searchable single-select with free-add: type to filter, click/Enter to pick,
// or add whatever you typed when it isn't in the list.
function ComboBox({ value, options, placeholder, onChange, inputClass = 'apo-in' }) {
  const [open, setOpen] = React.useState(false);
  const [q, setQ] = React.useState('');
  const ref = React.useRef(null);
  React.useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);
  const nq = q.trim().toLowerCase();
  const filtered = options.filter(o => !nq || o.toLowerCase().includes(nq));
  const exact = options.some(o => o.toLowerCase() === nq);
  const commit = (v) => { onChange(v); setQ(''); setOpen(false); };
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <input className={inputClass} value={open ? q : (value || '')} placeholder={placeholder}
        onFocus={() => { setQ(''); setOpen(true); }}
        onChange={(e) => { setQ(e.target.value); setOpen(true); }}
        onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); const v = q.trim(); if (v) commit(v); else setOpen(false); } else if (e.key === 'Escape') { setOpen(false); } }} />
      {open && (
        <div className="apo-combo-pop">
          {filtered.map(o => (
            <div key={o} className="apo-combo-opt" data-sel={String(o === value)} title={o} onMouseDown={(e) => { e.preventDefault(); commit(o); }}>{o}</div>
          ))}
          {nq && !exact && (
            <div className="apo-combo-opt add" onMouseDown={(e) => { e.preventDefault(); commit(q.trim()); }}>{'+ Add \u201c' + q.trim() + '\u201d'}</div>
          )}
          {!filtered.length && !nq && <div className="apo-combo-empty">{'Type to search or add\u2026'}</div>}
        </div>
      )}
    </div>
  );
}

function OpportunityDrawer({ project: p, api, notify, onClose, mode = 'edit', onAdd, onDiscard, catalog }) {
  const originalRef = React.useRef(p);
  const canAdd = (p.company || '').trim().length > 0;
  const pairs = [...(typeof APO_XLSX_ASSETS !== 'undefined' ? APO_XLSX_ASSETS : []), ...((catalog || []).map(x => ({ company: x.company, asset: x.asset })))];
  const companyOptions = [...new Set(pairs.map(x => x.company).filter(Boolean))].sort((a, b) => a.localeCompare(b));
  const assetsAll = [...new Set(pairs.map(x => x.asset).filter(Boolean))].sort((a, b) => a.localeCompare(b));
  const byCompany = {}; pairs.forEach(x => { if (!x.company || !x.asset) return; (byCompany[x.company] = byCompany[x.company] || new Set()).add(x.asset); });
  const assetOptions = (p.company && byCompany[p.company]) ? [...byCompany[p.company]].sort((a, b) => a.localeCompare(b)) : assetsAll;
  React.useEffect(() => {
    const f = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', f);
    return () => document.removeEventListener('keydown', f);
  }, [onClose]);
  const setStage = (key) => { const msg = apoDescribeMove(p, { stage: key }); if (!msg) return; api.move(p.id, { stage: key }); notify(msg); };
  const setTa = (key) => { const msg = apoDescribeMove(p, { ta: key }); if (!msg) return; api.move(p.id, { ta: key }); notify(msg); };
  const dealList = APO_DEALS.includes(p.deal) ? APO_DEALS : [p.deal, ...APO_DEALS];
  return (
    <React.Fragment>
      <div className="apo-scrim" onClick={onClose}></div>
      <aside className="apo-drawer" role="dialog" aria-label="Opportunity details">
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 18px 0', flexShrink: 0 }}>
          <span className="apo-lab" style={{ margin: 0, flex: 1 }}>{mode === 'new' ? 'New opportunity' : 'Opportunity details'}</span>
          <button className="icon-btn" style={{ width: 28, height: 28 }} onClick={onClose} title="Close" aria-label="Close">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
          </button>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', paddingBottom: 8 }}>
          <div style={{ padding: '8px 18px 14px' }}>
            <ComboBox inputClass="apo-title-in" value={p.company} placeholder="Company" options={companyOptions} onChange={(v) => api.update(p.id, { company: v })} />
            <ComboBox inputClass="apo-title-in sub" value={p.asset} placeholder="Asset" options={assetOptions} onChange={(v) => api.update(p.id, { asset: v })} />
            <div style={{ display: 'flex', gap: 6, marginTop: 10, flexWrap: 'wrap' }}>
              {APO_TAS.map(t => {
                const on = p.ta === t.key;
                return (
                  <button key={t.key} className="apo-phasebtn"
                    style={on ? { borderColor: t.accent, color: t.accent, boxShadow: `inset 0 0 0 1px ${t.accent}` } : {}}
                    onClick={() => setTa(t.key)}>
                    <span style={{ width: 8, height: 8, borderRadius: '50%', background: t.accent, flexShrink: 0 }}></span>
                    {t.name}
                  </button>
                );
              })}
            </div>
          </div>
          <DrawerSection title="Assessment stage">
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
              {APO_STAGES.map(st => {
                const on = p.stage === st.key;
                return (
                  <button key={st.key} className="apo-stagebtn" onClick={() => setStage(st.key)}
                    style={on ? { background: st.head, borderColor: st.head, color: st.headText } : {}}>
                    <span style={{ fontSize: 12.5, fontWeight: 700 }}>{st.label}</span>
                    <span style={{ fontSize: 10.5, opacity: .75, fontWeight: 500 }}>{st.sub}</span>
                  </button>
                );
              })}
            </div>
          </DrawerSection>
          <DrawerSection title="Development phase">
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
              {APO_PHASE_ORDER.map(k => {
                const ph = APO_PHASES[k];
                const on = p.phase === k;
                return (
                  <button key={k} className="apo-phasebtn"
                    style={on ? { background: ph.fill, borderColor: ph.border, color: ph.text, boxShadow: `inset 0 0 0 1px ${ph.border}` } : {}}
                    onClick={() => { if (!on) { api.update(p.id, { phase: k }); notify(`${p.company} \u2013 ${p.asset}: phase \u2192 ${ph.label}`); } }}>
                    <span style={{ width: 10, height: 10, borderRadius: 3, background: on ? 'rgba(255,255,255,.4)' : ph.fill, border: `1px solid ${ph.border}`, flexShrink: 0 }}></span>
                    {ph.label}
                  </button>
                );
              })}
            </div>
          </DrawerSection>
          <DrawerSection title="Status this week">
            <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'}`);
            }} />
          </DrawerSection>
          <DrawerSection title="Details">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              <label><span className="apo-lab">Indication</span><input className="apo-in" value={p.ind} placeholder="e.g. NSCLC (HER3)" onChange={(e) => api.update(p.id, { ind: e.target.value })} /></label>
              <label><span className="apo-lab">Modality</span><input className="apo-in" value={p.mod} placeholder="e.g. ADC, small molecule" onChange={(e) => api.update(p.id, { mod: e.target.value })} /></label>
              <label><span className="apo-lab">Deal type</span>
                <select className="apo-in" value={p.deal} onChange={(e) => api.update(p.id, { deal: e.target.value })}>
                  {dealList.map(d => <option key={d} value={d}>{d || '\u2014'}</option>)}
                </select>
              </label>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                <label><span className="apo-lab">BD lead</span>
                  <select className="apo-in" value={p.lead || ''} onChange={(e) => api.update(p.id, { lead: e.target.value })}>
                    {((p.lead && !APO_LEADS.includes(p.lead)) ? ['', p.lead, ...APO_LEADS] : ['', ...APO_LEADS]).map(n => <option key={n} value={n}>{n || 'Unassigned'}</option>)}
                  </select>
                </label>
                <label><span className="apo-lab">Updated</span><input className="apo-in" value={p.up} disabled style={{ background: 'var(--ab-slate-50)', color: 'var(--ab-slate-500)' }} /></label>
              </div>
              <label><span className="apo-lab">Next step</span><input className="apo-in" value={p.next} placeholder="e.g. DAM presentation Aug 5" onChange={(e) => api.update(p.id, { next: e.target.value })} /></label>
              <label><span className="apo-lab">Notes</span><textarea className="apo-in" rows={3} value={p.notes} placeholder="Context for the VPs / Board pack" onChange={(e) => api.update(p.id, { notes: e.target.value })} /></label>
            </div>
          </DrawerSection>
        </div>
        <div style={{ borderTop: '1px solid var(--ab-border)', padding: '12px 18px', display: 'flex', flexDirection: 'column', gap: 10, flexShrink: 0, background: '#fff' }}>
          {mode === 'new' ? (
            <React.Fragment>
              <span style={{ fontSize: 12, color: 'var(--ab-slate-500)' }}>{'This opportunity isn\u2019t on the board yet.'}</span>
              <div style={{ display: 'flex', gap: 8 }}>
                <button className="apo-newbtn" disabled={!canAdd} style={{ flex: 1, justifyContent: 'center', height: 34, ...(canAdd ? {} : { opacity: .5, cursor: 'not-allowed' }) }} onClick={onAdd}>Add opportunity</button>
                <button className="apo-ghostbtn" style={{ flex: 1, justifyContent: 'center', height: 34 }} onClick={onDiscard}>Discard opportunity</button>
              </div>
            </React.Fragment>
          ) : (
            <React.Fragment>
              <span style={{ fontSize: 12, color: 'var(--ab-slate-500)' }}>{`Updated ${p.up}`}</span>
              <button className="apo-ghostbtn" style={{ width: '100%', justifyContent: 'center' }} onClick={() => notify('Would deep-link to the CRM record')}>
                Open opportunity record
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M7 17L17 7M9 7h8v8"/></svg>
              </button>
              <div style={{ display: 'flex', gap: 8 }}>
                <button className="apo-newbtn" style={{ flex: 1, justifyContent: 'center', height: 34 }} onClick={onClose}>Update opportunity</button>
                <button className="apo-ghostbtn" style={{ flex: 1, justifyContent: 'center', height: 34 }} onClick={() => { api.replace(p.id, originalRef.current); onClose(); }}>Discard changes</button>
              </div>
            </React.Fragment>
          )}
        </div>
      </aside>
    </React.Fragment>
  );
}

Object.assign(window, { OpportunityDrawer, DrawerSection });
