// ====== Customers page ======
const tierColor = (t) => t === "VIP" ? "var(--gold-600)" : t === "Regular" ? "var(--green-700)" : "var(--ink-500)";
const tierBg = (t) => t === "VIP" ? "rgba(200,162,92,0.18)" : t === "Regular" ? "rgba(53,97,72,0.10)" : "rgba(125,132,114,0.10)";
const dateInputValue = (value) => value ? new Date(value).toISOString().slice(0, 10) : "";
const dateFromInput = (value) => value ? new Date(`${value}T12:00:00`).toISOString() : null;

// Edit / create modal for a guest
const CustomerEditModal = ({ customer, isNew, menuItems, onClose, onSave, onDelete }) => {
	  const [draft, setDraft] = React.useState(() => customer || {
	    id: `c${Date.now()}`, name: "", phone: "", email: "", tier: "New",
	    joined: new Date().toLocaleString("en-US", { month: "short", year: "numeric" }),
	    visits: 0, spent: 0, last: "—", last_visit_at: null, favorite_menu_item_id: null, fav: "—", note: "",
	  });
  const [saving, setSaving] = React.useState(false);
  const [dialog, setDialog] = React.useState(null);
  React.useEffect(() => {
    if (customer) setDraft(customer);
    setSaving(false);
  }, [customer]);
  const set = (patch) => setDraft({ ...draft, ...patch });

  return (
    <React.Fragment>
    <div className="modal-scrim open" onClick={onClose}>
      <div className="modal edit-modal" onClick={e => e.stopPropagation()}>
        <div className="modal-left edit-pane">
          <div className="modal-head">
            <div>
              <div style={{ fontFamily: "var(--font-script)", color: "var(--gold-600)", fontSize: 18, lineHeight: 1 }}>
                {isNew ? "New guest" : "Editing"}
              </div>
              <h2>{draft.name || "Untitled guest"}</h2>
              <div className="sub">
                {isNew ? "Add a new guest to the book" : <>Since {draft.joined} · {draft.visits} visits</>}
              </div>
            </div>
            <div className="row" style={{ gap: 8 }}>
              <span className="tier-pill" style={{ background: tierBg(draft.tier), color: tierColor(draft.tier) }}>
                {draft.tier}
              </span>
              <button className="icon-btn" onClick={onClose}><Ic name="x" /></button>
            </div>
          </div>

          <div className="modal-body" style={{ display: "flex", flexDirection: "column", gap: 18, minWidth: 0 }}>
            <div style={{ display: "grid", gridTemplateColumns: "120px 1fr", gap: 16, minWidth: 0 }}>
              <div style={{
                aspectRatio: "1/1",
                borderRadius: "var(--r-lg)",
                background: draft.tier === "VIP" ? "linear-gradient(135deg, var(--gold-500), var(--gold-600))" : "linear-gradient(135deg, var(--green-700), var(--green-800))",
                color: draft.tier === "VIP" ? "var(--green-900)" : "var(--gold-500)",
                display: "grid", placeItems: "center",
                fontFamily: "var(--font-display)",
                fontSize: 40, fontWeight: 500,
                border: "1px solid var(--line-gold)",
              }}>
                {(draft.name || "?").split(" ").map(n => n[0]).filter(Boolean).slice(0, 2).join("") || "?"}
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                <div className="field">
                  <label>Full name</label>
                  <input value={draft.name} onChange={e => set({ name: e.target.value })} placeholder="e.g. Amelia Chen" />
                </div>
                <div className="field">
                  <label>Tier</label>
                  <div className="seg" style={{ width: "100%" }}>
                    {["New", "Regular", "VIP"].map(t => (
                      <button key={t} className={draft.tier === t ? "on" : ""} onClick={() => set({ tier: t })}>{t}</button>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            <div className="edit-divider"><span>Contact</span></div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
              <div className="field">
                <label>Phone</label>
                <input value={draft.phone} onChange={e => set({ phone: formatPhone(e.target.value) })} placeholder="(415) 555-…" />
              </div>
              <div className="field">
                <label>Email</label>
                <input value={draft.email} onChange={e => set({ email: e.target.value })} placeholder="name@example.com" />
              </div>
            </div>

            <div className="edit-divider"><span>Preferences</span></div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
              <div className="field">
                <label>Favorite drink</label>
	                <select value={draft.favorite_menu_item_id || ""} onChange={e => {
	                  const item = (menuItems || []).find(m => m.id === e.target.value);
	                  set({ favorite_menu_item_id: item?.id || null, fav: item?.name || "—", favName: item?.name || "" });
	                }}>
	                  <option value="">— None —</option>
	                  {(menuItems || []).map(m => <option key={m.id} value={m.id}>{m.name}</option>)}
	                </select>
              </div>
	              <div className="field">
	                <label>Visits</label>
	                <input type="number" min="0" value={draft.visits} readOnly />
	              </div>
	            </div>

	            <div className="edit-divider"><span>Customer metrics</span></div>
	            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
	              <div className="field">
	                <label>Total spent</label>
	                <input type="number" min="0" step="0.01" value={draft.spent} readOnly />
	              </div>
	              <div className="field">
	                <label>Last visit</label>
	                <input type="date" value={dateInputValue(draft.last_visit_at)} readOnly />
	              </div>
	            </div>

	            <div className="field">
              <label>Barista note</label>
              <textarea
                rows={3}
                placeholder="e.g. Always 50% sugar, less ice"
                value={draft.note || ""}
                onChange={e => set({ note: e.target.value })}
                style={{ resize: "vertical" }}
              />
            </div>
          </div>

          <div className="modal-foot">
            {!isNew && (
              <button className="btn btn-ghost" style={{ color: "var(--rose-500)" }} onClick={() => setDialog({ title: "Delete guest?", message: `Remove "${draft.name}" from the guest book? This cannot be undone.`, confirmLabel: "Delete", onConfirm: () => onDelete(draft.id) })}>
                <Ic name="trash" size={14} /> Delete
              </button>
            )}
            <button className="btn btn-ghost" onClick={onClose} style={{ marginLeft: "auto" }}>Cancel</button>
            <button className="btn btn-primary" disabled={saving || !draft.name} onClick={async () => { setSaving(true); await onSave(draft); setSaving(false); }}>
              {saving ? <><span className="btn-spinner" /> Saving…</> : <><Ic name="check" size={14} /> {isNew ? "Add customer" : "Save"}</>}
            </button>
          </div>
        </div>
      </div>
    </div>
    {dialog && <ConfirmDialog title={dialog.title} message={dialog.message} confirmLabel={dialog.confirmLabel} onConfirm={() => { setDialog(null); dialog.onConfirm(); }} onCancel={() => setDialog(null)} />}
    </React.Fragment>
  );
};

const Customers = () => {
  const [tier, setTier] = React.useState("All");
  const [query, setQuery] = React.useState("");
  const [selectedId, setSelectedId] = React.useState(null);
  const [sort, setSort] = React.useState("recent");
  const [items, setItems] = React.useState([]);
  const [menuItems, setMenuItems] = React.useState([]);
  const [editing, setEditing] = React.useState(null); // {customer, isNew} | null
  const [backendReady, setBackendReady] = React.useState(false);
  const [backendError, setBackendError] = React.useState("");
  const [isLoading, setIsLoading] = React.useState(false);
  const [isSearching, setIsSearching] = React.useState(false);
  const searchSeq = React.useRef(0);
  const didInitSearch = React.useRef(false);

  const loadCustomers = React.useCallback(async () => {
    const backend = window.TeaGangBackend;
    if (!backend?.enabled) return;
    const seq = ++searchSeq.current;
    setIsLoading(true);
    try {
      const [customers, menu] = await Promise.all([
        backend.searchCustomers?.({ query: "", limit: 50 }) || backend.fetchCustomers(),
        backend.fetchMenu().catch(() => ({ items: [] })),
      ]);
      if (seq !== searchSeq.current) return;
      setItems(customers);
      setMenuItems(menu.items || []);
      setBackendReady(true);
      setBackendError("");
    } catch (error) {
      if (seq !== searchSeq.current) return;
      console.error("Customers backend unavailable.", error);
      setItems([]);
      setBackendReady(false);
      setBackendError(error.message || "Could not load customers.");
    } finally {
      if (seq === searchSeq.current) setIsLoading(false);
    }
  }, []);

  React.useEffect(() => { loadCustomers(); }, [loadCustomers]);

  React.useEffect(() => {
    const backend = window.TeaGangBackend;
    if (!backend?.enabled || !backend.searchCustomers) return;
    if (!didInitSearch.current) {
      didInitSearch.current = true;
      return;
    }
    const term = query.trim();
    const seq = ++searchSeq.current;
    setIsSearching(Boolean(term));
    const timer = window.setTimeout(async () => {
      try {
        const customers = await backend.searchCustomers({ query: term, limit: 50 });
        if (seq !== searchSeq.current) return;
        setItems(customers);
        setBackendReady(true);
        setBackendError("");
      } catch (error) {
        if (seq !== searchSeq.current) return;
        console.error("Could not search customers.", error);
        setBackendError(error.message || "Could not search customers.");
      } finally {
        if (seq === searchSeq.current) setIsSearching(false);
      }
    }, 300);
    return () => window.clearTimeout(timer);
  }, [query]);

  const q = normalizeVi(query.trim());
  const filtered = items
    .filter(c => tier === "All" || c.tier === tier)
    .filter(c => !q || normalizeVi(c.name).includes(q) || c.phone.includes(q) || normalizeVi(c.email).includes(q))
    .sort((a, b) => {
      if (sort === "spent") return b.spent - a.spent;
      if (sort === "visits") return b.visits - a.visits;
      return 0;
    });

  const total = items.length;
  const vip = items.filter(c => c.tier === "VIP").length;
  const newThisMonth = items.filter(c => c.tier === "New").length;
  const avgVisits = +(items.reduce((s, c) => s + c.visits, 0) / Math.max(1, items.length)).toFixed(1);

  const tiers = ["All", "VIP", "Regular", "New"];
  const topThree = [...items].sort((a, b) => b.spent - a.spent).slice(0, 3);
  const selected = items.find(c => c.id === selectedId);

  const saveCustomer = async (draft) => {
    try {
      const saved = await window.TeaGangBackend?.saveCustomer?.(draft);
      setItems(prev => {
        const next = saved || draft;
        const exists = prev.some(c => c.id === draft.id);
        return exists ? prev.map(c => c.id === draft.id ? { ...c, ...next } : c) : [next, ...prev];
      });
      if (backendReady) await loadCustomers();
    } catch (error) {
      console.error("Could not save customer.", error);
      setBackendError(error.message || "Could not save customer.");
      return;
    }
    setEditing(null);
  };
  const deleteCustomer = async (id) => {
    try {
      await window.TeaGangBackend?.deleteCustomer?.(id);
    } catch (error) {
      console.error("Could not delete customer from backend.", error);
      setBackendError(error.message || "Could not delete customer.");
      return;
    }
    setItems(prev => prev.filter(c => c.id !== id));
    setEditing(null);
    setSelectedId(null);
  };

  return (
    <div>
      <div className="page-head">
        <div>
          <div className="page-eyebrow">Our regulars</div>
          <h1 className="page-title">Customers</h1>
          <div className="page-meta" style={{ marginTop: 8 }}>
            <span className="ornament"></span>
            <span><b style={{ color: "var(--green-700)" }}>{total}</b> guests · <b style={{ color: "var(--gold-700)" }}>{vip}</b> VIP · <b>{newThisMonth}</b> new this month · avg <b>{avgVisits}</b> visits</span>
          </div>
          {backendError && (
            <div style={{ marginTop: 10, color: "var(--rose-500)", fontSize: 12.5 }}>
              {backendError}
            </div>
          )}
        </div>
        <div className="row" style={{ gap: 10 }}>
          <div className="search" style={{ width: 240, margin: 0 }}>
            <Ic name="search" size={14} />
            <input placeholder="Name, phone, email…" value={query} onChange={e => setQuery(e.target.value)} />
            {isSearching && <span className="search-spin" />}
          </div>
          <button className="btn btn-ghost"><Ic name="arrow-down" size={14} /> Export</button>
          <button className="btn btn-gold" onClick={() => setEditing({ customer: null, isNew: true })}><Ic name="plus" /> Add customer</button>
        </div>
      </div>


      {/* Filters */}
      <div className="card">
        <div className="card-head">
          <div>
            <div className="card-title">All guests</div>
            <div className="card-sub">{isLoading ? "Loading guests..." : `${filtered.length} match${filtered.length !== 1 ? "es" : ""}`}</div>
          </div>
          <div className="row" style={{ gap: 8 }}>
            <div className="menu-toolbar" style={{ margin: 0 }}>
              {tiers.map(t => (
                <button key={t} className={`chip ${tier === t ? "active" : ""}`} onClick={() => setTier(t)}>
                  {t}
                  {t !== "All" && <span className="chip-count">{items.filter(c => c.tier === t).length}</span>}
                </button>
              ))}
            </div>
            <div className="row" style={{ background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: "var(--r-md)", padding: 3 }}>
              {[
                { id: "recent", label: "Recent" },
                { id: "spent",  label: "Spend" },
                { id: "visits", label: "Visits" },
              ].map(s => (
                <button
                  key={s.id}
                  onClick={() => setSort(s.id)}
                  style={{
                    padding: "5px 11px", fontSize: 12, borderRadius: 5,
                    background: sort === s.id ? "var(--green-700)" : "transparent",
                    color: sort === s.id ? "var(--cream-50)" : "var(--ink-700)",
                  }}
                >{s.label}</button>
              ))}
            </div>
          </div>
        </div>

        <div className="card-divider" />
        <div style={{ overflowX: "auto" }}>
          <table className="table">
            <thead>
              <tr>
                <th>Guest</th>
                <th>Contact</th>
                <th>Favorite</th>
                <th className="num" style={{ textAlign: "right" }}>Visits</th>
                <th className="num" style={{ textAlign: "right" }}>Spent</th>
                <th>Last visit</th>
                <th>Tier</th>
                <th style={{ width: 50 }}></th>
              </tr>
            </thead>
            <tbody>
              {isLoading && (
                <tr>
                  <td colSpan="8">
                    <div className="customer-empty-state">Loading recent guests...</div>
                  </td>
                </tr>
              )}
              {!isLoading && filtered.length === 0 && (
                <tr>
                  <td colSpan="8">
                    <div className="customer-empty-state">
                      {query.trim() ? "No matching guest found." : "No recent guests found."}
                    </div>
                  </td>
                </tr>
              )}
              {filtered.map(c => (
                <tr key={c.id} style={{ cursor: "pointer" }} onClick={() => setSelectedId(c.id)}>
                  <td>
                    <div className="row" style={{ gap: 10 }}>
                      <div className="avatar" style={{ width: 34, height: 34, fontSize: 12, background: c.tier === "VIP" ? "var(--gold-500)" : "var(--cream-200)", color: c.tier === "VIP" ? "var(--green-900)" : "var(--green-700)" }}>
                        {c.name.split(" ").map(n => n[0]).join("")}
                      </div>
                      <div>
                        <div style={{ fontFamily: "var(--font-display)", fontSize: 15, color: "var(--green-800)" }}>{c.name}</div>
                        <div className="muted" style={{ fontSize: 11 }}>Since {c.joined}</div>
                      </div>
                    </div>
                  </td>
                  <td>
                    <div className="mono" style={{ fontSize: 12 }}>{c.phone}</div>
                    <div className="muted" style={{ fontSize: 11 }}>{c.email}</div>
                  </td>
                  <td>
                    <span style={{ fontSize: 12.5 }}>{c.fav}</span>
                  </td>
                  <td className="num" style={{ textAlign: "right" }}>{c.visits}</td>
                  <td className="num" style={{ textAlign: "right" }}>${c.spent.toFixed(2)}</td>
                  <td>
                    <span className="muted" style={{ fontSize: 12 }}>{c.last}</span>
                  </td>
                  <td>
                    <span className="tier-pill" style={{ background: tierBg(c.tier), color: tierColor(c.tier) }}>{c.tier}</span>
                  </td>
                  <td>
                    <button className="icon-btn" style={{ width: 30, height: 30 }} onClick={(e) => { e.stopPropagation(); setSelectedId(c.id); }}>
                      <Ic name="arrow-right" size={14} />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Guest detail drawer */}
      <div className={`drawer-scrim ${selected ? "open" : ""}`} onClick={() => setSelectedId(null)} />
      <div className={`drawer ${selected ? "open" : ""}`}>
        {selected && (
          <React.Fragment>
            <div className="drawer-head">
              <div className="row" style={{ gap: 14 }}>
                <div className="avatar" style={{ width: 54, height: 54, fontSize: 20, background: selected.tier === "VIP" ? "var(--gold-500)" : "var(--green-700)", color: selected.tier === "VIP" ? "var(--green-900)" : "var(--gold-500)" }}>
                  {selected.name.split(" ").map(n => n[0]).join("")}
                </div>
                <div>
                  <div style={{ fontFamily: "var(--font-display)", fontSize: 24, color: "var(--green-800)", lineHeight: 1.1 }}>{selected.name}</div>
                  <div className="row" style={{ gap: 8, marginTop: 6 }}>
                    <span className="tier-pill" style={{ background: tierBg(selected.tier), color: tierColor(selected.tier) }}>{selected.tier}</span>
                    <span className="muted" style={{ fontSize: 11.5 }}>Since {selected.joined}</span>
                  </div>
                </div>
              </div>
              <div className="row" style={{ gap: 6 }}>
                <button className="icon-btn" onClick={() => { setEditing({ customer: selected, isNew: false }); setSelectedId(null); }} title="Edit guest">
                  <Ic name="edit" size={14} />
                </button>
                <button className="icon-btn" onClick={() => setSelectedId(null)}><Ic name="x" /></button>
              </div>
            </div>

            <div className="drawer-body">
              {/* Quick stats */}
              <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10, marginBottom: 18 }}>
                <div className="ministat">
                  <div className="ministat-val">{selected.visits}</div>
                  <div className="ministat-lab">Visits</div>
                </div>
                <div className="ministat">
                  <div className="ministat-val">${selected.spent.toFixed(0)}</div>
                  <div className="ministat-lab">Total spent</div>
                </div>
                <div className="ministat">
                  <div className="ministat-val">${(selected.spent / Math.max(1, selected.visits)).toFixed(2)}</div>
                  <div className="ministat-lab">Avg ticket</div>
                </div>
              </div>

              <div style={{ fontSize: 10.5, letterSpacing: ".18em", textTransform: "uppercase", color: "var(--ink-500)", marginBottom: 8 }}>
                Contact
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 10, padding: "12px 14px", background: "var(--cream-100)", borderRadius: "var(--r-md)", marginBottom: 18 }}>
                <div className="spread"><span className="muted" style={{ fontSize: 12 }}>Phone</span><span className="mono" style={{ fontSize: 13 }}>{selected.phone}</span></div>
                <div className="spread"><span className="muted" style={{ fontSize: 12 }}>Email</span><span style={{ fontSize: 12.5 }}>{selected.email}</span></div>
                <div className="spread"><span className="muted" style={{ fontSize: 12 }}>Last visit</span><span style={{ fontSize: 12.5 }}>{selected.last}</span></div>
              </div>

              <div style={{ fontSize: 10.5, letterSpacing: ".18em", textTransform: "uppercase", color: "var(--ink-500)", marginBottom: 8 }}>
                Favorite drink
              </div>
              <div className="row" style={{ gap: 12, padding: 12, background: "var(--cream-50)", borderRadius: "var(--r-md)", border: "1px solid var(--line-soft)", marginBottom: 18 }}>
                <div className="detail-thumb" style={{ width: 44, height: 44, fontSize: 20 }}>
                  {menuItems.find(m => m.id === selected.favorite_menu_item_id)?.glyph || "茶"}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: "var(--font-display)", fontSize: 17, color: "var(--green-800)" }}>{selected.fav}</div>
                  <div className="muted" style={{ fontSize: 11.5 }}>Ordered {Math.round(selected.visits * 0.6)} times</div>
                </div>
              </div>

              {selected.note && (
                <React.Fragment>
                  <div style={{ fontSize: 10.5, letterSpacing: ".18em", textTransform: "uppercase", color: "var(--ink-500)", marginBottom: 8 }}>
                    Barista note
                  </div>
                  <div style={{ padding: 12, background: "var(--cream-100)", borderRadius: "var(--r-md)", borderLeft: "3px solid var(--gold-500)", fontStyle: "italic", fontSize: 13, color: "var(--ink-700)" }}>
                    {selected.note}
                  </div>
                </React.Fragment>
              )}
            </div>

            <div className="drawer-foot">
              <button className="btn btn-ghost" style={{ flex: 1 }}><Ic name="phone" size={14} /> Call</button>
              <button className="btn btn-primary" style={{ flex: 2 }}>
                <Ic name="plus" size={14} /> Start order
              </button>
            </div>
          </React.Fragment>
        )}
      </div>
      {editing && (
        <CustomerEditModal
          customer={editing.customer}
          isNew={editing.isNew}
          menuItems={menuItems}
          onClose={() => setEditing(null)}
          onSave={saveCustomer}
          onDelete={deleteCustomer}
        />
      )}
    </div>
  );
};

window.Customers = Customers;
