// New Contact creation modal — capture a fresh enquiry
function NewContactModal({ reps, showrooms, currentUser, defaultShowroom, allContacts, allDeals, onClose, onCreate, onOpenContact }) {
  const isLeadership = currentUser.role === 'admin' || currentUser.role === 'leadership';
  const defaultShowroomId = defaultShowroom !== 'all' ? defaultShowroom : (currentUser.home || showrooms[0].id);
  const defaultOwner = currentUser.repId
    ? reps.find(r => r.id === currentUser.repId)?.name
    : (reps.find(r => r.works.includes(defaultShowroomId))?.name || reps[0].name);

  const [draft, setDraft] = React.useState({
    name: '',
    phone: '',
    email: '',
    suburb: '',
    address: '',
    homeShowroom: defaultShowroomId,
    owner: defaultOwner,
    means: 'Showroom walk-in',
    source: 'Driving by',
    outcome: 'new_lead',
    comments: '',
  });

  const update = (k, v) => setDraft(prev => ({ ...prev, [k]: v }));
  // Track which fields were pre-filled from a global (network) match
  const [prefilled, setPrefilled] = React.useState({});
  const markEdited = (k) => setPrefilled(prev => (prev[k] ? { ...prev, [k]: false } : prev));
  const pf = (k) => prefilled[k]
    ? <span style={{ marginLeft: 6, fontSize: 9, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em', color: 'var(--accent-ink)', background: 'var(--accent-soft)', padding: '1px 5px', borderRadius: 3 }}>from network</span>
    : null;
  const pfStyle = (k) => prefilled[k] ? { background: 'var(--accent-soft)', borderColor: 'var(--accent)' } : null;

  const eligibleOwners = reps.filter(r => r.works.includes(draft.homeShowroom));
  React.useEffect(() => {
    if (!eligibleOwners.find(r => r.name === draft.owner)) {
      update('owner', eligibleOwners[0]?.name || draft.owner);
    }
  }, [draft.homeShowroom]);

  const valid = draft.name.trim().length > 1 && draft.homeShowroom;

  const MEANS_OPTIONS = ['Showroom walk-in', 'Phone', 'Email', 'Messenger', 'Zoom'];
  const SOURCE_OPTIONS = ['Driving by', 'Website', 'Google', 'Referral', 'Facebook', 'Newsletter', 'BayIsland', 'Other'];
  const OUTCOMES = [
    { id: 'new_lead', label: 'New Lead', desc: 'Right client — not ready to proceed yet' },
    { id: 'qualifies', label: 'Qualifies — Appt Made', desc: 'Right client — appointment booked' },
    { id: 'no_sale', label: 'Does Not Qualify', desc: 'Not the right client for KUB' },
  ];

  return (
    <div>
      <div className="detail-overlay" onClick={onClose} style={{ zIndex: 52 }}/>
      <div className="invite-modal" style={{ zIndex: 53, width: 600 }}>
        <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' }}>New contact</div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4 }}>
                Walk-in · phone · email · web — anyone who's just made first contact.
              </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: '65vh', overflowY: 'auto' }}>
          <div className="detail-section">
            <h4>Who is it?</h4>
            <div className="detail-grid">
              <div className="detail-field" style={{ gridColumn: '1 / -1' }}>
                <span className="lbl">Client name *{pf('name')}</span>
                <input
                  value={draft.name}
                  onChange={(e) => { update('name', e.target.value); markEdited('name'); }}
                  style={pfStyle('name')}
                  placeholder="e.g. Sarah & James Wilson"
                  autoFocus
                />
              </div>
              <div className="detail-field">
                <span className="lbl">Phone{pf('phone')}</span>
                <input
                  value={draft.phone}
                  onChange={(e) => { update('phone', e.target.value); markEdited('phone'); }}
                  style={pfStyle('phone')}
                  placeholder="04xx xxx xxx"
                  className="mono"
                />
              </div>
              <div className="detail-field">
                <span className="lbl">Email{pf('email')}</span>
                <input
                  value={draft.email}
                  onChange={(e) => { update('email', e.target.value); markEdited('email'); }}
                  style={pfStyle('email')}
                  type="email"
                  className="mono"
                  placeholder="sarah@example.com"
                />
              </div>
              <div className="detail-field">
                <span className="lbl">Suburb{pf('suburb')}</span>
                <input
                  value={draft.suburb}
                  onChange={(e) => { update('suburb', e.target.value); markEdited('suburb'); }}
                  style={pfStyle('suburb')}
                  placeholder="e.g. Bondi"
                />
              </div>
              <div className="detail-field" style={{ gridColumn: '1 / -1' }}>
                <span className="lbl">Address {pf('address') || <span style={{ fontSize: 10, color: 'var(--ink-3)' }}>· optional</span>}</span>
                <input
                  value={draft.address}
                  onChange={(e) => { update('address', e.target.value); markEdited('address'); }}
                  style={pfStyle('address')}
                  placeholder="e.g. 12 Orchard St, Bayswater VIC 3153"
                />
              </div>
              <div className="detail-field">
                <span className="lbl">Home showroom *</span>
                <select value={draft.homeShowroom} onChange={(e) => update('homeShowroom', e.target.value)}>
                  {(isLeadership ? showrooms : showrooms.filter(s => (currentUser.works || currentUser.manages || []).includes(s.id))).map(s => (
                    <option key={s.id} value={s.id}>{s.name} ({s.state})</option>
                  ))}
                </select>
              </div>
              <div className="detail-field">
                <span className="lbl">Owner designer</span>
                <select value={draft.owner} onChange={(e) => update('owner', e.target.value)}>
                  {eligibleOwners.map(r => <option key={r.id} value={r.name}>{r.name}</option>)}
                </select>
              </div>
            </div>
            {allContacts && (
              <CustomerLookup
                allContacts={allContacts}
                allDeals={allDeals || []}
                showrooms={showrooms}
                name={draft.name}
                phone={draft.phone}
                email={draft.email}
                address={draft.address}
                onMerge={(c) => {
                  setDraft(prev => ({
                    ...prev,
                    name: c.name || prev.name,
                    phone: c.phone || prev.phone,
                    email: c.email || prev.email,
                    suburb: c.suburb || prev.suburb,
                    address: c.address || prev.address,
                    homeShowroom: c.homeShowroom || prev.homeShowroom,
                  }));
                  setPrefilled({
                    name: !!c.name, phone: !!c.phone, email: !!c.email,
                    suburb: !!c.suburb, address: !!c.address,
                  });
                  setDraft(prev => ({ ...prev, _matchedContactId: c.id }));
                }}
              />
            )}
          </div>

          <div className="detail-section">
            <h4>How did they reach us?</h4>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {MEANS_OPTIONS.map(m => (
                <button
                  key={m}
                  className={`filter-chip ${draft.means === m ? 'active' : ''}`}
                  onClick={() => update('means', m)}
                  style={{ fontWeight: 500 }}
                >
                  {m}
                </button>
              ))}
            </div>
          </div>

          <div className="detail-section">
            <h4>How did they become aware of KUB?</h4>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {SOURCE_OPTIONS.map(s => (
                <button
                  key={s}
                  className={`filter-chip ${draft.source === s ? 'active' : ''}`}
                  onClick={() => update('source', s)}
                  style={{ fontWeight: 500 }}
                >
                  {s}
                </button>
              ))}
            </div>
          </div>

          <div className="detail-section">
            <h4>Initial outcome</h4>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {OUTCOMES.map(o => (
                <div
                  key={o.id}
                  className={`reassign-row ${draft.outcome === o.id ? 'on' : ''}`}
                  onClick={() => update('outcome', o.id)}
                >
                  <span className={`radio ${draft.outcome === o.id ? 'on' : ''}`}>
                    {draft.outcome === o.id && <span className="radio-dot"></span>}
                  </span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 500, fontSize: 13 }}>{o.label}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{o.desc}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="detail-section">
            <h4>Detailed comments</h4>
            <textarea
              placeholder="Why do they qualify / not qualify · what are the next steps · date of appointment · any other relevant details"
              value={draft.comments}
              onChange={(e) => update('comments', 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',
              }}
            />
          </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: !valid ? 0.5 : 1, cursor: !valid ? 'not-allowed' : 'pointer' }}
            disabled={!valid}
            onClick={() => onCreate(draft)}
          >
            <Icon name="plus" size={12}/> Add contact
          </button>
        </div>
      </div>
    </div>
  );
}

window.NewContactModal = NewContactModal;
