/* ============================================================
   P&L App (Lite) · Vendor / customer list (from the US demo's)

   The names are the ones on the rows (Lite keeps no separate list). Rename one everywhere at once,
   or merge two that are really the same: both change the rows themselves. New names are added
   by typing them on a row.
   ============================================================ */
function NameManager({ kind }) {
  const db = useDB();
  const isF = kind === 'furnizor';
  const list = isF ? db.furnizori : db.clienti;
  const aliases = isF ? db.furnizorAlias : db.clientAlias;
  const word = isF ? { title: 'Vendors', one: 'bill', many: 'bills', add: 'New vendor…', hint: 'Rename changes every bill from this vendor. Merge moves one name\'s bills into another.' }
                   : { title: 'Customers', one: 'invoice', many: 'invoices', add: 'New customer…', hint: 'Rename changes every invoice to this customer. Merge moves one name\'s invoices into another.' };
  const [q, setQ] = useState('');
  const [newName, setNewName] = useState('');
  const [note, setNote] = useState('');
  const [editId, setEditId] = useState(null);
  const [editVal, setEditVal] = useState('');
  const [mergeId, setMergeId] = useState(null);
  const [confirm, setConfirm] = useState(null);
  const [del, setDel] = useState(null);   // the name being deleted, awaiting "are you sure?"

  const needle = foldText(q);
  const shown = list.filter(x => !needle || foldText(x.name).includes(needle))
                    .slice().sort((a, b) => a.name.localeCompare(b.name, 'en', { sensitivity: 'base' }));
  const aliasesOf = id => aliases.filter(a => a.targetId === id).map(a => a.alias);

  const add = async () => {
    const typed = newName.trim(); if (!typed) return;
    const got = await addName(kind, typed);
    if (got && foldText(got) !== foldText(typed)) setNote(`Already exists: ${got}`);
    else setNote(got ? '' : '');
    if (got) setNewName('');
  };
  const saveEdit = async () => {
    const v = editVal.trim(); if (!v) { setEditId(null); return; }
    const ok = await renameName(kind, editId, v);
    if (ok) setEditId(null);
  };

  return (
    <>
      <div>
        <p className="text-[12.5px] text-muted mb-3">{word.hint}</p>
        {note && <div className="text-[12.5px] mb-2" style={{ color: 'var(--neg)' }}>{note}</div>}
        <SearchInput value={q} onChange={setQ} placeholder="Search the list…" width="100%" />
        <div className="text-[12px] text-muted mt-2 mb-2">{shown.length} {shown.length === 1 ? 'name' : 'names'}{needle ? ' found' : ''}</div>
        <div className="flex flex-col gap-1.5">
          {shown.map(x => {
            const used = countByName(kind, x.name);
            const al = aliasesOf(x.id);
            return (
              <div key={x.id} className="rounded-xl border border-line px-3 py-2 hover:border-[#D9DED5] transition-colors">
                <div className="flex items-center gap-2 min-h-[32px]">
                  {editId === x.id ? (
                    <Input autoFocus compact value={editVal} onChange={e => setEditVal(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') saveEdit(); if (e.key === 'Escape') setEditId(null); }} />
                  ) : (
                    <><span className="text-[13.5px] text-ink font-medium flex-1 min-w-0 truncate">{x.name}</span>
                      <span className="text-[11.5px] text-muted num shrink-0">{used} {used === 1 ? word.one : word.many}</span></>
                  )}
                  {editId === x.id ? (
                    <div className="flex gap-0.5 shrink-0"><IconButton icon="check" tone="pos" title="Save" onClick={saveEdit} /><IconButton icon="x" title="Cancel" onClick={() => setEditId(null)} /></div>
                  ) : (
                    <div className="flex gap-0.5 shrink-0">
                      <IconButton icon="edit" title="Rename" onClick={() => { setEditId(x.id); setEditVal(x.name); setMergeId(null); }} />
                      {used === 0 && <IconButton icon="trash" tone="neg" title="Delete: no row uses this name" onClick={() => { setDel(x); setEditId(null); setMergeId(null); }} />}
                      <Button variant="ghost" size="sm" onClick={() => { setMergeId(mergeId === x.id ? null : x.id); setEditId(null); }}>Merge…</Button>
                    </div>
                  )}
                </div>
                {al.length > 0 && editId !== x.id && (
                  <div className="text-[11.5px] text-muted mt-0.5 truncate" title={al.join(' · ')}>Also recognized as: {al.join(' · ')}</div>
                )}
                {mergeId === x.id && (
                  <div className="mt-2 flex items-center gap-2">
                    <span className="text-[12.5px] text-muted shrink-0">Merge into:</span>
                    <div className="flex-1 min-w-0">
                      <PickOrAdd value="" options={list.filter(o => o.id !== x.id).map(o => o.name)} allowCreate={false}
                                 placeholder="Pick the official name…" searchPlaceholder="Search…"
                                 onChange={name => { const to = list.find(o => o.name === name); if (to) setConfirm({ from: x, to }); }} />
                    </div>
                  </div>
                )}
              </div>
            );
          })}
          {shown.length === 0 && <div className="text-[13px] text-muted py-6 text-center">Nothing matches.</div>}
        </div>
      </div>
      <ConfirmDialog open={!!confirm} onClose={() => setConfirm(null)} danger={false} confirmLabel="Merge"
        title={confirm ? `Merge "${confirm.from.name}" into "${confirm.to.name}"?` : ''}
        message={confirm ? `The ${countByName(kind, confirm.from.name)} ${word.many} of "${confirm.from.name}" move to "${confirm.to.name}", and "${confirm.from.name}" leaves the list.` : ''}
        onConfirm={async () => { const c = confirm; setConfirm(null); setMergeId(null); await mergeNames(kind, c.from.id, c.to.id); }} />
      <ConfirmDialog open={!!del} onClose={() => setDel(null)} confirmLabel="Delete"
        title={del ? `Delete "${del.name}"?` : ''}
        message={del ? `No row uses "${del.name}", so it only leaves the list.` : ''}
        onConfirm={async () => { const d = del; setDel(null); await deleteName(kind, d.id); }} />
    </>
  );
}

Object.assign(window, { NameManager });
