// หน้าตั้งค่าระบบ — ข้อมูลร้าน / รหัสเข้าระบบ / รหัสพนักงาน / เงื่อนไขการซ่อม / PDPA
function pwValid(s) { return /^[A-Za-z0-9]{8,}$/.test(s || ""); }

/* แท็บปุ่ม pill */
function SettingsTab({ active, onClick, children }) {
  return (
    <button onClick={onClick} style={{
      padding: "8px 16px", border: "none", cursor: "pointer",
      background: active ? T.primary : T.chipBg,
      color: active ? "#fff" : T.text,
      borderRadius: 10, fontSize: 13.5, fontWeight: 700, fontFamily: T.bodyFont,
      boxShadow: active ? T.btnShadow : "none", transition: "all .15s",
    }}>{children}</button>
  );
}

/* อัปโหลดรูปเป็น base64 */
function readImageFile(file, cb) {
  const r = new FileReader();
  r.onload = () => cb(r.result);
  r.readAsDataURL(file);
}

/* ── แท็บข้อมูลร้านค้า ── */
function StoreInfoTab() {
  const { st, dispatch } = useStore();
  const s = st.settings;
  const set = (patch) => dispatch({ type: "SETTINGS_SET", patch });
  const logoRef = React.useRef(null);
  const qrRef = React.useRef(null);

  return (
    <Card style={{ padding: 24 }}>
      <div style={{ fontFamily: T.headFont, fontWeight: 700, fontSize: 17, marginBottom: 18 }}>ข้อมูลร้านค้า</div>
      <div style={{ display: "grid", gridTemplateColumns: "200px 1fr", gap: 28 }}>
        {/* ซ้าย: โลโก้ + QR Line */}
        <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
          <div>
            <div style={{ fontSize: 12.5, fontWeight: 600, color: T.sub, marginBottom: 8 }}>โลโก้ร้าน</div>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
              <img src={logoSrc(st)} alt="logo" style={{ width: 96, height: 96, objectFit: "contain" }} />
              <div style={{ fontSize: 11.5, color: T.sub, textAlign: "center", lineHeight: 1.5 }}>
                แสดงบนเมนู ใบเสร็จ และใบรับซ่อม
                {s.logo && <div><a className="ss-link" style={{ color: T.accent }} onClick={() => set({ logo: null })}>ลบรูป</a></div>}
              </div>
              <input ref={logoRef} type="file" accept="image/*" style={{ display: "none" }}
                onChange={(e) => { const f = e.target.files[0]; if (f) readImageFile(f, (d) => set({ logo: d })); }} />
              <Btn sm kind="ghost" onClick={() => logoRef.current && logoRef.current.click()}>เปลี่ยนโลโก้</Btn>
            </div>
          </div>
          <div>
            <div style={{ fontSize: 12.5, fontWeight: 600, color: T.sub, marginBottom: 8 }}>QR Code LINE</div>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
              {s.lineQr ? (
                <img src={s.lineQr} alt="line qr" style={{ width: 140, height: 140, objectFit: "contain", border: `1px solid ${T.border}`, borderRadius: 8 }} />
              ) : (
                <div style={{ width: 140, height: 140, border: `2px dashed ${T.border}`, borderRadius: 8, display: "flex", alignItems: "center", justifyContent: "center", color: T.sub, fontSize: 12, textAlign: "center", padding: 10 }}>
                  ยังไม่มี QR<br />LINE ร้าน
                </div>
              )}
              <input ref={qrRef} type="file" accept="image/*" style={{ display: "none" }}
                onChange={(e) => { const f = e.target.files[0]; if (f) readImageFile(f, (d) => set({ lineQr: d })); }} />
              <div style={{ display: "flex", gap: 6 }}>
                <Btn sm kind="ghost" onClick={() => qrRef.current && qrRef.current.click()}>อัปโหลด</Btn>
                {s.lineQr && <Btn sm kind="dangerSoft" onClick={() => set({ lineQr: null })}>ลบ</Btn>}
              </div>
            </div>
          </div>
        </div>

        {/* ขวา: ฟอร์ม */}
        <div style={{ display: "grid", gap: 14 }}>
          <Field label="ชื่อร้าน" req><TextInput value={s.name || ""} onChange={(e) => set({ name: e.target.value })} /></Field>
          <Field label="คำโปรย / สโลแกน"><TextInput value={s.tagline || ""} onChange={(e) => set({ tagline: e.target.value })} /></Field>
          <Field label="ที่อยู่ร้าน (สำนักงานใหญ่)"><TextArea value={s.addr || ""} onChange={(e) => set({ addr: e.target.value })} /></Field>
          <Field label="เลขประจำตัวผู้เสียภาษีอากร"><TextInput value={s.taxId || ""} onChange={(e) => set({ taxId: e.target.value })} /></Field>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <Field label="เบอร์ติดต่อ"><TextInput value={s.tel || ""} onChange={(e) => set({ tel: e.target.value })} /></Field>
            <Field label="Line ID"><TextInput value={s.lineId || ""} onChange={(e) => set({ lineId: e.target.value })} placeholder="เช่น @ssphone_official" /></Field>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <Field label="อีเมลร้าน"><TextInput value={s.ownerEmail || ""} onChange={(e) => set({ ownerEmail: e.target.value })} /></Field>
            <Field label="เว็บไซต์"><TextInput value={s.website || ""} onChange={(e) => set({ website: e.target.value })} /></Field>
          </div>
          <Field label="Facebook"><TextInput value={s.facebook || ""} onChange={(e) => set({ facebook: e.target.value })} /></Field>
        </div>
      </div>
      <div style={{ marginTop: 18, padding: "10px 14px", background: T.chipBg, borderRadius: 10, fontSize: 12, color: T.sub }}>
        บันทึกอัตโนมัติ · ที่อยู่/เบอร์รายสาขาแก้ได้ที่หน้า "สาขา"
      </div>
    </Card>
  );
}

/* ── แท็บรหัสเข้าระบบ (เจ้าของร้าน) ── */
function LoginPwTab() {
  const { st, dispatch } = useStore();
  const toast = useToast();
  const owner = st.users.find((u) => u.role === "owner");
  const [cur, setCur] = React.useState("");
  const [np, setNp] = React.useState("");
  const [cf, setCf] = React.useState("");

  const change = () => {
    if (owner.password !== cur) { toast("รหัสผ่านเดิมไม่ถูกต้อง", "danger"); return; }
    if (!pwValid(np)) { toast("รหัสใหม่ต้องเป็น A-Z a-z 0-9 อย่างน้อย 8 ตัว", "danger"); return; }
    if (np !== cf) { toast("ยืนยันรหัสไม่ตรงกัน", "danger"); return; }
    dispatch({ type: "USER_SET", id: owner.id, patch: { password: np } });
    toast("เปลี่ยนรหัสเข้าระบบเรียบร้อย");
    setCur(""); setNp(""); setCf("");
  };

  return (
    <Card style={{ maxWidth: 520, padding: 24 }}>
      <div style={{ fontFamily: T.headFont, fontWeight: 700, fontSize: 17, marginBottom: 6 }}>รหัสเข้าระบบ (เจ้าของร้าน)</div>
      <div style={{ fontSize: 12.5, color: T.sub, marginBottom: 18 }}>ผู้ใช้ <b style={{ color: T.text }}>{owner.username}</b> · ใช้เข้าสู่ระบบในฐานะเจ้าของร้าน</div>
      <div style={{ display: "grid", gap: 14 }}>
        <Field label="รหัสผ่านเดิม"><TextInput type="password" value={cur} onChange={(e) => setCur(e.target.value)} /></Field>
        <Field label="รหัสผ่านใหม่"><TextInput type="password" value={np} onChange={(e) => setNp(e.target.value)} placeholder="A-Z a-z 0-9 อย่างน้อย 8 ตัว" /></Field>
        <Field label="ยืนยันรหัสผ่านใหม่"><TextInput type="password" value={cf} onChange={(e) => setCf(e.target.value)} /></Field>
        <div style={{ display: "flex", justifyContent: "flex-end" }}>
          <Btn onClick={change}>เปลี่ยนรหัสผ่าน</Btn>
        </div>
      </div>
    </Card>
  );
}

/* ── แท็บรหัสพนักงาน ── */
function StaffPwTab() {
  const { st, dispatch } = useStore();
  const toast = useToast();
  const [openId, setOpenId] = React.useState(null);
  const [np, setNp] = React.useState("");
  const staff = st.users.filter((u) => u.role !== "owner");

  const save = () => {
    if (!pwValid(np)) { toast("รหัสต้องเป็น A-Z a-z 0-9 อย่างน้อย 8 ตัว", "danger"); return; }
    dispatch({ type: "USER_SET", id: openId, patch: { password: np } });
    toast("ตั้งรหัสพนักงานเรียบร้อย");
    setOpenId(null); setNp("");
  };

  const cur = st.users.find((u) => u.id === openId);

  return (
    <Card style={{ padding: 24 }}>
      <div style={{ fontFamily: T.headFont, fontWeight: 700, fontSize: 17, marginBottom: 6 }}>รหัสพนักงาน</div>
      <div style={{ fontSize: 12.5, color: T.sub, marginBottom: 18 }}>เจ้าของร้านตั้ง/รีเซ็ตรหัสเข้าระบบของพนักงานได้ที่นี่</div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 12 }}>
        {staff.map((u) => (
          <div key={u.id} style={{ border: `1px solid ${T.border}`, borderRadius: 12, padding: 14, display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10 }}>
            <div>
              <div style={{ fontWeight: 700, fontSize: 14 }}>{u.name}</div>
              <div style={{ fontSize: 12, color: T.sub }}>{u.username} · {u.role}</div>
            </div>
            <Btn sm kind="ghost" onClick={() => { setOpenId(u.id); setNp(""); }}>ตั้งรหัส</Btn>
          </div>
        ))}
      </div>
      <Modal open={openId != null} onClose={() => setOpenId(null)} title={`ตั้งรหัสผ่าน — ${cur ? cur.name : ""}`} width={440}
        footer={<React.Fragment>
          <Btn kind="ghost" onClick={() => setOpenId(null)}>ยกเลิก</Btn>
          <Btn onClick={save}>บันทึก</Btn>
        </React.Fragment>}>
        <Field label="รหัสผ่านใหม่"><TextInput type="password" value={np} onChange={(e) => setNp(e.target.value)} placeholder="A-Z a-z 0-9 อย่างน้อย 8 ตัว" autoFocus /></Field>
      </Modal>
    </Card>
  );
}

/* ── แท็บเงื่อนไขการซ่อม ── */
function RepairTermsTab() {
  const { st, dispatch } = useStore();
  const rt = st.settings.repairTerms || {};
  const set = (patch) => dispatch({ type: "SETTINGS_SET", patch: { repairTerms: { ...rt, ...patch } } });

  return (
    <Card style={{ maxWidth: 720, padding: 24 }}>
      <div style={{ fontFamily: T.headFont, fontWeight: 700, fontSize: 17, marginBottom: 6 }}>เงื่อนไขการซ่อม</div>
      <div style={{ fontSize: 12.5, color: T.sub, marginBottom: 18 }}>ข้อความนี้จะพิมพ์ลงบนใบรับซ่อม</div>
      <div style={{ display: "grid", gap: 14 }}>
        <Field label="ความรับผิดชอบ"><TextArea value={rt.responsibility || ""} onChange={(e) => set({ responsibility: e.target.value })} /></Field>
        <Field label="การรับประกัน"><TextArea value={rt.warranty || ""} onChange={(e) => set({ warranty: e.target.value })} /></Field>
        <Field label="การรับเครื่อง"><TextArea value={rt.pickup || ""} onChange={(e) => set({ pickup: e.target.value })} /></Field>
        <Field label="ระยะเวลารับประกัน"><TextInput value={rt.warrantyTime || ""} onChange={(e) => set({ warrantyTime: e.target.value })} /></Field>
      </div>
      <div style={{ marginTop: 18, padding: "10px 14px", background: T.chipBg, borderRadius: 10, fontSize: 12, color: T.sub }}>บันทึกอัตโนมัติ</div>
    </Card>
  );
}

/* ── แท็บเงื่อนไขเครื่อง/อุปกรณ์ ── */
function SaleTermsTab() {
  const { st, dispatch } = useStore();
  const stt = st.settings.saleTerms || {};
  const set = (patch) => dispatch({ type: "SETTINGS_SET", patch: { saleTerms: { ...stt, ...patch } } });

  return (
    <Card style={{ maxWidth: 720, padding: 24 }}>
      <div style={{ fontFamily: T.headFont, fontWeight: 700, fontSize: 17, marginBottom: 6 }}>เงื่อนไขเครื่อง / อุปกรณ์</div>
      <div style={{ fontSize: 12.5, color: T.sub, marginBottom: 18 }}>ข้อความนี้จะพิมพ์ลงบนใบเสร็จการขายเครื่องและอุปกรณ์</div>
      <div style={{ display: "grid", gap: 14 }}>
        <Field label="เงื่อนไขเครื่อง (มือถือ/เครื่องมือสอง)"><TextArea value={stt.device || ""} onChange={(e) => set({ device: e.target.value })} /></Field>
        <Field label="เงื่อนไขอุปกรณ์ (อุปกรณ์เสริม)"><TextArea value={stt.accessory || ""} onChange={(e) => set({ accessory: e.target.value })} /></Field>
      </div>
      <div style={{ marginTop: 18, padding: "10px 14px", background: T.chipBg, borderRadius: 10, fontSize: 12, color: T.sub }}>บันทึกอัตโนมัติ</div>
    </Card>
  );
}

/* ── แท็บ PDPA ── */
function PdpaTab() {
  const { st, dispatch } = useStore();
  const p = st.settings.pdpa || {};
  const set = (patch) => dispatch({ type: "SETTINGS_SET", patch: { pdpa: { ...p, ...patch } } });

  return (
    <Card style={{ maxWidth: 720, padding: 24 }}>
      <div style={{ fontFamily: T.headFont, fontWeight: 700, fontSize: 17, marginBottom: 6 }}>PDPA — ความเป็นส่วนตัว</div>
      <div style={{ fontSize: 12.5, color: T.sub, marginBottom: 18 }}>ข้อความตามพระราชบัญญัติคุ้มครองข้อมูลส่วนบุคคล จะแสดงบนใบรับซ่อม</div>
      <div style={{ display: "grid", gap: 14 }}>
        <Field label="การเก็บข้อมูล"><TextArea value={p.collect || ""} onChange={(e) => set({ collect: e.target.value })} /></Field>
        <Field label="สิทธิของเจ้าของข้อมูล"><TextArea value={p.rights || ""} onChange={(e) => set({ rights: e.target.value })} /></Field>
        <Field label="ระยะเวลาเก็บข้อมูล"><TextArea value={p.retention || ""} onChange={(e) => set({ retention: e.target.value })} /></Field>
        <Field label="การให้ความยินยอม"><TextArea value={p.consent || ""} onChange={(e) => set({ consent: e.target.value })} /></Field>
      </div>
      <div style={{ marginTop: 18, padding: "10px 14px", background: T.chipBg, borderRadius: 10, fontSize: 12, color: T.sub }}>บันทึกอัตโนมัติ</div>
    </Card>
  );
}

/* ── หน้าหลัก ── */
function SettingsPage({ user }) {
  const [tab, setTab] = React.useState("info");
  const tabs = [
    { id: "info", label: "ข้อมูลร้านค้า" },
    { id: "login", label: "รหัสเข้าระบบ" },
    { id: "staff", label: "รหัสพนักงาน" },
    { id: "repair", label: "เงื่อนไขการซ่อม" },
    { id: "sale", label: "เงื่อนไขเครื่อง/อุปกรณ์" },
    { id: "pdpa", label: "PDPA" },
    { id: "backup", label: "สำรองข้อมูล" },
  ];

  return (
    <div>
      <div style={{ display: "flex", gap: 8, marginBottom: 18, flexWrap: "wrap" }}>
        {tabs.map((t) => (
          <SettingsTab key={t.id} active={tab === t.id} onClick={() => setTab(t.id)}>{t.label}</SettingsTab>
        ))}
      </div>
      {tab === "info" && <StoreInfoTab />}
      {tab === "login" && <LoginPwTab />}
      {tab === "staff" && <StaffPwTab />}
      {tab === "repair" && <RepairTermsTab />}
      {tab === "sale" && <SaleTermsTab />}
      {tab === "pdpa" && <PdpaTab />}
      {tab === "backup" && <BackupTab />}
    </div>
  );
}
window.SettingsPage = SettingsPage;
