// ===== Teuanjai Radio — Branch management (admin) =====
// เพิ่ม/แก้ไข/ลบ รหัสสาขา + ชื่อสาขา — บันทึกลงฐานข้อมูล (localStorage)

function BranchEditor({ initial, onSave, onCancel, onDelete }) {
  const isEdit = !!initial;
  const [code, setCode] = useState(initial ? initial.code : "");
  const [name, setName] = useState(initial ? initial.name : "");
  const [err, setErr] = useState("");

  const save = () => {
    const res = branchUpsert(code, name, { allowOverwrite: isEdit });
    if (!res.ok) { setErr(res.error); return; }
    onSave(res.code);
  };

  return (
    <div onClick={onCancel} style={{ position: "absolute", inset: 0, zIndex: 60, display: "flex", flexDirection: "column", justifyContent: "flex-end",
      background: "oklch(0.4 0.04 250 / 0.34)", backdropFilter: "blur(4px)", animation: "fadeIn 0.25s both" }}>
      <div onClick={(e) => e.stopPropagation()} className="glass" style={{ borderRadius: "26px 26px 0 0",
        padding: "10px 22px calc(22px + env(safe-area-inset-bottom))", background: "oklch(0.98 0.012 220 / 0.86)",
        animation: "slideUp 0.35s cubic-bezier(0.22,1,0.36,1)" }}>
        <div style={{ width: 44, height: 5, borderRadius: 5, background: "oklch(0.7 0.02 250 / 0.3)", margin: "4px auto 16px" }} />
        <div style={{ fontFamily: "var(--font-disp)", fontSize: 18, fontWeight: 700, color: "var(--ink)", marginBottom: 16 }}>
          {isEdit ? "แก้ไขสาขา" : "เพิ่มสาขาใหม่"}
        </div>

        <label style={lblStyle}>รหัสสาขา (ตัวเลข 3 หลัก)</label>
        <input value={code} inputMode="numeric" maxLength={3} disabled={isEdit}
          onChange={(e) => { setCode(e.target.value.replace(/\D/g, "").slice(0, 3)); setErr(""); }}
          placeholder="เช่น 015"
          style={{ ...inpStyle, fontFamily: "var(--font-disp)", letterSpacing: "0.2em", fontWeight: 700,
            opacity: isEdit ? 0.6 : 1, cursor: isEdit ? "not-allowed" : "text" }} />

        <label style={{ ...lblStyle, marginTop: 12 }}>ชื่อสาขา</label>
        <input value={name} onChange={(e) => { setName(e.target.value); setErr(""); }}
          placeholder="เช่น สาขาตลาดกลาง (สฎ-50)" style={inpStyle} />

        {err && (
          <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 10, color: "oklch(0.55 0.18 25)", fontSize: 12.5, fontWeight: 600 }}>
            <Icon name="xmark" size={14} /> {err}
          </div>
        )}

        <button onClick={save} style={{ ...btnPrimary, marginTop: 18 }}>{isEdit ? "บันทึกการแก้ไข" : "เพิ่มสาขา"}</button>
        {isEdit && (
          <button onClick={() => onDelete(initial.code)} style={{ ...btnGhost, marginTop: 10, color: "oklch(0.55 0.16 25)" }}>
            ลบสาขานี้
          </button>
        )}
        <button onClick={onCancel} style={{ ...btnGhost, marginTop: 10 }}>ยกเลิก</button>
      </div>
    </div>
  );
}

function ConfirmDelete({ branch, onConfirm, onCancel }) {
  return (
    <div onClick={onCancel} style={{ position: "absolute", inset: 0, zIndex: 70, display: "grid", placeItems: "center", padding: 28,
      background: "oklch(0.4 0.04 250 / 0.4)", backdropFilter: "blur(5px)", animation: "fadeIn 0.2s both" }}>
      <div onClick={(e) => e.stopPropagation()} className="glass" style={{ borderRadius: 24, padding: "24px 22px", maxWidth: 320, textAlign: "center",
        background: "oklch(0.98 0.012 220 / 0.9)", animation: "pop 0.32s both" }}>
        <div style={{ width: 52, height: 52, borderRadius: 16, margin: "0 auto 14px", display: "grid", placeItems: "center", color: "#fff",
          background: "linear-gradient(140deg, oklch(0.66 0.18 25), oklch(0.62 0.18 15))" }}><Icon name="trash" size={26} /></div>
        <div style={{ fontFamily: "var(--font-disp)", fontSize: 17, fontWeight: 700, color: "var(--ink)", marginBottom: 6 }}>ลบสาขานี้?</div>
        <div style={{ fontSize: 13.5, color: "var(--ink-soft)", lineHeight: 1.5, marginBottom: 18 }}>
          {branch.code} · {branch.name}
        </div>
        <button onClick={() => onConfirm(branch.code)} style={{ ...btnPrimary, background: "linear-gradient(120deg, oklch(0.62 0.18 22), oklch(0.6 0.17 10))" }}>ยืนยันลบ</button>
        <button onClick={onCancel} style={{ ...btnGhost, marginTop: 10 }}>ยกเลิก</button>
      </div>
    </div>
  );
}

function BranchView({ onMutate }) {
  const [q, setQ] = useState("");
  const [editing, setEditing] = useState(null);   // {code,name} | "new" | null
  const [confirm, setConfirm] = useState(null);
  const [tick, setTick] = useState(0);            // re-read after mutate

  const all = useMemo(() => branchList(), [tick]);
  const filtered = useMemo(() => {
    const s = q.trim().toLowerCase();
    if (!s) return all;
    return all.filter((b) => b.code.includes(s) || b.name.toLowerCase().includes(s));
  }, [all, q]);
  const customCount = all.filter((b) => b.custom).length;

  const bump = () => { setTick((t) => t + 1); if (onMutate) onMutate(); };

  return (
    <div className="scroll" style={{ flex: 1, padding: "4px 16px 160px" }}>
      {/* summary + add */}
      <div className="glass" style={{ borderRadius: 22, padding: "16px 18px", marginBottom: 14,
        background: "linear-gradient(135deg, oklch(0.96 0.03 220 / 0.7), oklch(0.96 0.03 175 / 0.6))" }}>
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 12 }}>
          <div>
            <div style={{ fontSize: 12.5, color: "var(--ink-soft)", fontWeight: 600, marginBottom: 4 }}>สาขาทั้งหมดในระบบ</div>
            <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
              <span style={{ fontFamily: "var(--font-disp)", fontSize: 32, fontWeight: 700, lineHeight: 1, color: "var(--ink)", fontVariantNumeric: "tabular-nums" }}>{all.length}</span>
              <span style={{ fontSize: 12, color: "var(--ink-faint)" }}>สาขา</span>
            </div>
          </div>
          <button onClick={() => setEditing("new")} style={{ display: "flex", alignItems: "center", gap: 7, height: 44, padding: "0 16px", borderRadius: 14,
            color: "#fff", fontSize: 14, fontWeight: 700, flex: "0 0 auto",
            background: "linear-gradient(120deg, var(--accent), var(--accent-2))", boxShadow: "0 10px 22px oklch(0.6 0.12 215 / 0.34)" }}>
            <Icon name="plus" size={18} /> เพิ่มสาขา
          </button>
        </div>
        {customCount > 0 && (
          <div style={{ fontSize: 11.5, color: "var(--ink-faint)", marginTop: 10 }}>เพิ่ม/แก้ไขเอง {customCount} สาขา</div>
        )}
      </div>

      {/* search */}
      <div className="glass" style={{ borderRadius: 14, padding: "0 14px", display: "flex", alignItems: "center", gap: 10, marginBottom: 14, height: 46 }}>
        <span style={{ color: "var(--ink-faint)", display: "inline-flex" }}><Icon name="search" size={18} /></span>
        <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="ค้นหารหัส หรือ ชื่อสาขา"
          style={{ flex: 1, border: "none", outline: "none", background: "transparent", fontSize: 14.5, color: "var(--ink)" }} />
        {q && <button onClick={() => setQ("")} style={{ color: "var(--ink-faint)", display: "inline-flex" }}><Icon name="xmark" size={17} /></button>}
      </div>

      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 4px 10px" }}>
        <div style={{ fontSize: 15, fontWeight: 700, color: "var(--ink)" }}>รายชื่อสาขา</div>
        <Chip>{filtered.length} รายการ</Chip>
      </div>

      {/* list */}
      {filtered.length === 0 ? (
        <div className="glass" style={{ borderRadius: 18, padding: "26px 16px", textAlign: "center", color: "var(--ink-faint)", fontSize: 13.5 }}>
          ไม่พบสาขาที่ตรงกับ “{q}”
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
          {filtered.map((b) => (
            <div key={b.code} className="glass" style={{ borderRadius: 16, padding: "10px 12px", display: "flex", alignItems: "center", gap: 12 }}>
              <div style={{ width: 46, height: 46, borderRadius: 13, flex: "0 0 auto", display: "grid", placeItems: "center",
                fontFamily: "var(--font-disp)", fontWeight: 700, fontSize: 16, color: "var(--accent-deep)",
                background: "oklch(0.93 0.04 215 / 0.7)", letterSpacing: "0.04em", fontVariantNumeric: "tabular-nums" }}>{b.code}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14.5, fontWeight: 600, color: "var(--ink)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{b.name}</div>
                <div style={{ fontSize: 11.5, color: "var(--ink-faint)", marginTop: 1 }}>{b.custom ? "เพิ่ม/แก้ไขเอง" : "ข้อมูลตั้งต้น"}</div>
              </div>
              <button onClick={() => setEditing({ code: b.code, name: b.name })} aria-label="แก้ไข"
                style={{ width: 38, height: 38, borderRadius: 11, flex: "0 0 auto", display: "grid", placeItems: "center",
                  color: "var(--accent-deep)", background: "oklch(1 0 0 / 0.6)", border: "1px solid var(--glass-line)" }}>
                <Icon name="edit" size={18} />
              </button>
            </div>
          ))}
        </div>
      )}

      {editing && (
        <BranchEditor
          initial={editing === "new" ? null : editing}
          onSave={() => { setEditing(null); bump(); }}
          onCancel={() => setEditing(null)}
          onDelete={(code) => { setEditing(null); setConfirm({ code, name: MEMBERS[code] || "" }); }}
        />
      )}
      {confirm && (
        <ConfirmDelete branch={confirm}
          onConfirm={(code) => { branchDelete(code); setConfirm(null); bump(); }}
          onCancel={() => setConfirm(null)} />
      )}
    </div>
  );
}

const lblStyle = { display: "block", fontSize: 12.5, fontWeight: 600, color: "var(--ink-soft)", marginBottom: 6 };
const inpStyle = { width: "100%", height: 50, borderRadius: 14, padding: "0 14px", fontSize: 15.5, color: "var(--ink)",
  background: "oklch(1 0 0 / 0.7)", border: "1.5px solid var(--glass-line)", outline: "none", boxSizing: "border-box" };

Object.assign(window, { BranchView });
