// address-book.jsx — customer portal: manage saved addresses (add / edit / remove / favourite).
const { useState: useStateAB } = React;

function AddressBookModalForm({ open, onClose, seed, onSave }) {
  const [label, setLabel] = useStateAB("");
  const [company, setCompany] = useStateAB("");
  const [contact, setContact] = useStateAB("");
  const [phone, setPhone] = useStateAB("");
  const [email, setEmail] = useStateAB("");
  const [unit, setUnit] = useStateAB("");
  const [line, setLine] = useStateAB("");
  const [suburb, setSuburb] = useStateAB("");
  const [postcode, setPostcode] = useStateAB("");
  const [fav, setFav] = useStateAB(false);
  React.useEffect(() => {
    if (open) {
      setLabel(seed ? (seed.label || "") : "");
      setCompany(seed ? (seed.company || "") : "");
      setContact(seed ? (seed.contact || "") : "");
      setPhone(seed ? (seed.phone || "") : "");
      setEmail(seed ? (seed.email || "") : "");
      setUnit(seed ? (seed.unit || "") : "");
      setLine(seed ? (seed.line || "") : "");
      setSuburb(seed ? (seed.suburb || "") : "");
      setPostcode(seed ? (seed.postcode || "") : "");
      setFav(seed ? !!seed.fav : false);
    }
  }, [open, seed]);
  const ok = label.trim() && suburb;
  function save() {
    onSave({
      id: seed ? seed.id : "ab" + Date.now(),
      label: label.trim(), name: label.trim(), company: company.trim(),
      contact: contact.trim(), phone: phone.trim(), email: email.trim(),
      unit: unit.trim(), line: line.trim(), suburb, postcode: postcode || window.FX.suburbPostcode(suburb), fav,
      instructions: seed ? (seed.instructions || "") : "",
    });
  }
  return (
    <Modal open={open} onClose={onClose} title={seed ? "Edit address" : "Add address"} width={540}>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <Field label={<span>Label <span style={{ color: "var(--danger)" }}>*</span></span>} hint="How it appears in your address book, e.g. “Warehouse — Mascot”.">
          <TextInput value={label} onChange={setLabel} placeholder="e.g. Sydney warehouse" />
        </Field>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field label="Company (optional)"><TextInput value={company} onChange={setCompany} placeholder="Acme Pty Ltd" /></Field>
          <Field label="Contact name"><TextInput value={contact} onChange={setContact} placeholder="Jane Smith" /></Field>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field label="Phone"><TextInput value={phone} onChange={setPhone} placeholder="+61 4XX XXX XXX" mono /></Field>
          <Field label="Email"><TextInput value={email} onChange={setEmail} placeholder="name@company.com.au" type="email" /></Field>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 2fr", gap: 12 }}>
          <Field label="Unit / level (optional)"><TextInput value={unit} onChange={setUnit} placeholder="Unit 4 / Dock 2" /></Field>
          <Field label="Street address"><TextInput value={line} onChange={setLine} placeholder="123 George St" /></Field>
        </div>
        <Field label={<span>Suburb or postcode <span style={{ color: "var(--danger)" }}>*</span></span>}>
          <SuburbPostcodeField suburb={suburb} postcode={postcode} onPick={(sub, pc) => { setSuburb(sub); setPostcode(pc); }} />
        </Field>
        <button onClick={() => setFav(!fav)} style={{ display: "flex", alignItems: "center", gap: 10, background: "transparent", border: "none", padding: 0, textAlign: "left", cursor: "pointer" }}>
          <span style={{ width: 38, height: 22, borderRadius: 999, flex: "none", background: fav ? "var(--accent)" : "var(--bg-mist-2)", position: "relative", transition: "all 160ms ease" }}>
            <span style={{ position: "absolute", top: 2, left: fav ? 18 : 2, width: 18, height: 18, borderRadius: "50%", background: "#fff", transition: "all 160ms ease" }} />
          </span>
          <span style={{ fontSize: 13.5, color: "var(--fg-strong)", fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name="star" size={14} color={fav ? "var(--accent)" : "var(--fg-faint)"} /> Favourite — shows first when picking an address</span>
        </button>
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 4 }}>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="primary" icon="check" disabled={!ok} onClick={save}>{seed ? "Save address" : "Add to address book"}</Button>
        </div>
      </div>
    </Modal>
  );
}

function AddressBookPage({ addressBook, onSave, onRemove, nav }) {
  const [q, setQ] = useStateAB("");
  const [modal, setModal] = useStateAB(false);
  const [seed, setSeed] = useStateAB(null);
  const [confirmRm, setConfirmRm] = useStateAB(null);

  const list = [...addressBook].sort((a, b) => (b.fav ? 1 : 0) - (a.fav ? 1 : 0));
  const filtered = q.trim()
    ? list.filter(a => [a.label, a.company, a.line, a.suburb, a.postcode, a.contact].join(" ").toLowerCase().includes(q.trim().toLowerCase()))
    : list;

  return (
    <div className="fade-up">
      <PageHeader eyebrow="Manage" title="Address book" sub="Your saved pickup and delivery addresses — available whenever you book."
        actions={<Button variant="primary" icon="plus" onClick={() => { setSeed(null); setModal(true); }}>Add address</Button>} />

      <div style={{ position: "relative", maxWidth: 380, marginBottom: 16 }}>
        <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--fg-mute)" }}><Icon name="search" size={15} /></span>
        <TextInput value={q} onChange={setQ} placeholder="Search label, suburb or contact…" style={{ paddingLeft: 37 }} />
      </div>

      {filtered.length === 0 ? (
        <Card pad={48} style={{ textAlign: "center", borderStyle: "dashed", background: "var(--bg-mist)" }}>
          <div style={{ width: 54, height: 54, borderRadius: "50%", background: "var(--surface)", display: "inline-flex", alignItems: "center", justifyContent: "center", margin: "0 auto 12px", color: "var(--fg-faint)" }}><Icon name="building" size={24} /></div>
          <div style={{ fontSize: 15, fontWeight: 600, color: "var(--fg-strong)" }}>{q.trim() ? "No addresses match your search" : "No saved addresses yet"}</div>
          <div style={{ fontSize: 13.5, color: "var(--fg-mute)", marginTop: 5 }}>{q.trim() ? "Try a different label, suburb or contact." : "Add your regular pickup and delivery locations to book faster."}</div>
        </Card>
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(310px, 1fr))", gap: 14 }}>
          {filtered.map(a => (
            <Card key={a.id} pad={0} style={{ overflow: "hidden", display: "flex", flexDirection: "column" }}>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 12, padding: "16px 16px 12px" }}>
                <span style={{ width: 40, height: 40, borderRadius: 10, flex: "none", background: "var(--brand-soft)", color: "var(--brand)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Icon name="building" size={19} /></span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14.5, fontWeight: 700, color: "var(--fg-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.label}</div>
                  {a.company && <div style={{ fontSize: 12, color: "var(--fg-mute)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.company}</div>}
                </div>
                <button onClick={() => onSave({ ...a, fav: !a.fav })} title={a.fav ? "Remove from favourites" : "Mark as favourite"} style={{ flex: "none", width: 30, height: 30, borderRadius: 8, border: "1px solid " + (a.fav ? "var(--accent)" : "var(--border)"), background: a.fav ? "var(--accent-soft)" : "var(--surface)", display: "inline-flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}>
                  <Icon name="star" size={15} color={a.fav ? "var(--accent)" : "var(--fg-faint)"} />
                </button>
              </div>
              <div style={{ padding: "0 16px 13px", display: "flex", flexDirection: "column", gap: 5 }}>
                <span style={{ display: "inline-flex", alignItems: "flex-start", gap: 8, fontSize: 12.5, color: "var(--fg-body)" }}>
                  <Icon name="map-pin" size={13} color="var(--fg-mute)" style={{ flex: "none", marginTop: 2 }} />
                  <span style={{ minWidth: 0 }}>{[a.unit, a.line].filter(Boolean).join(" · ")}{(a.unit || a.line) ? ", " : ""}{a.suburb} <span style={{ fontFamily: "var(--font-mono)", color: "var(--fg-mute)" }}>{a.postcode}</span></span>
                </span>
                {(a.contact || a.phone) && (
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 8, fontSize: 12.5, color: "var(--fg-body)" }}>
                    <Icon name="user" size={13} color="var(--fg-mute)" style={{ flex: "none" }} />
                    <span style={{ minWidth: 0, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.contact}{a.contact && a.phone ? " · " : ""}<span style={{ fontFamily: "var(--font-mono)" }}>{a.phone}</span></span>
                  </span>
                )}
              </div>
              <div style={{ display: "flex", gap: 8, padding: "11px 16px", marginTop: "auto", borderTop: "1px solid var(--border)", background: "var(--bg-mist)" }}>
                <Button variant="secondary" size="sm" icon="pencil" onClick={() => { setSeed(a); setModal(true); }}>Edit</Button>
                <Button variant="secondary" size="sm" icon="plus" onClick={() => nav && nav("book")}>Book from here</Button>
                <button onClick={() => setConfirmRm(a)} title="Remove address" style={{ marginLeft: "auto", width: 32, height: 32, borderRadius: 8, border: "1px solid var(--border)", background: "var(--surface)", color: "var(--fg-mute)", display: "inline-flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}><Icon name="trash-2" size={15} /></button>
              </div>
            </Card>
          ))}
        </div>
      )}

      <AddressBookModalForm open={modal} onClose={() => setModal(false)} seed={seed} onSave={a => { onSave(a); setModal(false); }} />

      <Modal open={!!confirmRm} onClose={() => setConfirmRm(null)} title="Remove address" width={440}>
        {confirmRm && (
          <div>
            <p style={{ margin: "0 0 16px", fontSize: 14, color: "var(--fg-body)", lineHeight: 1.55 }}>Remove <strong style={{ color: "var(--fg-strong)" }}>{confirmRm.label}</strong> from your address book? Existing bookings aren't affected.</p>
            <div style={{ display: "flex", justifyContent: "flex-end", gap: 10 }}>
              <Button variant="ghost" onClick={() => setConfirmRm(null)}>Cancel</Button>
              <Button variant="dark" icon="trash-2" style={{ background: "var(--danger)" }} onClick={() => { onRemove(confirmRm.id); setConfirmRm(null); }}>Remove</Button>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
}

Object.assign(window, { AddressBookPage });
