// Manage Showrooms — admin-only CRUD for showroom locations
function ShowroomsAdmin({ showrooms, reps, deals, users, onSave }) {
  const [draft, setDraft] = React.useState(showrooms);
  const [editingId, setEditingId] = React.useState(null);
  const [addOpen, setAddOpen] = React.useState(false);

  const dealCount = (sid) => deals.filter((d) => d.showroom === sid).length;
  const repCount = (sid) => reps.filter((r) => (r.works || []).includes(sid)).length;

  const dirty = JSON.stringify(draft) !== JSON.stringify(showrooms);

  return (
    <div>
      <div className="card" style={{ marginBottom: 16, padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 14, background: 'var(--info-soft)', border: '1px solid oklch(0.85 0.04 240)' }}>
        <div style={{ width: 32, height: 32, borderRadius: 16, background: 'var(--info)', color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name="home" size={16} color="white" />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'oklch(0.3 0.1 240)', marginBottom: 2 }}>Manage showroom locations</div>
          <div style={{ fontSize: 12, color: 'oklch(0.35 0.08 240)' }}>
            Add a new showroom as you expand, rename or update existing ones. New showrooms appear everywhere — filters, reports, targets, and the assignment options in Team &amp; Access.
          </div>
        </div>
        <button className="btn primary" onClick={() => setAddOpen(true)}><Icon name="plus" size={12} /> Add showroom</button>
      </div>

      <div className="card">
        <div className="card-hd">
          <div>
            <div className="card-title">{draft.length} showroom{draft.length !== 1 ? 's' : ''}</div>
            <div className="card-sub">Click a row to edit · changes apply across the whole system on save</div>
          </div>
          {dirty &&
          <div style={{ display: 'flex', gap: 6 }}>
              <button className="btn sm" onClick={() => setDraft(showrooms)}>Revert</button>
              <button className="btn sm primary" onClick={() => onSave(draft)}><Icon name="check" size={11} /> Save changes</button>
            </div>
          }
        </div>
        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th>Showroom</th>
                <th>State</th>
                <th className="num-col">Opened</th>
                <th className="num-col">Designers</th>
                <th className="num-col">Deals</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {draft.map((s, i) =>
              <tr key={s.id}>
                  <td style={{ fontSize: "15px" }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span className={`ss-tab-dot ${s.id}`} style={{ width: 10, height: 10, borderRadius: 5, background: `var(--ss-${s.id}, var(--accent))` }}></span>
                      {editingId === s.id ?
                    <input value={s.name} onChange={(e) => setDraft((d) => d.map((x, j) => j === i ? { ...x, name: e.target.value } : x))} style={{ padding: '4px 8px', border: '1px solid var(--ink-3)', borderRadius: 4, fontSize: 13 }} /> :
                    <span style={{ fontWeight: 500 }}>{s.name}</span>}
                      <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-4)' }}>{s.id && s.id.length > 12 ? s.id.slice(0, 8) + '…' : s.id}</span>
                    </div>
                  </td>
                  <td style={{ fontSize: "15px" }}>
                    {editingId === s.id ?
                  <input value={s.state} onChange={(e) => setDraft((d) => d.map((x, j) => j === i ? { ...x, state: e.target.value } : x))} style={{ padding: '4px 8px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 13, width: 60 }} /> :
                  <span>{s.state}</span>}
                  </td>
                  <td className="num-col" style={{ fontSize: "15px" }}>
                    {editingId === s.id ?
                  <input type="number" value={s.openedYear || ''} onChange={(e) => setDraft((d) => d.map((x, j) => j === i ? { ...x, openedYear: parseInt(e.target.value) || null } : x))} style={{ padding: '4px 8px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 13, width: 70 }} /> :
                  <span className="num">{s.openedYear || '—'}</span>}
                  </td>
                  <td className="num-col" style={{ fontSize: "15px" }}><span className="num">{repCount(s.id)}</span></td>
                  <td className="num-col" style={{ fontSize: "15px" }}><span className="num">{dealCount(s.id)}</span></td>
                  <td>
                    <div style={{ display: 'flex', gap: 4, justifyContent: 'flex-end' }}>
                      <button className="btn icon sm" onClick={() => setEditingId(editingId === s.id ? null : s.id)} title="Edit">
                        <Icon name={editingId === s.id ? 'check' : 'edit'} size={13} />
                      </button>
                      <button
                      className="btn icon sm"
                      title="Remove"
                      onClick={() => {
                        if (dealCount(s.id) > 0) {alert(`Can't remove ${s.name} — it still has ${dealCount(s.id)} deals. Reassign or archive them first.`);return;}
                        if (confirm(`Remove ${s.name}? This can't be undone.`)) setDraft((d) => d.filter((x) => x.id !== s.id));
                      }}
                      style={{ color: 'var(--lost)' }}>
                      
                        <Icon name="close" size={13} />
                      </button>
                    </div>
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {addOpen &&
      <AddShowroomModal
        existingIds={draft.map((s) => s.id)}
        onClose={() => setAddOpen(false)}
        onAdd={(sr) => {setDraft((d) => [...d, sr]);setAddOpen(false);}} />

      }
    </div>);

}

function AddShowroomModal({ existingIds, onClose, onAdd }) {
  const [name, setName] = React.useState('');
  const [state, setState] = React.useState('VIC');
  const [year, setYear] = React.useState(new Date().getFullYear());

  // Auto-generate a 3-letter id from the name
  const genId = (n) => {
    let base = n.toLowerCase().replace(/[^a-z]/g, '').slice(0, 3) || 'new';
    let id = base,n2 = 1;
    while (existingIds.includes(id)) {id = base + n2;n2++;}
    return id;
  };
  const valid = name.trim().length > 1;

  return (
    <div>
      <div className="detail-overlay" onClick={onClose} style={{ zIndex: 52 }} />
      <div className="invite-modal" style={{ zIndex: 53, width: 480 }}>
        <div style={{ padding: '18px 22px 14px', borderBottom: '1px solid var(--border)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.02em' }}>Add showroom</div>
            <button className="detail-close" style={{ marginLeft: 'auto' }} onClick={onClose}><Icon name="close" size={16} /></button>
          </div>
        </div>
        <div style={{ padding: '18px 22px' }}>
          <div className="detail-grid">
            <div className="detail-field" style={{ gridColumn: '1 / -1' }}>
              <span className="lbl">Showroom name *</span>
              <input value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Geelong" autoFocus />
            </div>
            <div className="detail-field">
              <span className="lbl">State</span>
              <select value={state} onChange={(e) => setState(e.target.value)}>
                {['VIC', 'NSW', 'QLD', 'SA', 'WA', 'TAS', 'ACT', 'NT'].map((s) => <option key={s} value={s}>{s}</option>)}
              </select>
            </div>
            <div className="detail-field">
              <span className="lbl">Year opened</span>
              <input type="number" value={year} onChange={(e) => setYear(parseInt(e.target.value) || null)} />
            </div>
          </div>
          {name.trim() &&
          <div style={{ marginTop: 12, fontSize: 11.5, color: 'var(--ink-3)' }}>
              Internal ID will be <span className="mono" style={{ background: 'var(--surface-3)', padding: '1px 6px', borderRadius: 3 }}>{genId(name)}</span>
            </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"
            disabled={!valid}
            style={{ marginLeft: 'auto', opacity: !valid ? 0.5 : 1 }}
            onClick={() => onAdd({ id: genId(name), name: name.trim(), state, openedYear: year, target: 0 })}>
            <Icon name="plus" size={12} /> Add showroom</button>
        </div>
      </div>
    </div>);

}

window.ShowroomsAdmin = ShowroomsAdmin;