// Contacts — 聯絡窗口（場地／接駁／住宿／醫護）
(() => {
const { Panel, Badge, Button, Divider, Input, Select } = window.WCATalentGameDesignSystem_377d00;
const { Modal, FormRow, ModalActions, EditPencil } = window.WCA_UI;

const KIND = {
  venue: { label: "場地", tone: "gold", icon: "⛨" },
  shuttle: { label: "接駁", tone: "cyan", icon: "⛟" },
  lodging: { label: "住宿", tone: "info", icon: "☾" },
  medical: { label: "醫護", tone: "danger", icon: "✚" },
};
const KIND_OPTIONS = Object.entries(KIND).map(([value, k]) => ({ value, label: k.icon + " " + k.label }));

function ContactModal({ contact, nextSort, onClose, refresh }) {
  const [f, setF] = React.useState(contact || { kind: "venue", name: "", person: "", phone: "", note: "" });
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
  const save = async () => {
    if (!f.name.trim()) return alert("請填窗口名稱");
    const body = { kind: f.kind, name: f.name.trim(), person: f.person, phone: f.phone, note: f.note, sort: contact ? contact.sort : nextSort };
    if (contact) await api("PUT", "/api/contacts/" + contact.id, body);
    else await api("POST", "/api/contacts", body);
    await refresh(); onClose();
  };
  const del = contact ? async () => { await api("DELETE", "/api/contacts/" + contact.id); await refresh(); onClose(); } : null;
  return (
    <Modal title={contact ? "編輯聯絡窗口" : "新增聯絡窗口"} onClose={onClose}>
      <FormRow cols="0.7fr 1.3fr">
        <Select label="類別" value={f.kind} onChange={set("kind")} options={KIND_OPTIONS} />
        <Input label="名稱" value={f.name} onChange={set("name")} placeholder="例：谷關戰場基地 · 管理室" />
      </FormRow>
      <FormRow cols="1fr 1fr">
        <Input label="聯絡人" value={f.person} onChange={set("person")} />
        <Input label="電話" value={f.phone} onChange={set("phone")} />
      </FormRow>
      <FormRow cols="1fr"><Input label="備註" as="textarea" value={f.note} onChange={set("note")} /></FormRow>
      <ModalActions onSave={save} onCancel={onClose} onDelete={del} />
    </Modal>
  );
}

function ContactCard({ c, canEdit, onEdit }) {
  const k = KIND[c.kind] || KIND.venue;
  return (
    <Panel inset="18px">
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
        <span style={{ fontSize: 24, color: "var(--gold-400)", width: 40, height: 40, display: "flex", alignItems: "center", justifyContent: "center", background: "var(--navy-900)", borderRadius: "var(--radius-sm)", border: "1px solid var(--border-default)" }}>{k.icon}</span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: "var(--font-serif)", fontWeight: 700, fontSize: 17, color: "var(--text-primary)" }}>{c.name}</div>
          <div style={{ fontSize: 12.5, color: "var(--text-muted)" }}>{c.person}</div>
        </div>
        <Badge tone={k.tone} size="sm">{k.label}</Badge>
        {canEdit && <EditPencil onClick={() => onEdit(c)} />}
      </div>
      <Divider style={{ marginBottom: 12 }} />
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
        <span style={{ fontFamily: "var(--font-pixel)", fontSize: 8, color: "var(--text-muted)" }}>TEL</span>
        <a href={"tel:" + c.phone.replace(/[^0-9+]/g, "")} style={{ fontFamily: "var(--font-body)", fontSize: 16, color: "var(--text-gold)", letterSpacing: ".04em", textDecoration: "none" }}>{c.phone}</a>
      </div>
      <p style={{ margin: 0, fontSize: 13, color: "var(--text-secondary)", lineHeight: 1.7 }}>{c.note}</p>
    </Panel>
  );
}

function Contacts({ data, refresh, canEdit }) {
  const [modal, setModal] = React.useState(null);
  const copyAll = () => {
    const text = data.contacts.map((c) => `【${(KIND[c.kind] || KIND.venue).label}】${c.name}｜${c.person}｜${c.phone}｜${c.note}`).join("\n");
    navigator.clipboard.writeText(text).then(() => alert("已複製全部窗口"));
  };
  return (
    <div>
      {canEdit && (
        <div style={{ marginBottom: 16 }}>
          <Button size="sm" onClick={() => setModal({ new: true })}>＋ 新增窗口</Button>
        </div>
      )}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 16 }}>
        {data.contacts.map((c) => <ContactCard key={c.id} c={c} canEdit={canEdit} onEdit={(x) => setModal({ contact: x })} />)}
      </div>
      <Panel variant="battlefield" inset="16px">
        <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
          <span style={{ fontFamily: "var(--font-serif)", color: "var(--gold-200)", fontSize: 15 }}>緊急聯絡</span>
          <span style={{ color: "var(--paper)", fontSize: 15 }}>{data.meta.emergency_contact}</span>
          <Button size="sm" variant="secondary" style={{ marginLeft: "auto" }} onClick={copyAll}>複製全部窗口</Button>
        </div>
      </Panel>
      {modal && <ContactModal contact={modal.contact} nextSort={data.contacts.length} onClose={() => setModal(null)} refresh={refresh} />}
    </div>
  );
}
window.Contacts = Contacts;
})();
