// Quick Create modal — fast entry point to create anything

const QC_ITEMS = [
  { id: 'deal',     title: 'Deal',              section: 'crm',        icon: 'card',      desc: 'Log a new deal in the CRM pipeline.', kbd: 'D' },
  { id: 'customer', title: 'Customer',          section: 'customers',  icon: 'store',     desc: 'Add a new customer account.', kbd: 'C' },
  { id: 'invoice',  title: 'Invoice',           section: 'fin-invoices', icon: 'doc',     desc: 'Bill a customer for products or services.', kbd: 'V' },
  { id: 'bill',     title: 'Bill',              section: 'fin-bills',  icon: 'card',      desc: 'Record a vendor bill or expense.', kbd: 'B' },
  { id: 'idea',     title: 'Innovation idea',   section: 'innovation', icon: 'bulb',      desc: 'Capture an idea for the innovation board.', kbd: 'I' },
  { id: 'contract', title: 'Contract',          section: 'contracts',  icon: 'doc',       desc: 'Upload or draft a new contract.', kbd: 'K' },
  { id: 'employee', title: 'Employee invite',   section: 'hrm',        icon: 'users',     desc: 'Invite someone to the workspace.', kbd: 'E' },
  { id: 'note',     title: 'Personal note',     section: null,         icon: 'pencil',    desc: 'A quick note that lands in your inbox.', kbd: 'N' },
  { id: 'file',     title: 'Upload file',       section: 'files',      icon: 'upload',    desc: 'Drop a file into a workspace folder.', kbd: 'U' },
];

function QuickCreate({ open, onClose, onNavigate, initialType }) {
  const [active, setActive] = useState(null);
  const [q, setQ] = useState('');
  const inputRef = useRef();

  useEffect(() => {
    if (open) {
      setActive(null);
      setQ('');
      setTimeout(() => inputRef.current?.focus(), 50);
    }
  }, [open, initialType]);

  if (!open) return null;

  // Contextual skew by sidebar group: surface that group's create-types first,
  // always plus the universal defaults (task, note). Dashboard/none → no skew.
  const GROUP_SUGGEST = {
    hr:  ['employee'],
    rev: ['deal', 'customer', 'contract'],
    fin: ['invoice', 'bill', 'contract'],
    ops: ['idea', 'file'],
    sys: ['employee'],
  };
  const base = GROUP_SUGGEST[initialType];
  const suggestedIds = base ? [...new Set([...base, 'note'])] : [];
  const isSearching = !!q.trim();
  const matches = it => it.title.toLowerCase().includes(q.toLowerCase()) || it.desc.toLowerCase().includes(q.toLowerCase());
  const filtered = QC_ITEMS.filter(it => !isSearching || matches(it));
  const suggested = !isSearching ? suggestedIds.map(id => QC_ITEMS.find(i => i.id === id)).filter(Boolean) : [];
  const rest = !isSearching ? QC_ITEMS.filter(it => !suggestedIds.includes(it.id)) : filtered;

  const renderItem = (it, suggested) => (
    <button key={it.id} onClick={() => setActive(it.id)}
            style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: 12, border: '1px solid transparent', background: 'transparent', borderRadius: 8, cursor: 'pointer', textAlign: 'left' }}
            onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-elev)'}
            onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
      <div style={{ width: 32, height: 32, background: 'var(--brand-orange-tint)', borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--brand-orange)', flexShrink: 0 }}>
        <Icon name={it.icon} size={15} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="row gap-2"><strong style={{ fontSize: 13.5 }}>{it.title}</strong><Kbd>{it.kbd}</Kbd></div>
        <div className="dim" style={{ fontSize: 11.5, marginTop: 2 }}>{it.desc}</div>
      </div>
    </button>
  );

  return (
    <div className="cmdk-scrim" onClick={onClose} style={{ paddingTop: '10vh' }}>
      <div onClick={e => e.stopPropagation()}
           style={{ width: 680, maxWidth: '94vw', background: 'var(--bg-card)', borderRadius: 14, border: '1px solid var(--border)', boxShadow: 'var(--shadow-lg)', overflow: 'hidden', display: 'flex', flexDirection: 'column', maxHeight: '78vh' }}>

        {active ? (
          <QuickCreateForm
            type={active}
            item={QC_ITEMS.find(i => i.id === active)}
            onBack={() => setActive(null)}
            onClose={onClose}
            onNavigate={onNavigate} />
        ) : (
          <>
            <div style={{ padding: '16px 22px 12px', borderBottom: '1px solid var(--border)' }}>
              <h2 style={{ margin: 0, fontSize: 17, fontWeight: 600 }}>Quick create</h2>
              <p className="muted" style={{ margin: '4px 0 12px', fontSize: 12.5 }}>What would you like to create?</p>
              <div className="search-inline">
                <Icon name="search" size={14} />
                <input ref={inputRef} value={q} onChange={e => setQ(e.target.value)} placeholder="Type to filter…" style={{ flex: 1 }} />
                <Kbd>esc</Kbd>
              </div>
            </div>
            <div style={{ overflowY: 'auto', flex: 1 }}>
              {suggested.length > 0 && (
                <>
                  <div className="qc-sec-label">Suggested for this screen</div>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 4, padding: '0 10px 6px' }}>
                    {suggested.map(it => renderItem(it))}
                  </div>
                  <div className="qc-sec-label">Everything else</div>
                </>
              )}
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 4, padding: suggested.length > 0 ? '0 10px 10px' : 10 }}>
                {rest.map(it => renderItem(it))}
              </div>
              {isSearching && filtered.length === 0 && <div className="dim" style={{ textAlign: 'center', padding: 40 }}>No matches for "{q}"</div>}
            </div>
          </>
        )}
      </div>
    </div>
  );
}

function QuickCreateForm({ type, item, onBack, onClose, onNavigate }) {
  const D = window.HitcentsData;
  const [draft, setDraft] = useState({});
  const [created, setCreated] = useState(false);

  function set(patch) { setDraft(d => ({ ...d, ...patch })); }
  function submit() {
    setCreated(true);
    setTimeout(() => {
      if (item.section) onNavigate(item.section);
      onClose();
    }, 1000);
  }

  if (created) {
    return (
      <div style={{ padding: 40, textAlign: 'center' }}>
        <div style={{ width: 56, height: 56, borderRadius: 999, background: 'var(--green)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: '#fff', marginBottom: 14 }}>
          <Icon name="check" size={24} stroke={3} />
        </div>
        <h3 style={{ margin: '0 0 4px', fontSize: 17 }}>Created!</h3>
        <p className="muted" style={{ fontSize: 13 }}>Taking you to {item.section || 'your workspace'}…</p>
      </div>
    );
  }

  return (
    <>
      <div style={{ padding: '14px 22px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 12 }}>
        <Button variant="ghost" size="sm" icon="chev_l" onClick={onBack}>Back</Button>
        <span className="dim">/</span>
        <div className="row gap-2">
          <div style={{ width: 26, height: 26, background: 'var(--brand-orange-tint)', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--brand-orange)' }}>
            <Icon name={item.icon} size={12} />
          </div>
          <strong>New {item.title.toLowerCase()}</strong>
        </div>
      </div>

      <div style={{ padding: 22, overflowY: 'auto', flex: 1 }}>
        {type === 'invoice' && (
          <>
            <div className="field"><label>Customer</label>
              <select onChange={e => set({ customer: e.target.value })} defaultValue=""><option value="">— Select customer —</option>{D.CUSTOMERS.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}</select>
            </div>
            <div className="grid g-2" style={{ gap: 12 }}>
              <div className="field"><label>Issue date</label><input type="date" onChange={e => set({ issued: e.target.value })} /></div>
              <div className="field"><label>Due date</label><input type="date" onChange={e => set({ due: e.target.value })} /></div>
            </div>
            <div className="field"><label>Description</label><input autoFocus placeholder="e.g. SaaS platform — May" onChange={e => set({ desc: e.target.value })} /></div>
            <div className="field"><label>Amount (USD)</label><input type="number" placeholder="0" onChange={e => set({ amount: +e.target.value })} /></div>
          </>
        )}

        {type === 'bill' && (
          <>
            <div className="field"><label>Vendor</label>
              <select onChange={e => set({ vendor: e.target.value })} defaultValue=""><option value="">— Select vendor —</option>{(D.VENDORS || []).map(v => <option key={v.id} value={v.id}>{v.name}</option>)}</select>
            </div>
            <div className="grid g-2" style={{ gap: 12 }}>
              <div className="field"><label>Issue date</label><input type="date" onChange={e => set({ issued: e.target.value })} /></div>
              <div className="field"><label>Due date</label><input type="date" onChange={e => set({ due: e.target.value })} /></div>
            </div>
            <div className="field"><label>Expense account</label>
              <select onChange={e => set({ code: e.target.value })}>{D.FIN_ACCOUNTS.filter(a => a.type === 'Expense').map(a => <option key={a.code} value={a.code}>{a.code} · {a.name}</option>)}</select>
            </div>
            <div className="field"><label>Amount (USD)</label><input type="number" placeholder="0" onChange={e => set({ amount: +e.target.value })} /></div>
          </>
        )}

        {type === 'deal' && (
          <>
            <div className="field"><label>Deal name</label><input autoFocus placeholder="e.g. Northbrook — renewal expansion" onChange={e => set({ name: e.target.value })} /></div>
            <div className="grid g-2" style={{ gap: 12 }}>
              <div className="field"><label>Customer</label>
                <select onChange={e => set({ customer: e.target.value })}><option value="">— New prospect —</option>{D.CUSTOMERS.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}</select>
              </div>
              <div className="field"><label>Value (USD)</label><input type="number" placeholder="0" onChange={e => set({ value: +e.target.value })} /></div>
              <div className="field"><label>Stage</label>
                <select onChange={e => set({ stage: e.target.value })} defaultValue="lead">{D.DEAL_STAGES.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}</select>
              </div>
              <div className="field"><label>Close date</label><input type="date" onChange={e => set({ close: e.target.value })} /></div>
              <div className="field"><label>Owner</label>
                <select onChange={e => set({ owner: e.target.value })}>{D.EMPLOYEES.filter(e => e.dept === 'sal').map(e => <option key={e.id} value={e.id}>{e.name}</option>)}</select>
              </div>
              <div className="field"><label>Source</label>
                <select onChange={e => set({ source: e.target.value })}><option>Inbound</option><option>Outbound</option><option>Referral</option><option>Partner</option><option>Expansion</option></select>
              </div>
            </div>
          </>
        )}

        {type === 'contract' && (
          <>
            <div className="field"><label>Contract name</label><input autoFocus placeholder="e.g. Acme — MSA + Order Form" onChange={e => set({ name: e.target.value })} /></div>
            <div className="grid g-2" style={{ gap: 12 }}>
              <div className="field"><label>Type</label>
                <select onChange={e => set({ type: e.target.value })} defaultValue="customer">{D.CONTRACT_TYPES.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}</select>
              </div>
              <div className="field"><label>Counterparty</label><input placeholder="Company or person" onChange={e => set({ counterparty: e.target.value })} /></div>
              <div className="field"><label>Value (USD)</label><input type="number" onChange={e => set({ value: +e.target.value })} /></div>
              <div className="field"><label>Billing</label><input placeholder="e.g. Annual" defaultValue="Annual" onChange={e => set({ billing: e.target.value })} /></div>
              <div className="field"><label>Start date</label><input type="date" onChange={e => set({ startDate: e.target.value })} /></div>
              <div className="field"><label>End date</label><input type="date" onChange={e => set({ endDate: e.target.value })} /></div>
            </div>
            <div style={{ padding: 16, border: '2px dashed var(--border-strong)', borderRadius: 8, textAlign: 'center', marginTop: 8 }}>
              <Icon name="upload" size={20} style={{ color: 'var(--text-muted)' }} />
              <div className="muted" style={{ fontSize: 12.5, marginTop: 6 }}>Drag contract files here or click to upload</div>
            </div>
          </>
        )}

        {type === 'customer' && (
          <>
            <div className="field"><label>Company name</label><input autoFocus onChange={e => set({ name: e.target.value })} /></div>
            <div className="grid g-2" style={{ gap: 12 }}>
              <div className="field"><label>Website</label><input placeholder="acme.com" onChange={e => set({ website: e.target.value })} /></div>
              <div className="field"><label>Industry</label><input onChange={e => set({ industry: e.target.value })} /></div>
              <div className="field"><label>Tier</label>
                <select defaultValue="SMB" onChange={e => set({ tier: e.target.value })}><option>Enterprise</option><option>Mid-market</option><option>SMB</option></select>
              </div>
              <div className="field"><label>Account owner</label>
                <select onChange={e => set({ owner: e.target.value })}>{D.EMPLOYEES.filter(e => e.dept === 'sal').map(e => <option key={e.id} value={e.id}>{e.name}</option>)}</select>
              </div>
            </div>
          </>
        )}

        {type === 'employee' && (
          <>
            <div className="field"><label>Work email</label><input autoFocus type="email" placeholder="name@hitcents.com" onChange={e => set({ email: e.target.value })} /></div>
            <div className="grid g-2" style={{ gap: 12 }}>
              <div className="field"><label>Full name</label><input onChange={e => set({ name: e.target.value })} /></div>
              <div className="field"><label>Title</label><input onChange={e => set({ title: e.target.value })} /></div>
              <div className="field"><label>Department</label>
                <select onChange={e => set({ dept: e.target.value })}>{D.DEPTS.map(d => <option key={d.id} value={d.id}>{d.name}</option>)}</select>
              </div>
              <div className="field"><label>Manager</label>
                <select onChange={e => set({ mgr: e.target.value })}>{D.EMPLOYEES.map(e => <option key={e.id} value={e.id}>{e.name}</option>)}</select>
              </div>
              <div className="field"><label>Start date</label><input type="date" onChange={e => set({ start: e.target.value })} /></div>
              <div className="field"><label>Role</label>
                <select onChange={e => set({ role: e.target.value })}><option>Employee</option><option>Manager</option><option>Admin</option></select>
              </div>
            </div>
          </>
        )}

        {type === 'note' && (
          <>
            <div className="field"><label>Title (optional)</label><input autoFocus onChange={e => set({ title: e.target.value })} /></div>
            <div className="field"><label>Note</label><textarea rows={8} placeholder="Capture whatever you'll forget later..." onChange={e => set({ body: e.target.value })} /></div>
            <div className="muted" style={{ fontSize: 12 }}>Lands in your personal inbox. Tag with @people to share.</div>
          </>
        )}

        {type === 'file' && (
          <>
            <div className="field"><label>Folder</label>
              <select onChange={e => set({ folder: e.target.value })}>{D.FILES.filter(f => f.kind === 'folder').map(f => <option key={f.id} value={f.id}>{f.name}</option>)}</select>
            </div>
            <div style={{ padding: 32, border: '2px dashed var(--border-strong)', borderRadius: 10, textAlign: 'center' }}>
              <Icon name="upload" size={32} style={{ color: 'var(--text-muted)' }} />
              <div style={{ fontWeight: 500, fontSize: 14, marginTop: 12 }}>Drag files here or click to upload</div>
              <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>Up to 100 MB per file. Folder ACLs apply.</div>
            </div>
          </>
        )}
      </div>

      <div style={{ padding: '14px 22px', borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', background: 'var(--bg-elev)' }}>
        <Button variant="ghost" onClick={onClose}>Cancel</Button>
        <div className="row gap-2">
          <Button variant="secondary">Save as draft</Button>
          <Button variant="primary" icon="check" onClick={submit}>Create {item.title.toLowerCase()}</Button>
        </div>
      </div>
    </>
  );
}

window.QuickCreate = QuickCreate;
