/* contacts.jsx — записная книжка: список контактов, поиск, карточка с историей. */

function ContactsScreen({ onOpenNote }) {
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [q, setQ] = React.useState("");
  const [openId, setOpenId] = React.useState(null);

  const load = React.useCallback(async () => {
    setLoading(true);
    setItems(await api.getContacts({ q: q || undefined }));
    setLoading(false);
  }, [q]);
  React.useEffect(() => { const t = setTimeout(load, 200); return () => clearTimeout(t); }, [q]);

  return (
    <div>
      <ScreenHead title="Контакты" sub="Кто звонил и о чём — собирается автоматически из заметок с телефоном" />

      <div className="relative mb-4">
        <Icon name="search" size={18} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-[var(--muted)]" />
        <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Поиск по имени, телефону, ЖК…"
          className="w-full h-11 rounded-xl border border-[var(--border)] bg-[var(--surface)] pl-10 pr-3 text-sm text-[var(--text)] outline-none focus:border-[var(--accent)] transition placeholder:text-[var(--muted)]" />
      </div>

      {loading ? (
        <div className="grid gap-3">{[0, 1, 2].map((i) => <div key={i} className="sk h-20 rounded-2xl" />)}</div>
      ) : items.length === 0 ? (
        <EmptyState icon="user" title={q ? "Ничего не нашлось" : "Контактов пока нет"}
          sub={q ? "Измени запрос." : "Напиши заметку с телефоном — например «звонил +7 916 … Владимир по ремонту в ЖК …» — и контакт появится здесь."} />
      ) : (
        <div className="grid gap-3">
          {items.map((c, i) => <ContactRow key={c.id} c={c} index={i} onOpen={() => setOpenId(c.id)} />)}
        </div>
      )}

      <ContactModal contactId={openId} open={!!openId} onClose={() => setOpenId(null)} onChanged={load} onOpenNote={onOpenNote} />
    </div>
  );
}

function ContactRow({ c, index = 0, onOpen }) {
  const initials = (c.name || c.phone || "?").trim().slice(0, 1).toUpperCase();
  return (
    <button onClick={onOpen} style={{ animationDelay: `${Math.min(index, 10) * 30}ms` }}
      className="card-in text-left w-full rounded-2xl border border-[var(--border)] bg-[var(--surface)] p-4 hover:border-[var(--border-strong)] transition">
      <div className="flex items-center gap-3">
        <span className="grid place-items-center w-10 h-10 rounded-full bg-[var(--accent-weak)] text-[var(--accent)] font-bold shrink-0">{initials}</span>
        <div className="min-w-0 flex-1">
          <div className="text-[15px] font-bold text-[var(--text)] truncate">{c.name || c.phone}</div>
          <div className="text-[13px] text-[var(--muted)] truncate mono">{c.phone}{c.address ? " · " + c.address : ""}</div>
        </div>
        <Icon name="chevron" size={16} className="text-[var(--muted)] shrink-0" />
      </div>
      {c.note && <p className="mt-2 text-[13px] text-[var(--muted)] line-clamp-2">{c.note}</p>}
    </button>
  );
}

function ContactModal({ contactId, open, onClose, onChanged, onOpenNote }) {
  const [data, setData] = React.useState(null);
  const [form, setForm] = React.useState({});
  const [busy, setBusy] = React.useState(false);
  const [confirmDel, setConfirmDel] = React.useState(false);

  React.useEffect(() => {
    if (open && contactId) {
      setData(null); setConfirmDel(false);
      api.getContact(contactId).then((d) => { setData(d); setForm({ name: d.name, address: d.address, social: d.social, note: d.note, phone: d.phone }); });
    }
  }, [open, contactId]);

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const save = async () => { setBusy(true); await api.updateContact(contactId, form); setBusy(false); onChanged && onChanged(); onClose(); };
  const del = async () => { setBusy(true); await api.deleteContact(contactId); setBusy(false); onChanged && onChanged(); onClose(); };

  return (
    <Modal open={open} onClose={onClose}>
      <div className="sticky top-0 z-10 flex items-center gap-2.5 px-5 sm:px-6 pt-5 pb-3 bg-[var(--surface)]/95 backdrop-blur border-b border-[var(--border)]">
        <span className="grid place-items-center w-8 h-8 rounded-lg bg-[var(--accent-weak)] text-[var(--accent)]"><Icon name="user" size={17} /></span>
        <h2 className="text-base font-bold text-[var(--text)] truncate">{(form.name || form.phone || "Контакт")}</h2>
        <button onClick={onClose} className="ml-auto p-1.5 rounded-lg text-[var(--muted)] hover:bg-[var(--surface-2)] transition" aria-label="Закрыть"><Icon name="close" size={18} /></button>
      </div>

      {!data ? (
        <div className="grid place-items-center py-16 text-[var(--muted)]"><Spinner size={22} /></div>
      ) : (
        <>
          <div className="px-5 sm:px-6 py-4 space-y-4">
            <div className="grid sm:grid-cols-2 gap-4">
              <Field label="Имя"><input value={form.name || ""} onChange={(e) => set("name", e.target.value)} className="w-full rounded-xl border border-[var(--border)] bg-[var(--surface-2)] px-3.5 h-[42px] text-sm text-[var(--text)] outline-none focus:border-[var(--accent)] transition" /></Field>
              <Field label="Телефон">
                <div className="flex gap-1.5">
                  <input value={form.phone || ""} onChange={(e) => set("phone", e.target.value)} className="mono flex-1 rounded-xl border border-[var(--border)] bg-[var(--surface-2)] px-3.5 h-[42px] text-sm text-[var(--text)] outline-none focus:border-[var(--accent)] transition" />
                  <a href={"tel:" + (form.phone || "")} className="shrink-0 grid place-items-center px-3 rounded-xl border border-[var(--border)] text-[var(--accent)] hover:bg-[var(--surface-2)] transition" title="Позвонить"><Icon name="phone" size={16} /></a>
                </div>
              </Field>
            </div>
            <Field label="ЖК / адрес"><input value={form.address || ""} onChange={(e) => set("address", e.target.value)} className="w-full rounded-xl border border-[var(--border)] bg-[var(--surface-2)] px-3.5 h-[42px] text-sm text-[var(--text)] outline-none focus:border-[var(--accent)] transition" /></Field>
            <Field label="Соцсеть / телеграм">
              <div className="flex gap-1.5">
                <input value={form.social || ""} onChange={(e) => set("social", e.target.value)} placeholder="https://t.me/…" className="flex-1 rounded-xl border border-[var(--border)] bg-[var(--surface-2)] px-3.5 h-[42px] text-sm text-[var(--text)] outline-none focus:border-[var(--accent)] transition" />
                {form.social && /^https?:\/\//i.test(form.social) && <a href={form.social} target="_blank" rel="noreferrer" className="shrink-0 grid place-items-center px-3 rounded-xl border border-[var(--border)] text-[var(--accent)] hover:bg-[var(--surface-2)] transition"><Icon name="external" size={16} /></a>}
              </div>
            </Field>
            <Field label="Примечание"><textarea value={form.note || ""} onChange={(e) => set("note", e.target.value)} rows={2} className="w-full resize-y rounded-xl border border-[var(--border)] bg-[var(--surface-2)] px-3.5 py-2.5 text-sm text-[var(--text)] outline-none focus:border-[var(--accent)] transition" /></Field>

            <div>
              <span className="mb-2 block text-[12px] font-semibold uppercase tracking-wide text-[var(--muted)]">История ({data.history.length})</span>
              <div className="grid gap-2">
                {data.history.length === 0 && <p className="text-[13px] text-[var(--muted)]">Пока нет записей.</p>}
                {data.history.map((n) => (
                  <button key={n.id} onClick={() => { onClose(); onOpenNote && onOpenNote(n); }}
                    className="text-left rounded-xl border border-[var(--border)] bg-[var(--surface-2)] p-3 hover:border-[var(--border-strong)] transition">
                    <div className="flex items-center gap-2 mb-1">
                      <CategoryBadge category={n.category} size="sm" />
                      <span className="ml-auto text-[11px] text-[var(--muted)] whitespace-nowrap">{formatCreated(n.created_at)}</span>
                    </div>
                    <p className="text-[13px] text-[var(--text)] line-clamp-2">{n.summary || n.raw_text}</p>
                  </button>
                ))}
              </div>
            </div>
          </div>

          <div className="sticky bottom-0 flex items-center gap-2 px-5 sm:px-6 py-3.5 bg-[var(--surface)]/95 backdrop-blur border-t border-[var(--border)]">
            {!confirmDel ? (
              <Button variant="danger" onClick={() => setConfirmDel(true)} disabled={busy}><Icon name="trash" size={16} /> Удалить</Button>
            ) : (
              <div className="flex items-center gap-2">
                <Button variant="danger" onClick={del} disabled={busy}>Да, удалить</Button>
                <Button variant="ghost" onClick={() => setConfirmDel(false)}>Отмена</Button>
              </div>
            )}
            <div className="ml-auto flex items-center gap-2">
              <Button variant="ghost" onClick={onClose} disabled={busy}>Закрыть</Button>
              <Button variant="primary" onClick={save} disabled={busy}>{busy ? <Spinner /> : <Icon name="check" size={16} />} Сохранить</Button>
            </div>
          </div>
        </>
      )}
    </Modal>
  );
}

Object.assign(window, { ContactsScreen });
