// address.jsx — inline address form (manual by default) + address-book picker
const { useState: useStateAddr } = React;

function Modal({ open, onClose, title, children, width = 560, top = false }) {
  if (!open) return null;
  return (
    <div onClick={onClose} className="fade-in" style={{
      position: "fixed", inset: 0, background: "rgba(30,22,51,0.42)", zIndex: 200,
      display: "flex", alignItems: top ? "flex-start" : "center", justifyContent: "center", padding: 20, paddingTop: top ? "4.5vh" : 20, backdropFilter: "blur(2px)",
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: "var(--surface)", borderRadius: "var(--r-2xl)", width: "100%", maxWidth: width,
        maxHeight: "86vh", display: "flex", flexDirection: "column", boxShadow: "var(--shadow-pop)",
        animation: "fadeUp 0.25s cubic-bezier(0.2,0.8,0.2,1) both",
      }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "18px 22px", borderBottom: "1px solid var(--border)" }}>
          <div style={{ fontSize: 17, fontWeight: 700, color: "var(--fg-strong)" }}>{title}</div>
          <button onClick={onClose} style={{ background: "var(--bg-mist)", border: "none", borderRadius: "50%", width: 32, height: 32, display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--fg-mute)" }}>
            <Icon name="x" size={17} />
          </button>
        </div>
        <div style={{ padding: 22, overflowY: "auto" }}>{children}</div>
      </div>
    </div>
  );
}

function AddressBookModal({ open, onClose, addressBook, onPick }) {
  const [q, setQ] = useStateAddr("");
  const list = addressBook.filter(a => (a.label + a.suburb + a.name + (a.contact || "")).toLowerCase().includes(q.toLowerCase()));
  const sorted = [...list].sort((a, b) => (b.fav ? 1 : 0) - (a.fav ? 1 : 0));
  return (
    <Modal open={open} onClose={onClose} title="Select from address book" top>
      <div style={{ position: "relative", marginBottom: 14 }}>
        <span style={{ position: "absolute", left: 13, top: "50%", transform: "translateY(-50%)", color: "var(--fg-mute)" }}><Icon name="search" size={16} /></span>
        <TextInput value={q} onChange={setQ} placeholder="Search saved addresses…" style={{ paddingLeft: 38 }} />
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {sorted.map(a => (
          <button key={a.id} onClick={() => onPick(a)} style={{
            display: "flex", alignItems: "center", gap: 13, textAlign: "left", width: "100%",
            background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--r-md)",
            padding: "13px 15px", transition: "all 140ms ease",
          }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = "var(--brand)"; e.currentTarget.style.background = "var(--brand-soft)"; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = "var(--border)"; e.currentTarget.style.background = "var(--surface)"; }}>
            <span style={{ width: 38, height: 38, borderRadius: 10, background: "var(--brand-soft)", color: "var(--brand)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
              <Icon name="building" size={18} />
            </span>
            <span style={{ flex: 1, minWidth: 0 }}>
              <span style={{ display: "flex", alignItems: "center", gap: 7 }}>
                <span style={{ fontWeight: 600, fontSize: 14, color: "var(--fg-strong)" }}>{a.label}</span>
                {a.fav && <Icon name="star" size={12} color="var(--accent)" />}
              </span>
              <span style={{ display: "block", fontSize: 12.5, color: "var(--fg-mute)", marginTop: 2, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.line}, {a.suburb} · {a.contact}</span>
            </span>
            <Icon name="chevron-right" size={16} color="var(--fg-faint)" />
          </button>
        ))}
        {sorted.length === 0 && <div style={{ textAlign: "center", color: "var(--fg-mute)", fontSize: 14, padding: 20 }}>No matching addresses</div>}
      </div>
    </Modal>
  );
}

// Combined suburb/postcode field (item 7): type either a suburb or a postcode, search both,
// display both once matched. Used anywhere an address is entered.
function SuburbPostcodeField({ suburb, postcode, onPick, placeholder = "Type a suburb or postcode…" }) {
  const [q, setQ] = useStateAddr("");
  const [open, setOpen] = useStateAddr(false);
  const [editing, setEditing] = useStateAddr(false);
  const results = window.FX.searchSuburbs(q);
  const pc = postcode || (suburb ? window.FX.suburbPostcode(suburb) : "");
  return (
    <div style={{ position: "relative" }}>
      {(!editing && suburb) ? (
        <button type="button" onClick={() => { setEditing(true); setQ(""); setOpen(false); }} style={{ ...inputStyle, display: "flex", alignItems: "center", justifyContent: "space-between", cursor: "text", textAlign: "left" }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 8, minWidth: 0 }}>
            <Icon name="map-pin" size={14} color="var(--brand)" />
            <span style={{ fontWeight: 500, color: "var(--fg-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{suburb}</span>
            {pc && <span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--fg-mute)", flex: "none" }}>{pc}</span>}
          </span>
          <Icon name="search" size={14} color="var(--fg-faint)" />
        </button>
      ) : (
        <div style={{ position: "relative" }}>
          <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--fg-mute)" }}><Icon name="search" size={15} /></span>
          <input autoFocus={editing} value={q} placeholder={placeholder}
            onChange={e => { setQ(e.target.value); setOpen(true); }}
            onFocus={() => setOpen(true)}
            onBlur={() => setTimeout(() => { setOpen(false); setEditing(false); }, 160)}
            style={{ ...inputStyle, paddingLeft: 36 }} />
        </div>
      )}
      {open && q && (
        <div className="fade-in" style={{ position: "absolute", top: "calc(100% + 4px)", left: 0, right: 0, background: "var(--surface)", borderRadius: "var(--r-md)", boxShadow: "var(--shadow-pop)", border: "1px solid var(--border)", padding: 5, zIndex: 70, maxHeight: 244, overflowY: "auto" }}>
          {results.map(s => (
            <button key={s.name} type="button" onMouseDown={() => { onPick(s.name, s.postcode); setQ(""); setOpen(false); setEditing(false); }} style={{ display: "flex", alignItems: "center", gap: 10, width: "100%", textAlign: "left", padding: "9px 10px", borderRadius: "var(--r-sm)", border: "none", background: "transparent" }}
              onMouseEnter={e => e.currentTarget.style.background = "var(--bg-mist)"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
              <Icon name="map-pin" size={14} color="var(--fg-faint)" />
              <span style={{ flex: 1, fontSize: 13.5, fontWeight: 500, color: "var(--fg-strong)" }}>{s.name}</span>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-mute)" }}>{s.postcode}</span>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--fg-faint)", width: 30, textAlign: "right" }}>{s.state}</span>
            </button>
          ))}
          {results.length === 0 && <div style={{ padding: "10px", fontSize: 13, color: "var(--fg-mute)" }}>No suburb or postcode matches “{q}”.</div>}
        </div>
      )}
    </div>
  );
}

// Inline, always-editable address form. The address book is an optional shortcut.
function AddressField({ value, onChange, addressBook, role, accent = "var(--brand)", onRemove, index, compact }) {
  const [open, setOpen] = useStateAddr(false);
  const [more, setMore] = useStateAddr(false);
  const v = value || window.FX.emptyAddr();
  const set = (k, val) => onChange({ ...v, [k]: val });
  const isPickup = role.toLowerCase().includes("pickup");
  return (
    <div style={{ border: "1px solid var(--border)", borderRadius: "var(--r-lg)", padding: 16, background: "var(--surface)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 14 }}>
        <span style={{ width: 26, height: 26, borderRadius: 8, background: accent, color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none", fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 12 }}>
          {index != null ? index + 1 : <Icon name="map-pin" size={15} />}
        </span>
        <span style={{ fontSize: 13, fontWeight: 600, letterSpacing: "0.3px", textTransform: "uppercase", fontFamily: "var(--font-mono)", color: "var(--fg-mute)", flex: 1 }}>{role}</span>
        <button onClick={() => setOpen(true)} title="Select from address book" style={{ display: "inline-flex", alignItems: "center", gap: 6, background: "var(--brand-soft)", border: "none", borderRadius: "var(--r-pill)", padding: "6px 12px", color: "var(--brand)", fontSize: 12.5, fontWeight: 500 }}>
          <Icon name="search" size={14} /> Address book
        </button>
        {onRemove && <button onClick={onRemove} title="Remove stop" style={{ background: "var(--bg-mist)", border: "none", borderRadius: "50%", width: 30, height: 30, display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--fg-mute)", flex: "none" }}><Icon name="x" size={15} /></button>}
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        <Field label={compact ? "Search address — suburb or postcode" : "Suburb or postcode"}><SuburbPostcodeField suburb={v.suburb} postcode={v.postcode} onPick={(sub, pcode) => onChange({ ...v, suburb: sub, postcode: pcode })} /></Field>
        {compact && !more && (
          <button onClick={() => setMore(true)} style={{ display: "inline-flex", alignItems: "center", gap: 7, alignSelf: "flex-start", padding: "8px 13px", background: "var(--surface)", border: "1px dashed var(--border-strong)", borderRadius: "var(--r-pill)", color: "var(--brand)", fontSize: 12.5, fontWeight: 600, cursor: "pointer" }}>
            <Icon name="plus" size={14} /> Contact &amp; address details{(v.contact || v.line) ? ` · ${[v.contact, v.line].filter(Boolean).join(" · ")}` : " (optional)"}
          </button>
        )}
        {(!compact || more) && (
          <React.Fragment>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <Field label="Contact name"><TextInput value={v.contact} onChange={x => set("contact", x)} placeholder="Jane Smith" /></Field>
              <Field label="Phone"><TextInput value={v.phone} onChange={x => set("phone", x)} placeholder="+61 4xx xxx xxx" mono /></Field>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <Field label="Email"><TextInput value={v.email} onChange={x => set("email", x)} placeholder="name@company.com.au" type="email" /></Field>
              <Field label="Company (optional)"><TextInput value={v.company} onChange={x => set("company", x)} placeholder="Acme Pty Ltd" /></Field>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 2fr", gap: 12 }}>
              <Field label="Unit / level (optional)"><TextInput value={v.unit} onChange={x => set("unit", x)} placeholder="Unit 4 / Level 2" /></Field>
              <Field label="Street address"><TextInput value={v.line} onChange={x => set("line", x)} placeholder="123 George St" /></Field>
            </div>
          </React.Fragment>
        )}
        <Field label={(isPickup ? "Pickup" : "Delivery") + " instructions (optional)"}>
          <textarea value={v.instructions || ""} onChange={e => set("instructions", e.target.value)} rows={2}
            placeholder={isPickup ? "e.g. Loading dock at rear, ask for dispatch" : "e.g. Leave at reception, call on arrival"}
            style={{ ...inputStyle, resize: "vertical", fontSize: 13.5, lineHeight: 1.45 }} />
        </Field>
      </div>

      <AddressBookModal open={open} onClose={() => setOpen(false)} addressBook={addressBook}
        onPick={a => { onChange({ contact: a.contact || "", company: a.company || "", email: a.email || "", phone: a.phone || "", unit: a.unit || "", line: a.line || "", suburb: a.suburb || "", postcode: a.postcode || "", instructions: v.instructions || "", label: a.label }); setOpen(false); }} />
    </div>
  );
}

Object.assign(window, { Modal, AddressBookModal, AddressField, SuburbPostcodeField });
