// cloud/clients.jsx — Modal de sélection / autocomplete client

const { useState: useStateCli, useEffect: useEffectCli, useMemo: useMemoCli, useRef: useRefCli } = React;

// ═══════════════════════════════════════════════════════════════════
// ClientPickerButton — bouton + modale qui charge tous les clients
// puis filtre côté client. Sur sélection : appelle onPick(client).
// ═══════════════════════════════════════════════════════════════════
function ClientPickerButton({ onPick }) {
  const [open, setOpen] = useStateCli(false);
  return (
    <>
      <button
        type="button"
        style={cliCss.openBtn}
        onClick={() => setOpen(true)}
        title="Charger un client existant"
      >
        <Icon name="users" size={13}/>
        <span>Charger un client existant</span>
      </button>
      {open && <ClientPickerModal onClose={() => setOpen(false)} onPick={(c) => { onPick(c); setOpen(false); }}/>}
    </>
  );
}

function ClientPickerModal({ onClose, onPick }) {
  const [rows, setRows] = useStateCli([]);
  const [loading, setLoading] = useStateCli(true);
  const [err, setErr] = useStateCli(null);
  const [q, setQ] = useStateCli("");
  const inputRef = useRefCli(null);

  useEffectCli(() => {
    setLoading(true);
    window.RaycastDB.listClients({ limit: 500 })
      .then((data) => { setRows(data); setLoading(false); })
      .catch((e) => { setErr(e.message || String(e)); setLoading(false); });
    setTimeout(() => inputRef.current?.focus(), 60);

    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const filtered = useMemoCli(() => {
    if (!q.trim()) return rows.slice(0, 50);
    const s = q.toLowerCase();
    return rows.filter(r =>
      (r.name || "").toLowerCase().includes(s) ||
      (r.address_street || "").toLowerCase().includes(s) ||
      (r.address_city || "").toLowerCase().includes(s) ||
      (r.address_postal || "").toLowerCase().includes(s) ||
      (r.phone || "").toLowerCase().includes(s) ||
      (r.email || "").toLowerCase().includes(s)
    ).slice(0, 80);
  }, [rows, q]);

  return (
    <div style={cliCss.backdrop} onClick={onClose}>
      <div style={cliCss.modal} onClick={(e) => e.stopPropagation()}>
        <div style={cliCss.head}>
          <div>
            <h3 style={cliCss.title}>Répertoire clients</h3>
            <div style={cliCss.sub}>{rows.length} client{rows.length > 1 ? "s" : ""} dans la base</div>
          </div>
          <button style={cliCss.closeBtn} onClick={onClose}><Icon name="x" size={16}/></button>
        </div>

        <div style={cliCss.searchWrap}>
          <Icon name="search" size={14}/>
          <input
            ref={inputRef}
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="Nom, rue, ville, code postal, téléphone…"
            style={cliCss.search}
          />
        </div>

        <div style={cliCss.list}>
          {loading ? (
            <div style={cliCss.note}>Chargement…</div>
          ) : err ? (
            <div style={{...cliCss.note, color: "#991b1b"}}>Erreur : {err}</div>
          ) : filtered.length === 0 ? (
            <div style={cliCss.note}>
              {q ? "Aucun client trouvé." : "Aucun client encore. Crées-en un en sauvegardant une soumission."}
            </div>
          ) : filtered.map(c => (
            <button
              key={c.id}
              style={cliCss.row}
              onClick={() => onPick(c)}
              type="button"
            >
              <div style={cliCss.rowMain}>
                <div style={cliCss.rowName}>{c.name}</div>
                <div style={cliCss.rowAddr}>
                  {[c.address_civic, c.address_street, c.address_city, c.address_postal].filter(Boolean).join(" · ") || "—"}
                </div>
              </div>
              <div style={cliCss.rowMeta}>
                {c.phone && <span>{c.phone}</span>}
                {c.email && <span style={cliCss.email}>{c.email}</span>}
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

const cliCss = {
  openBtn: {
    display: "inline-flex", alignItems: "center", gap: 6,
    padding: "6px 12px",
    background: "#eff6ff", color: "#1e40af",
    border: "1px solid #bfdbfe", borderRadius: 6,
    fontSize: 12, fontWeight: 600, cursor: "pointer",
    fontFamily: "inherit"
  },
  backdrop: {
    position: "fixed", inset: 0, background: "rgba(15,23,42,0.45)",
    display: "flex", alignItems: "center", justifyContent: "center",
    zIndex: 9000, padding: 20
  },
  modal: {
    width: "100%", maxWidth: 640, maxHeight: "80vh",
    background: "#fff", borderRadius: 12,
    boxShadow: "0 30px 80px -20px rgba(0,0,0,0.4)",
    display: "flex", flexDirection: "column",
    overflow: "hidden", fontFamily: "'Inter', system-ui, sans-serif"
  },
  head: {
    padding: "16px 20px", borderBottom: "1px solid #e2e8f0",
    display: "flex", justifyContent: "space-between", alignItems: "flex-start"
  },
  title: { margin: 0, fontSize: 16, fontWeight: 700, color: "#0f172a" },
  sub:   { fontSize: 12, color: "#64748b", marginTop: 2 },
  closeBtn: {
    background: "transparent", border: "none", padding: 6,
    color: "#64748b", cursor: "pointer", borderRadius: 4
  },
  searchWrap: {
    margin: "12px 20px 6px",
    display: "flex", alignItems: "center", gap: 8,
    padding: "0 12px", background: "#f8fafc",
    border: "1px solid #cbd5e1", borderRadius: 8, color: "#94a3b8"
  },
  search: {
    flex: 1, padding: "9px 0", border: "none", outline: "none",
    fontSize: 13, fontFamily: "inherit", background: "transparent", color: "#0f172a"
  },
  list: {
    flex: 1, overflowY: "auto", padding: "6px 10px 14px",
    display: "flex", flexDirection: "column", gap: 2
  },
  note: { padding: 30, textAlign: "center", color: "#94a3b8", fontSize: 13 },
  row: {
    display: "flex", justifyContent: "space-between", alignItems: "center",
    gap: 12, padding: "10px 12px",
    background: "transparent", border: "none", borderRadius: 6,
    cursor: "pointer", textAlign: "left", fontFamily: "inherit", color: "#0f172a",
    transition: "background 0.1s"
  },
  rowMain:  { flex: 1, minWidth: 0 },
  rowName:  { fontSize: 13.5, fontWeight: 600 },
  rowAddr:  { fontSize: 11.5, color: "#64748b", marginTop: 2 },
  rowMeta:  { display: "flex", flexDirection: "column", gap: 2, fontSize: 11, color: "#64748b", textAlign: "right" },
  email: { color: "#1a6fc4" }
};

// Hover effect via inline style ne fonctionne pas — fallback CSS injecté
if (!document.getElementById("raycast-clients-css")) {
  const s = document.createElement("style");
  s.id = "raycast-clients-css";
  s.textContent = `
    [data-cli-row]:hover { background: #f1f5f9 !important; }
    [data-cli-row]:active { background: #e2e8f0 !important; }
  `;
  document.head.appendChild(s);
}

Object.assign(window, { ClientPickerButton });
