// Detail slideout — full deal view with inline edit
function DealDetail({ deal, stages, reps, showrooms, onClose, onEdit, isLeadership }) {
  const [edits, setEdits] = React.useState({});
  const [reassignOpen, setReassignOpen] = React.useState(false);
  const [logFormOpen, setLogFormOpen] = React.useState(false);
  const [logType, setLogType] = React.useState('call');
  const [logText, setLogText] = React.useState('');

  if (!deal) return null;
  const d = { ...deal, ...edits };
  const stageIdx = stages.findIndex(s => s.id === d.stage);
  const isClosed = d.stage === 'sold' || d.stage === 'lost';

  const update = (field, value) => {
    setEdits(prev => ({ ...prev, [field]: value }));
    // Log significant field changes as activities
    const significant = {
      customer: 'Customer name',
      phone: 'Phone',
      email: 'Email',
      product: 'Job type',
      stage: 'Stage',
      value: 'Value',
      customerBudget: 'Customer budget',
      jobType: 'Install/DIY',
      stoneSupply: 'Stone supply',
      designApptDate: 'Design appt date',
      quotePresentationDate: 'Quote presentation date',
      forecastDepositMonth: 'Forecast deposit',
      onsiteVisitDone: 'Onsite visit',
      showroom: 'Showroom',
    };
    let patch = { [field]: value };
    if (significant[field]) {
      const oldVal = d[field];
      const fmtVal = (v) => v == null || v === '' ? '—' : v === true ? 'Yes' : v === false ? 'No' : v.toString().slice(0, 60);
      const activity = {
        id: 'a' + Math.floor(Math.random() * 1e9),
        type: 'note',
        label: `${significant[field]} changed: ${fmtVal(oldVal)} → ${fmtVal(value)}`,
        date: new Date().toISOString().slice(0, 10),
        daysAgo: 0,
      };
      patch.activities = [activity, ...(d.activities || [])];
    }
    onEdit(d.id, patch);
  };

  return (
    <div>
      <div className="detail-overlay" onClick={onClose}/>
      <div className="detail-panel">
        <div className="detail-hd">
          <div className="detail-row1">
            <span className="detail-id mono">{d.quoteNumber || d.id}</span>
            <span style={{ color: 'var(--ink-3)', fontSize: 11 }}>·</span>
            <span style={{ color: 'var(--ink-3)', fontSize: 11 }}>Created {fmt.shortDate(d.created)} · {fmt.daysAgo(d.createdDaysAgo)}</span>
            <button className="detail-close" onClick={onClose}>
              <Icon name="close" size={16}/>
            </button>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <Avatar name={d.customer} sz="lg"/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <input
                className="detail-customer"
                defaultValue={d.customer}
                onBlur={(e) => { if (e.target.value.trim() && e.target.value !== d.customer) update('customer', e.target.value.trim()); }}
                style={{ background: 'transparent', border: 'none', padding: 0, fontSize: 22, fontWeight: 600, letterSpacing: '-0.025em', width: '100%', outline: 'none' }}
              />
              <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>{d.product || 'Quote'}{d.quoteNumber ? ` · Quote #${d.quoteNumber}` : ''}</div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 6, marginTop: 4 }}>
            {d.phone && <a className="btn sm primary" href={`tel:${d.phone.replace(/\s+/g, '')}`}><Icon name="phone" size={12}/> Call</a>}
            <a className="btn sm" href={`sms:${(d.phone || '').replace(/\s+/g, '')}`}><Icon name="mail" size={12}/> SMS</a>
            <button className="btn sm" onClick={() => {
              const node = document.getElementById('deal-notes-' + d.id);
              if (node) { node.scrollIntoView({ behavior: 'smooth', block: 'center' }); node.focus(); }
            }}><Icon name="calendar" size={12}/> Schedule next</button>
            {isLeadership && <button className="btn sm" style={{ marginLeft: 'auto' }} onClick={() => setReassignOpen(true)} title="Reassign deal"><Icon name="users" size={13}/></button>}
          </div>
        </div>

        <div className="detail-body">
          {/* Where this deal currently sits */}
          <div className="detail-section">
            <h4>Where this deal currently sits</h4>
            {(() => {
              const flow = stages.filter(s => s.id !== 'lost');
              const curIdx = flow.findIndex(s => s.id === d.stage);
              const lost = d.stage === 'lost';
              return (
                <div className="journey" style={{ marginBottom: 12 }}>
                  {flow.map((s, i) => {
                    const achieved = !lost && (i < curIdx || d.stage === 'sold' && i <= curIdx);
                    const current = !lost && s.id === d.stage;
                    return (
                      <React.Fragment key={s.id}>
                        <div className={`j-step ${achieved ? 'achieved' : ''} ${current ? 'current' : ''}`}>
                          <div className="j-dot">{achieved ? <Icon name="check" size={10} color="white"/> : <span className="j-dot-inner"></span>}</div>
                          <div className="j-label">{s.label}</div>
                        </div>
                        {i < flow.length - 1 && <div className={`j-line ${(!lost && i < curIdx) ? 'achieved' : ''}`}></div>}
                      </React.Fragment>
                    );
                  })}
                </div>
              );
            })()}
            <div style={{ background: d.stage === 'lost' ? 'var(--lost-soft)' : 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 'var(--r-md)', padding: '10px 13px', marginBottom: 10 }}>
              <div style={{ fontSize: 10.5, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--ink-3)' }}>Current position</div>
              <div style={{ fontSize: 14, fontWeight: 600, marginTop: 2 }}>{(stages.find(s => s.id === d.stage) || {}).label || d.stage}</div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2, display: 'flex', alignItems: 'center', gap: 5 }}>
                <Icon name="clock" size={11}/> <span className="num">{d.stageEnteredDaysAgo}d</span> in this stage
              </div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>Move stage:</span>
              <select className="sel" value={d.stage} onChange={(e) => update('stage', e.target.value)} style={{ fontWeight: 500, flex: 1 }}>
                {stages.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
              </select>
            </div>
            {d.stage === 'lost' && d.lossReason && (
              <div style={{ marginTop: 10, padding: '10px 12px', borderRadius: 8, background: 'var(--lost-soft)', border: '1px solid color-mix(in oklch, var(--lost) 25%, transparent)' }}>
                <div style={{ fontSize: 10.5, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'oklch(0.45 0.16 25)' }}>Reason lost</div>
                <div style={{ fontSize: 13, fontWeight: 500, marginTop: 2 }}>{d.lossReason}</div>
                {d.lossNote && <div style={{ fontSize: 12, color: 'var(--ink-2)', marginTop: 3, fontStyle: 'italic' }}>“{d.lossNote}”</div>}
              </div>
            )}
          </div>

          {/* Key fields */}
          <div className="detail-section">
            <h4>Deal details</h4>
            <div className="detail-grid">
              <div className="detail-field">
                <span className="lbl">Value</span>
                <input
                  type="number"
                  defaultValue={d.value}
                  onBlur={(e) => update('value', parseInt(e.target.value, 10) || 0)}
                  className="num"
                />
              </div>
              <div className="detail-field">
                <span className="lbl">Expected close</span>
                <input type="date" defaultValue={d.expectedClose} onBlur={(e) => update('expectedClose', e.target.value)}/>
              </div>
              <div className="detail-field">
                <span className="lbl">
                  Assigned rep
                  {!isLeadership && <Icon name="alert" size={10} style={{ marginLeft: 4, color: 'var(--ink-3)', verticalAlign: 'middle' }}/>}
                </span>
                {isLeadership ? (
                  <button
                    onClick={() => setReassignOpen(true)}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 8,
                      padding: '6px 10px',
                      border: '1px solid var(--border)',
                      borderRadius: 4,
                      background: 'var(--surface)',
                      cursor: 'pointer',
                      width: '100%',
                      textAlign: 'left',
                      fontSize: 13,
                    }}
                  >
                    <span className="avatar sm">{d.repName.split(' ').map(s => s[0]).slice(0, 2).join('')}</span>
                    <span style={{ flex: 1 }}>{d.repName}</span>
                    <Icon name="edit" size={11} color="var(--ink-3)"/>
                  </button>
                ) : (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 0', fontSize: 13, color: 'var(--ink-2)' }}>
                    <span className="avatar sm">{d.repName.split(' ').map(s => s[0]).slice(0, 2).join('')}</span>
                    {d.repName}
                  </div>
                )}
              </div>
              <div className="detail-field">
                <span className="lbl">Customer budget (AUD)</span>
                <input
                  type="number"
                  defaultValue={d.customerBudget || ''}
                  placeholder="e.g. 25000"
                  className="num"
                  onBlur={(e) => update('customerBudget', parseFloat(e.target.value) || 0)}
                />
              </div>
              <div className="detail-field" style={{ gridColumn: '1 / -1' }}>
                <span className="lbl">Job type</span>
                <div style={{ display: 'flex', gap: 4 }}>
                  {[
                    { id: 'install', label: 'Install' },
                    { id: 'diy', label: 'DIY / Supply only' },
                    { id: 'hybrid', label: 'Hybrid' },
                  ].map(opt => {
                    const on = d.jobType === opt.id || (!d.jobType && d.install && opt.id === 'install');
                    return (
                      <button key={opt.id} onClick={() => update('jobType', opt.id)}
                        style={{ flex: 1, padding: '6px 8px', fontSize: 12, border: '1px solid var(--border)', borderRadius: 4,
                          background: on ? 'var(--ink)' : 'var(--surface)', color: on ? 'white' : 'var(--ink-2)', cursor: 'pointer' }}>{opt.label}</button>
                    );
                  })}
                </div>
              </div>
              <div className="detail-field" style={{ gridColumn: '1 / -1' }}>
                <span className="lbl">Stone supply</span>
                <div style={{ display: 'flex', gap: 4 }}>
                  {[
                    { id: 'kub', label: 'Supplied by KUB' },
                    { id: 'customer', label: 'Customer arranges direct' },
                    { id: 'na', label: 'Not applicable' },
                  ].map(opt => (
                    <button
                      key={opt.id}
                      onClick={() => update('stoneSupply', opt.id)}
                      style={{
                        flex: 1, padding: '6px 8px', fontSize: 11.5,
                        border: '1px solid var(--border)', borderRadius: 4,
                        background: d.stoneSupply === opt.id ? 'var(--ink)' : 'var(--surface)',
                        color: d.stoneSupply === opt.id ? 'white' : 'var(--ink-2)',
                        cursor: 'pointer',
                      }}
                    >{opt.label}</button>
                  ))}
                </div>
              </div>
              <div className="detail-field">
                <span className="lbl">Onsite visit</span>
                <div className="val">
                  <span className="pill" style={d.onsiteVisitDone ? { background: 'var(--won-soft)', color: 'oklch(0.35 0.1 155)' } : null}>
                    <span className="dot" style={{ background: d.onsiteVisitDone ? 'var(--won)' : 'var(--ink-3)' }}></span>
                    {d.onsiteVisitDone ? 'Yes — done' : 'Not yet'}
                  </span>
                </div>
              </div>
              <div className="detail-field">
                <span className="lbl">Install service</span>
                <div className="val">
                  <span className="pill" style={{ background: d.install ? 'var(--info-soft)' : 'var(--surface-3)', color: d.install ? 'oklch(0.4 0.09 240)' : 'var(--ink-3)' }}>
                    {d.install ? 'Yes — included' : 'Supply only'}
                  </span>
                </div>
              </div>
              <div className="detail-field">
                <span className="lbl">Showroom</span>
                {isLeadership ? (
                  <select value={d.showroom} onChange={(e) => update('showroom', e.target.value)}>
                    {showrooms.map(s => <option key={s.id} value={s.id}>{s.name} ({s.state})</option>)}
                  </select>
                ) : (
                  <div style={{ padding: '6px 0', fontSize: 13, color: 'var(--ink-2)' }}>
                    {showrooms.find(s => s.id === d.showroom)?.name}
                  </div>
                )}
              </div>
              <div className="detail-field">
                <span className="lbl">Probability</span>
                <div className="val num">{fmt.pct(stages.find(s => s.id === d.stage)?.prob || 0, 0)}</div>
              </div>
            </div>
          </div>

          {/* Contact */}
          <div className="detail-section">
            <h4>Contact & dates</h4>
            <div className="detail-grid">
              <div className="detail-field">
                <span className="lbl">Phone</span>
                <input
                  className="mono"
                  defaultValue={d.phone || ''}
                  placeholder="04xx xxx xxx"
                  onBlur={(e) => update('phone', e.target.value)}
                />
              </div>
              <div className="detail-field">
                <span className="lbl">Email</span>
                <input
                  className="mono"
                  type="email"
                  defaultValue={d.email || ''}
                  placeholder="customer@example.com"
                  onBlur={(e) => update('email', e.target.value)}
                />
              </div>
              <div className="detail-field">
                <span className="lbl">Job type</span>
                <select defaultValue={d.product || 'Kitchen'} onChange={(e) => update('product', e.target.value)}>
                  {['Kitchen','Laundry','Walk-in robe','Built-in robes',"Butler's pantry",'Kitchen + Laundry','Vanity','Storage / media wall','Other'].map(p => (
                    <option key={p} value={p}>{p}</option>
                  ))}
                </select>
              </div>
              <div className="detail-field">
                <span className="lbl">Budget range</span>
                <input defaultValue={d.budgetRange || ''} placeholder="e.g. $20–30k" onBlur={(e) => update('budgetRange', e.target.value)}/>
              </div>

              {/* Past-locked dates */}
              {(() => {
                const today = '2026-05-28';
                const fields = [
                  { key: 'designApptDate', label: 'First design appt' },
                  { key: 'quotePresentationDate', label: 'Quote presented' },
                  { key: 'forecastDepositMonth', label: 'Forecast deposit month', hint: 'drives the Forecast tab' },
                ];
                return fields.map(f => {
                  const val = d[f.key];
                  const isPast = val && val < today;
                  return (
                    <div className="detail-field" key={f.key} style={f.key === 'forecastDepositMonth' ? { gridColumn: '1 / -1' } : null}>
                      <span className="lbl">
                        {f.label}
                        {f.hint && <span style={{ fontSize: 10, color: 'var(--ink-3)' }}> · {f.hint}</span>}
                        {isPast && <span style={{ fontSize: 10, color: 'var(--lost)', marginLeft: 4, fontWeight: 600 }}>· locked</span>}
                      </span>
                      {isPast ? (
                        <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                          <div style={{ padding: '6px 10px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface-2)', fontSize: 12.5, color: 'var(--ink-3)', flex: 1, display: 'flex', alignItems: 'center', gap: 4 }}>
                            <Icon name="alert" size={11} color="var(--lost)"/>
                            {fmt.shortDate(val)}
                          </div>
                          <button
                            className="btn sm"
                            onClick={() => {
                              const next = prompt(`Reschedule "${f.label}" to (YYYY-MM-DD):`, today);
                              if (!next || next < today) { alert('Must be today or later.'); return; }
                              update(f.key, next);
                            }}
                          >Reschedule</button>
                        </div>
                      ) : (
                        <input
                          type="date"
                          min={today}
                          defaultValue={val || ''}
                          onBlur={(e) => update(f.key, e.target.value)}
                        />
                      )}
                    </div>
                  );
                });
              })()}
            </div>
          </div>

          {/* Follow-up reminder (deal-level) */}
          <div className="detail-section">
            <h4>Follow-up reminder</h4>
            {d.followUpReminder && d.followUpReminder.date && (
              <div style={{ background: 'var(--warn-soft)', border: '1px solid oklch(0.85 0.08 70)', borderRadius: 6, padding: '8px 12px', marginBottom: 8, display: 'flex', alignItems: 'center', gap: 8, fontSize: 12 }}>
                <Icon name="alert" size={13} color="oklch(0.5 0.13 60)"/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 500 }}>Reminder set for {fmt.shortDate(d.followUpReminder.date)} at {d.followUpReminder.time || '09:00'}</div>
                  {d.followUpReminder.note && <div style={{ marginTop: 4, fontStyle: 'italic', color: 'var(--ink-2)' }}>"{d.followUpReminder.note}"</div>}
                  <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>Synced to {d.repName}'s calendar</div>
                </div>
                <button className="btn sm" onClick={() => update('followUpReminder', null)}><Icon name="close" size={11}/></button>
              </div>
            )}
            <div style={{ display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap', marginBottom: 8 }}>
              <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>Remind in:</span>
              {(window.quickReminderPresets ? window.quickReminderPresets() : []).map(p => (
                <button
                  key={p.id}
                  className="filter-chip"
                  onClick={() => {
                    const el = document.getElementById(`deal-rem-date-${d.id}`);
                    if (el) el.value = window.quickReminderDate(p.days);
                  }}
                >{p.label}</button>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 6, alignItems: 'center', marginBottom: 6, flexWrap: 'wrap' }}>
              <select
                id={`deal-rem-type-${d.id}`}
                defaultValue={d.followUpReminder?.type || 'followup_call'}
                style={{ padding: '5px 8px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 12 }}
              >
                {(window.apptTypes ? window.apptTypes() : [{ id: 'followup_call', label: 'Follow-up call' }]).map(t => (
                  <option key={t.id} value={t.id}>{t.label}</option>
                ))}
              </select>
              <input
                type="date"
                min="2026-05-29"
                defaultValue={d.followUpReminder?.date || ''}
                id={`deal-rem-date-${d.id}`}
                style={{ padding: '5px 8px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 12 }}
              />
              <input
                type="time"
                defaultValue={d.followUpReminder?.time || '09:00'}
                id={`deal-rem-time-${d.id}`}
                style={{ padding: '5px 8px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 12 }}
              />
              <button
                className="btn sm primary"
                onClick={() => {
                  const dateEl = document.getElementById(`deal-rem-date-${d.id}`);
                  const timeEl = document.getElementById(`deal-rem-time-${d.id}`);
                  const noteEl = document.getElementById(`deal-rem-note-${d.id}`);
                  const typeEl = document.getElementById(`deal-rem-type-${d.id}`);
                  if (!dateEl.value) { alert('Pick a date.'); return; }
                  update('followUpReminder', { date: dateEl.value, time: timeEl.value || '09:00', type: typeEl.value, note: noteEl.value || '' });
                }}
              ><Icon name="check" size={11}/> Save reminder</button>
            </div>
            <textarea
              id={`deal-rem-note-${d.id}`}
              defaultValue={d.followUpReminder?.note || ''}
              placeholder="What to follow up about… e.g. 'Send revised stone option', 'Confirm install date'"
              rows="2"
              style={{ width: '100%', padding: '6px 10px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 12, fontFamily: 'inherit', resize: 'vertical', outline: 'none' }}
            />
            <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 4 }}>
              Reminder auto-syncs to the designer's calendar at the scheduled time.
            </div>
          </div>

          {/* Notes */}
          <div className="detail-section">
            <h4>Notes</h4>
            <textarea
              id={`deal-notes-${d.id}`}
              defaultValue={d.notes}
              onBlur={(e) => update('notes', e.target.value)}
              rows="4"
              style={{
                width: '100%',
                padding: '10px 12px',
                border: '1px solid var(--border)',
                borderRadius: 6,
                background: 'var(--surface-2)',
                fontSize: 12.5,
                fontFamily: 'inherit',
                resize: 'vertical',
                outline: 'none',
                color: 'var(--ink)',
              }}
            />
          </div>

          {/* Ownership trail */}
          {d.transferLog && d.transferLog.length > 0 && (
            <div className="detail-section">
              <h4>Ownership history ({d.transferLog.length})</h4>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {d.transferLog.slice().reverse().map((t, i) => (
                  <div key={i} style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: 10,
                    padding: '8px 12px',
                    border: '1px solid var(--border)',
                    borderRadius: 6,
                    background: 'var(--surface-2)',
                    fontSize: 12,
                  }}>
                    <Icon name="arrow-right" size={12} color="var(--ink-3)"/>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: 500 }}>
                        {t.from || <em style={{ fontStyle: 'normal', color: 'var(--ink-3)' }}>Unassigned</em>}
                        <span style={{ color: 'var(--ink-3)' }}> → </span>
                        {t.to || <em style={{ fontStyle: 'normal', color: 'var(--ink-3)' }}>Unassigned</em>}
                      </div>
                      <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 1 }}>
                        by {t.changedBy} · {fmt.shortDate(t.date)}
                        {t.reason ? ` · "${t.reason}"` : ''}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Activity */}
          <div className="detail-section">
            <h4>Activity ({d.activities.length})</h4>
            <div className="activity-list">
              {d.activities.map(a => (
                <div className="activity-item" key={a.id}>
                  <span className={`activity-dot ${a.type}`}></span>
                  <div style={{ flex: 1 }}>
                    <div>{a.label}</div>
                    <div className="activity-meta">{fmt.shortDate(a.date)} · {fmt.daysAgo(a.daysAgo)}</div>
                  </div>
                </div>
              ))}
            </div>
            {logFormOpen ? (
              <div style={{ marginTop: 10, padding: 10, border: '1px solid var(--border)', borderRadius: 6, background: 'var(--surface-2)' }}>
                <div style={{ display: 'flex', gap: 6, marginBottom: 8 }}>
                  {[
                    { id: 'call', label: 'Call' },
                    { id: 'email', label: 'Email' },
                    { id: 'meeting', label: 'Meeting' },
                    { id: 'note', label: 'Note' },
                  ].map(t => (
                    <button
                      key={t.id}
                      className={`filter-chip ${logType === t.id ? 'active' : ''}`}
                      onClick={() => setLogType(t.id)}
                      style={{ fontSize: 11.5 }}
                    >{t.label}</button>
                  ))}
                </div>
                <textarea
                  value={logText}
                  onChange={(e) => setLogText(e.target.value)}
                  placeholder="What happened? e.g. 'Sent revised quote, follow up Tuesday'"
                  rows="2"
                  autoFocus
                  style={{
                    width: '100%', padding: '8px 10px', border: '1px solid var(--border)',
                    borderRadius: 4, fontFamily: 'inherit', fontSize: 12.5, resize: 'vertical', outline: 'none',
                  }}
                />
                <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
                  <button className="btn sm" onClick={() => { setLogFormOpen(false); setLogText(''); }}>Cancel</button>
                  <button
                    className="btn sm primary"
                    disabled={!logText.trim()}
                    style={{ marginLeft: 'auto', opacity: !logText.trim() ? 0.5 : 1 }}
                    onClick={() => {
                      const newActivity = {
                        id: 'a' + Math.floor(Math.random() * 1e9),
                        type: logType,
                        label: logText.trim(),
                        date: new Date().toISOString().slice(0, 10),
                        daysAgo: 0,
                      };
                      onEdit(d.id, { activities: [newActivity, ...(d.activities || [])] });
                      setLogText(''); setLogFormOpen(false);
                    }}
                  ><Icon name="check" size={11}/> Save activity</button>
                </div>
              </div>
            ) : (
              <button className="btn sm" style={{ marginTop: 10 }} onClick={() => setLogFormOpen(true)}>
                <Icon name="plus" size={11}/> Log activity
              </button>
            )}
          </div>
        </div>
      </div>
      {reassignOpen && (
        <ReassignModal
          deals={[d]}
          reps={reps}
          showrooms={showrooms}
          onClose={() => setReassignOpen(false)}
          onConfirm={(newRepId, note) => {
            const newRep = reps.find(r => r.id === newRepId);
            const fromName = d.repName;
            const handoverActivity = {
              id: 'a' + Math.floor(Math.random() * 1e9),
              type: 'note',
              label: `Reassigned from ${fromName} to ${newRep.name}${note ? ` — ${note}` : ''}`,
              date: new Date().toISOString().slice(0, 10),
              daysAgo: 0,
            };
            update('rep', newRep.id);
            update('repName', newRep.name);
            update('activities', [handoverActivity, ...d.activities]);
            setReassignOpen(false);
          }}
        />
      )}
    </div>
  );
}

function ReassignModal({ deals, reps, showrooms, onClose, onConfirm }) {
  const isBulk = deals.length > 1;
  const dealsValue = deals.reduce((s, d) => s + d.value, 0);
  // Figure out which rep options to show — reps that work at all selected deals' showrooms
  const showroomSet = [...new Set(deals.map(d => d.showroom))];
  const eligibleReps = reps.filter(r =>
    showroomSet.every(sid => r.works.includes(sid))
  );
  const ineligibleReps = reps.filter(r => !eligibleReps.includes(r));

  const currentRepIds = [...new Set(deals.map(d => d.rep))];
  const [selected, setSelected] = React.useState('');
  const [note, setNote] = React.useState('');
  const [notifyRep, setNotifyRep] = React.useState(true);

  return (
    <div>
      <div className="detail-overlay" onClick={onClose} style={{ zIndex: 52 }}/>
      <div className="invite-modal" style={{ zIndex: 53 }}>
        <div style={{ padding: '18px 22px 14px', borderBottom: '1px solid var(--border)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div>
              <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.02em' }}>
                {isBulk ? `Reassign ${deals.length} deals` : 'Reassign deal'}
              </div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4 }}>
                {isBulk ? (
                  <>Total value <span className="num">{fmt.money(dealsValue, true)}</span> · across {showroomSet.length} showroom{showroomSet.length > 1 ? 's' : ''}</>
                ) : (
                  <>Currently owned by <strong>{deals[0].repName}</strong> · <span className="num">{fmt.money(deals[0].value, true)}</span></>
                )}
              </div>
            </div>
            <button className="detail-close" style={{ marginLeft: 'auto' }} onClick={onClose}>
              <Icon name="close" size={16}/>
            </button>
          </div>
        </div>

        <div style={{ padding: '18px 22px', maxHeight: '60vh', overflowY: 'auto' }}>
          <div className="detail-section">
            <h4>Assign to</h4>
            <div className="reassign-list">
              {eligibleReps.map(r => (
                <div
                  key={r.id}
                  className={`reassign-row ${selected === r.id ? 'on' : ''}`}
                  onClick={() => setSelected(r.id)}
                >
                  <span className={`radio ${selected === r.id ? 'on' : ''}`}>
                    {selected === r.id && <span className="radio-dot"></span>}
                  </span>
                  <Avatar name={r.name} sz="sm"/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 500, fontSize: 13 }}>{r.name}
                      {currentRepIds.includes(r.id) && (
                        <span className="chip-soft" style={{ marginLeft: 6, fontSize: 9.5, padding: '0 5px' }}>current owner</span>
                      )}
                    </div>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)', display: 'flex', alignItems: 'center', gap: 4, marginTop: 1 }}>
                      Works at:
                      {r.works.map(sid => {
                        const s = showrooms.find(x => x.id === sid);
                        return <span key={sid} style={{ display: 'inline-flex', alignItems: 'center', gap: 2 }}><span className={`ss-tab-dot ${sid}`} style={{ width: 6, height: 6 }}></span>{s.name}</span>;
                      })}
                    </div>
                  </div>
                </div>
              ))}
              {ineligibleReps.length > 0 && (
                <>
                  <div style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--ink-4)', padding: '10px 4px 4px', fontWeight: 500 }}>
                    Not assignable — doesn't work at {isBulk ? 'all selected' : 'this'} showroom{showroomSet.length > 1 ? 's' : ''}
                  </div>
                  {ineligibleReps.map(r => (
                    <div key={r.id} className="reassign-row disabled" title="This rep doesn't have access to one or more of the selected deals' showrooms">
                      <span className="radio disabled"></span>
                      <Avatar name={r.name} sz="sm"/>
                      <div style={{ flex: 1, minWidth: 0, opacity: 0.5 }}>
                        <div style={{ fontSize: 13 }}>{r.name}</div>
                        <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>
                          Works at: {r.works.map(sid => showrooms.find(x => x.id === sid).name).join(', ')}
                        </div>
                      </div>
                    </div>
                  ))}
                </>
              )}
            </div>
          </div>

          <div className="detail-section">
            <h4>Handover note (optional)</h4>
            <textarea
              placeholder="Why is this being reassigned? e.g. 'Amelia on leave — Daniel covering until June 10'"
              value={note}
              onChange={(e) => setNote(e.target.value)}
              rows="3"
              style={{
                width: '100%',
                padding: '10px 12px',
                border: '1px solid var(--border)',
                borderRadius: 6,
                fontFamily: 'inherit',
                fontSize: 12.5,
                resize: 'vertical',
                outline: 'none',
              }}
            />
            <label style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 10, fontSize: 12, color: 'var(--ink-2)', cursor: 'pointer' }}>
              <input type="checkbox" checked={notifyRep} onChange={(e) => setNotifyRep(e.target.checked)} style={{ margin: 0 }}/>
              Notify the new owner by email
            </label>
          </div>
        </div>

        <div style={{ padding: '14px 22px', borderTop: '1px solid var(--border)', background: 'var(--surface-2)', display: 'flex', gap: 8 }}>
          <button className="btn" onClick={onClose}>Cancel</button>
          <button
            className="btn primary"
            style={{ marginLeft: 'auto', opacity: !selected ? 0.5 : 1, cursor: !selected ? 'not-allowed' : 'pointer' }}
            disabled={!selected}
            onClick={() => onConfirm(selected, note)}
          >
            <Icon name="check" size={12}/>
            {isBulk ? `Reassign ${deals.length} deals` : 'Confirm reassignment'}
          </button>
        </div>
      </div>
    </div>
  );
}

window.DealDetail = DealDetail;
window.ReassignModal = ReassignModal;
