/* global React, Icon, Field, Pill, DB */
const { useState: useStateS, useEffect: useEffectS } = React;

function Settings({ t, setTweak, adminAvatar, setAdminAvatar }) {
  const [tab, setTab] = useStateS("business");

  // ── ข้อมูลธุรกิจ ──
  const [biz, setBiz] = useStateS({
    name: t.brand || "", tagline: t.tagline || "",
    address: "", phone: "", taxId: "",
  });
  const [bizSaved, setBizSaved] = useStateS(false);
  const [bizLoading, setBizLoading] = useStateS(false);

  // ── รหัสผ่าน ──
  const [oldPass, setOldPass] = useStateS("");
  const [newPass, setNewPass] = useStateS("");
  const [confirmPass, setConfirmPass] = useStateS("");
  const [passError, setPassError] = useStateS("");
  const [passSaved, setPassSaved] = useStateS(false);
  const [showOld, setShowOld] = useStateS(false);
  const [showNew, setShowNew] = useStateS(false);

  // ── Login background ──
  const [bgType, setBgType] = useStateS("gradient");
  const [bgUrl, setBgUrl] = useStateS("");
  const [bgSaved, setBgSaved] = useStateS(false);
  const [bgLoading, setBgLoading] = useStateS(false);
  const [imgStatus, setImgStatus] = useStateS("idle"); // idle | loading | ok | error
  const [loginTitle, setLoginTitle] = useStateS("ระบบจัดการอัจฉริยะ");
  const [loginSubtitle, setLoginSubtitle] = useStateS("สำหรับห้องพักและที่จอดรถ");

  // ── โปรไฟล์ ──
  const [avatarSaved, setAvatarSaved] = useStateS(false);

  // โหลดข้อมูลจาก DB
  useEffectS(() => {
    DB.loadSettings().then(s => {
      if (s.business_address) setBiz(b => ({ ...b, address: s.business_address || "" }));
      if (s.business_phone)   setBiz(b => ({ ...b, phone:   s.business_phone   || "" }));
      if (s.business_tax_id)  setBiz(b => ({ ...b, taxId:   s.business_tax_id  || "" }));
      if (s.login_bg_image)   { setBgType("url"); setBgUrl(s.login_bg_image); }
      if (s.login_title)      setLoginTitle(s.login_title);
      if (s.login_subtitle)   setLoginSubtitle(s.login_subtitle);
    }).catch(console.error);
  }, []);

  // sync brand/tagline ถ้า tweaks เปลี่ยนจากที่อื่น
  useEffectS(() => {
    setBiz(b => ({ ...b, name: t.brand || "", tagline: t.tagline || "" }));
  }, [t.brand, t.tagline]);

  // ── Save ──
  const saveBiz = async () => {
    setBizLoading(true);
    try {
      if (biz.name.trim())    setTweak("brand",   biz.name.trim());
      if (biz.tagline.trim()) setTweak("tagline", biz.tagline.trim());
      await Promise.all([
        DB.saveSetting("business_address", biz.address),
        DB.saveSetting("business_phone",   biz.phone),
        DB.saveSetting("business_tax_id",  biz.taxId),
      ]);
      setBizSaved(true);
      setTimeout(() => setBizSaved(false), 2500);
    } finally { setBizLoading(false); }
  };

  const savePassword = async () => {
    setPassError("");
    try {
      const s = await DB.loadSettings();
      const stored = s.admin_password ? atob(s.admin_password) : atob("UEByQHNpdGUxNDQ=");
      if (oldPass !== stored)      { setPassError("รหัสผ่านปัจจุบันไม่ถูกต้อง"); return; }
      if (newPass.length < 6)      { setPassError("รหัสผ่านใหม่ต้องมีอย่างน้อย 6 ตัวอักษร"); return; }
      if (newPass !== confirmPass)  { setPassError("รหัสผ่านใหม่ไม่ตรงกัน"); return; }
      await DB.saveSetting("admin_password", btoa(newPass));
      setPassSaved(true);
      setOldPass(""); setNewPass(""); setConfirmPass("");
      setTimeout(() => setPassSaved(false), 2500);
    } catch (e) { setPassError("เกิดข้อผิดพลาด: " + e.message); }
  };

  const saveBg = async () => {
    setBgLoading(true);
    try {
      await Promise.all([
        DB.saveSetting("login_bg_image", bgType === "gradient" ? "" : bgUrl),
        DB.saveSetting("login_title",    loginTitle),
        DB.saveSetting("login_subtitle", loginSubtitle),
      ]);
      setBgSaved(true);
      setTimeout(() => setBgSaved(false), 2500);
    } finally { setBgLoading(false); }
  };

  // บีบอัดรูปโปรไฟล์เป็น base64 ขนาด 160x160
  const compressAvatar = (file) => new Promise((resolve) => {
    const reader = new FileReader();
    reader.onload = (ev) => {
      const img = new Image();
      img.onload = () => {
        const size = 160;
        const canvas = document.createElement("canvas");
        canvas.width = canvas.height = size;
        const ctx = canvas.getContext("2d");
        const scale = Math.max(size / img.width, size / img.height);
        const w = img.width * scale, h = img.height * scale;
        ctx.drawImage(img, (size - w) / 2, (size - h) / 2, w, h);
        resolve(canvas.toDataURL("image/jpeg", 0.85));
      };
      img.src = ev.target.result;
    };
    reader.readAsDataURL(file);
  });

  const handleAvatarChange = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (file.size > 5 * 1024 * 1024) { alert("ไฟล์ใหญ่เกิน 5MB"); return; }
    const compressed = await compressAvatar(file);
    setAdminAvatar(compressed);
    await DB.saveSetting("admin_avatar", compressed);
    setAvatarSaved(true);
    setTimeout(() => setAvatarSaved(false), 2500);
  };

  const removeAvatar = async () => {
    setAdminAvatar("");
    await DB.saveSetting("admin_avatar", "");
  };

  const COLORS = ["#2563eb","#0ea5a4","#ea580c","#7c3aed","#16804a","#be123c","#0f172a","#d97706","#db2777"];

  const EyeBtn = ({ show, onToggle }) => (
    <button type="button" tabIndex={-1} onClick={onToggle} style={{
      position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)",
      background: "none", border: "none", cursor: "pointer", color: "var(--ink-3)", padding: "4px 6px",
      display: "flex", alignItems: "center",
    }}>
      {show
        ? <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
        : <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
      }
    </button>
  );

  return (
    <div className="grid" style={{ gap: 18, maxWidth: 720 }}>

      {/* Tab bar */}
      <div className="tabs" style={{ flexWrap: "wrap" }}>
        {[
          ["business", <><Icon name="doc" size={15}/> ข้อมูลธุรกิจ</>],
          ["theme",    <><Icon name="sun" size={15}/> ธีมและสี</>],
          ["password", <><Icon name="settings" size={15}/> เปลี่ยนรหัสผ่าน</>],
          ["login",    <><Icon name="home" size={15}/> หน้า Login</>],
          ["profile",  <><Icon name="users" size={15}/> โปรไฟล์</>],
        ].map(([id, label]) => (
          <button key={id} className={"tab " + (tab === id ? "active" : "")}
            onClick={() => setTab(id)} style={{ display: "flex", alignItems: "center", gap: 6 }}>
            {label}
          </button>
        ))}
      </div>

      {/* ══ ข้อมูลธุรกิจ ══ */}
      {tab === "business" && (
        <div className="card">
          <div className="card-head">
            <h3>ข้อมูลธุรกิจ</h3>
            <div className="spacer"/>
            <span style={{ fontSize: "0.8rem", color: "var(--ink-3)" }}>แสดงบนใบเสร็จ / ใบแจ้งหนี้</span>
          </div>
          <div className="grid" style={{ gap: 14 }}>
            <div className="grid cols-2" style={{ gap: 14 }}>
              <Field label="ชื่อกิจการ">
                <input className="input" value={biz.name}
                  onChange={e => setBiz(b => ({ ...b, name: e.target.value }))}
                  placeholder="ParkingHome"/>
              </Field>
              <Field label="คำโปรย">
                <input className="input" value={biz.tagline}
                  onChange={e => setBiz(b => ({ ...b, tagline: e.target.value }))}
                  placeholder="ห้องพัก & ที่จอดรถ"/>
              </Field>
            </div>
            <Field label="ที่อยู่">
              <textarea className="input" rows={2} value={biz.address}
                onChange={e => setBiz(b => ({ ...b, address: e.target.value }))}
                placeholder="เลขที่ ถนน แขวง/ตำบล เขต/อำเภอ จังหวัด รหัสไปรษณีย์"
                style={{ resize: "vertical" }}/>
            </Field>
            <div className="grid cols-2" style={{ gap: 14 }}>
              <Field label="เบอร์โทรศัพท์">
                <input className="input" value={biz.phone}
                  onChange={e => setBiz(b => ({ ...b, phone: e.target.value }))}
                  placeholder="02-xxx-xxxx"/>
              </Field>
              <Field label="เลขที่ผู้เสียภาษี">
                <input className="input" value={biz.taxId}
                  onChange={e => setBiz(b => ({ ...b, taxId: e.target.value }))}
                  placeholder="0-0000-00000-00-0"/>
              </Field>
            </div>
          </div>
          <div className="row" style={{ justifyContent: "flex-end", marginTop: 18, gap: 10 }}>
            {bizSaved && <Pill tone="ok">✓ บันทึกแล้ว</Pill>}
            <button className="btn primary" onClick={saveBiz} disabled={bizLoading}>
              <Icon name="check" size={16}/> {bizLoading ? "กำลังบันทึก…" : "บันทึก"}
            </button>
          </div>
        </div>
      )}

      {/* ══ ธีมและสี ══ */}
      {tab === "theme" && (
        <div className="card">
          <div className="card-head"><h3>ธีมและสี</h3></div>
          <div className="grid" style={{ gap: 24 }}>

            {/* สีหลัก */}
            <div>
              <div style={{ fontWeight: 600, marginBottom: 12 }}>สีหลัก (Accent Color)</div>
              <div className="row" style={{ gap: 10, flexWrap: "wrap", alignItems: "center" }}>
                {COLORS.map(c => (
                  <button key={c} onClick={() => setTweak("accent", c)} style={{
                    width: 38, height: 38, borderRadius: 10, background: c,
                    border: "none", cursor: "pointer", flexShrink: 0,
                    boxShadow: t.accent === c ? `0 0 0 3px var(--surface), 0 0 0 5px ${c}` : "none",
                    transition: "box-shadow .15s",
                  }}/>
                ))}
                <label style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer" }}>
                  <input type="color" value={t.accent}
                    onChange={e => setTweak("accent", e.target.value)}
                    style={{ width: 38, height: 38, borderRadius: 10, border: "1px solid var(--line)", cursor: "pointer", padding: 3 }}/>
                  <span style={{ fontSize: "0.82rem", color: "var(--ink-3)" }}>กำหนดเอง</span>
                </label>
              </div>
              <div style={{ marginTop: 10, padding: "10px 14px", background: "var(--surface-2)", borderRadius: 8,
                display: "flex", alignItems: "center", gap: 10, fontSize: "0.85rem" }}>
                <div style={{ width: 20, height: 20, borderRadius: 6, background: t.accent, flexShrink: 0 }}/>
                <span style={{ color: "var(--ink-3)" }}>สีที่เลือก:</span>
                <strong>{t.accent}</strong>
              </div>
            </div>

            {/* โหมด */}
            <div>
              <div style={{ fontWeight: 600, marginBottom: 10 }}>โหมดการแสดงผล</div>
              <div className="row" style={{ gap: 8 }}>
                {[["light","☀️","โหมดสว่าง"],["dark","🌙","โหมดมืด"]].map(([v,ic,l]) => (
                  <button key={v} className="btn" onClick={() => setTweak("theme", v)} style={{
                    flex: 1, flexDirection: "column", gap: 6, padding: "14px 0", justifyContent: "center",
                    background: t.theme === v ? "var(--accent)" : "var(--surface-2)",
                    color: t.theme === v ? "#fff" : "var(--ink)",
                    borderColor: t.theme === v ? "var(--accent)" : "var(--line)",
                    fontWeight: t.theme === v ? 600 : 400,
                  }}>
                    <span style={{ fontSize: "1.4rem" }}>{ic}</span>
                    <span style={{ fontSize: "0.83rem" }}>{l}</span>
                  </button>
                ))}
              </div>
            </div>

            {/* โทน */}
            <div>
              <div style={{ fontWeight: 600, marginBottom: 10 }}>โทนสีพื้นหลัง</div>
              <div className="row" style={{ gap: 8 }}>
                {[["warm","🟡","อบอุ่น (Warm)"],["neutral","⬜","เป็นกลาง (Neutral)"]].map(([v,ic,l]) => (
                  <button key={v} className="btn" onClick={() => setTweak("warmth", v)} style={{
                    flex: 1, flexDirection: "column", gap: 6, padding: "14px 0", justifyContent: "center",
                    background: t.warmth === v ? "var(--accent)" : "var(--surface-2)",
                    color: t.warmth === v ? "#fff" : "var(--ink)",
                    borderColor: t.warmth === v ? "var(--accent)" : "var(--line)",
                    fontWeight: t.warmth === v ? 600 : 400,
                  }}>
                    <span style={{ fontSize: "1.3rem" }}>{ic}</span>
                    <span style={{ fontSize: "0.83rem" }}>{l}</span>
                  </button>
                ))}
              </div>
            </div>

            {/* ขนาดตัวอักษร */}
            <div>
              <div className="row" style={{ justifyContent: "space-between", marginBottom: 10 }}>
                <span style={{ fontWeight: 600 }}>ขนาดตัวอักษร</span>
                <Pill>{Math.round(t.fontScale * 100)}%</Pill>
              </div>
              <input type="range" min="85" max="120" step="5"
                value={Math.round(t.fontScale * 100)}
                onChange={e => setTweak("fontScale", +e.target.value / 100)}
                style={{ width: "100%", accentColor: "var(--accent)" }}/>
              <div className="row" style={{ justifyContent: "space-between", fontSize: "0.78rem", color: "var(--ink-3)", marginTop: 6 }}>
                <span>เล็กสุด 85%</span><span>ปกติ 100%</span><span>ใหญ่สุด 120%</span>
              </div>
            </div>

            <div style={{ padding: "10px 14px", background: "var(--info-soft)", borderRadius: 8, fontSize: "0.83rem", color: "var(--ink-2)" }}>
              ✨ การเปลี่ยนธีมมีผลทันที — ไม่ต้องกดบันทึก
            </div>
          </div>
        </div>
      )}

      {/* ══ เปลี่ยนรหัสผ่าน ══ */}
      {tab === "password" && (
        <div className="card" style={{ maxWidth: 480 }}>
          <div className="card-head"><h3>เปลี่ยนรหัสผ่านผู้ดูแลระบบ</h3></div>
          <div className="grid" style={{ gap: 16 }}>
            <Field label="รหัสผ่านปัจจุบัน">
              <div style={{ position: "relative" }}>
                <input className="input" type={showOld ? "text" : "password"}
                  style={{ paddingRight: 40 }}
                  value={oldPass} onChange={e => setOldPass(e.target.value)}
                  autoComplete="current-password"/>
                <EyeBtn show={showOld} onToggle={() => setShowOld(v => !v)}/>
              </div>
            </Field>
            <Field label="รหัสผ่านใหม่">
              <div style={{ position: "relative" }}>
                <input className="input" type={showNew ? "text" : "password"}
                  style={{ paddingRight: 40 }}
                  placeholder="อย่างน้อย 6 ตัวอักษร"
                  value={newPass} onChange={e => setNewPass(e.target.value)}
                  autoComplete="new-password"/>
                <EyeBtn show={showNew} onToggle={() => setShowNew(v => !v)}/>
              </div>
            </Field>
            <Field label="ยืนยันรหัสผ่านใหม่">
              <div style={{ position: "relative" }}>
                <input className="input" type={showNew ? "text" : "password"}
                  style={{ paddingRight: 40 }}
                  placeholder="พิมพ์รหัสผ่านใหม่อีกครั้ง"
                  value={confirmPass} onChange={e => setConfirmPass(e.target.value)}
                  autoComplete="new-password"/>
              </div>
            </Field>

            {/* strength */}
            {newPass && (
              <div>
                {[
                  [newPass.length >= 8,  "อย่างน้อย 8 ตัวอักษร"],
                  [/[A-Z]/.test(newPass),"มีตัวพิมพ์ใหญ่"],
                  [/[0-9]/.test(newPass),"มีตัวเลข"],
                  [/[^A-Za-z0-9]/.test(newPass),"มีอักขระพิเศษ"],
                ].map(([ok, label]) => (
                  <div key={label} className="row" style={{ gap: 6, marginBottom: 4, fontSize: "0.8rem",
                    color: ok ? "var(--ok)" : "var(--ink-3)" }}>
                    <span>{ok ? "✓" : "○"}</span><span>{label}</span>
                  </div>
                ))}
              </div>
            )}

            {passError && (
              <div style={{ padding: "10px 14px", borderRadius: 8, fontSize: "0.86rem",
                background: "var(--danger-soft)", color: "var(--danger)",
                border: "1px solid color-mix(in oklab, var(--danger) 25%, transparent)" }}>
                ⚠️ {passError}
              </div>
            )}

            <div className="row" style={{ justifyContent: "flex-end", gap: 10, marginTop: 4 }}>
              {passSaved && <Pill tone="ok">✓ เปลี่ยนรหัสผ่านแล้ว</Pill>}
              <button className="btn primary" onClick={savePassword}
                disabled={!oldPass || !newPass || !confirmPass}>
                <Icon name="check" size={16}/> เปลี่ยนรหัสผ่าน
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ══ หน้า Login ══ */}
      {tab === "login" && (
        <div className="card">
          <div className="card-head"><h3>รูปพื้นหลังหน้า Login</h3></div>
          <div className="grid" style={{ gap: 16 }}>
            <div className="row" style={{ gap: 8 }}>
              {[["gradient","🎨 ไล่สี (Default)"],["url","🖼️ URL รูปภาพ"]].map(([v, l]) => (
                <button key={v} className="btn" onClick={() => setBgType(v)} style={{
                  flex: 1, justifyContent: "center",
                  background: bgType === v ? "var(--accent)" : "var(--surface-2)",
                  color: bgType === v ? "#fff" : "var(--ink)",
                  borderColor: bgType === v ? "var(--accent)" : "var(--line)",
                  fontWeight: bgType === v ? 600 : 400,
                }}>{l}</button>
              ))}
            </div>

            {bgType === "url" && (
              <div className="grid" style={{ gap: 10 }}>
                <Field label="URL รูปภาพ (ต้องเป็น link รูปโดยตรง)">
                  <input className="input" placeholder="https://images.unsplash.com/photo-..."
                    value={bgUrl}
                    onChange={e => { setBgUrl(e.target.value); setImgStatus("loading"); }}/>
                </Field>

                {/* คำแนะนำ */}
                <div style={{ padding: "10px 14px", background: "var(--info-soft)", borderRadius: 8, fontSize: "0.8rem", color: "var(--ink-2)", lineHeight: 1.6 }}>
                  <strong>⚠️ ต้องใช้ URL ของรูปภาพโดยตรง</strong> ไม่ใช่หน้าเว็บ<br/>
                  • <strong>Unsplash:</strong> เปิดรูป → คลิกขวา → "คัดลอก URL รูปภาพ" หรือใช้รูปด้านล่าง<br/>
                  • <strong>Google Drive / Dropbox:</strong> ต้องเปิดเป็น public แล้วได้ link รูป
                </div>

                {/* รูปตัวอย่างสำเร็จรูป */}
                <div>
                  <div style={{ fontSize: "0.82rem", fontWeight: 600, marginBottom: 8, color: "var(--ink-2)" }}>
                    🖼️ รูปอาคาร/คอนโด สำเร็จรูป — คลิกเพื่อใช้
                  </div>
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8 }}>
                    {[
                      { label: "คอนโด 1", url: "https://images.unsplash.com/photo-1545324418-cc1a3fa10c00?w=1200&fit=crop&q=80" },
                      { label: "อาคาร 1", url: "https://images.unsplash.com/photo-1486325212027-8081e485255e?w=1200&fit=crop&q=80" },
                      { label: "อพาร์ต", url: "https://images.unsplash.com/photo-1560448204-e02f11c3d0e2?w=1200&fit=crop&q=80" },
                      { label: "โมเดิร์น", url: "https://images.unsplash.com/photo-1512917774080-9991f1c4c750?w=1200&fit=crop&q=80" },
                    ].map(({ label, url }) => (
                      <button key={url} onClick={() => { setBgUrl(url); setImgStatus("loading"); }}
                        style={{
                          padding: 0, border: bgUrl === url ? "2px solid var(--accent)" : "2px solid var(--line)",
                          borderRadius: 8, overflow: "hidden", cursor: "pointer", position: "relative",
                          height: 64, background: "var(--surface-2)",
                        }}>
                        <img src={url} alt={label}
                          style={{ width: "100%", height: "100%", objectFit: "cover" }}/>
                        <div style={{
                          position: "absolute", inset: 0, background: "rgba(0,0,0,0.3)",
                          display: "flex", alignItems: "flex-end", padding: "4px 6px",
                        }}>
                          <span style={{ color: "#fff", fontSize: "0.7rem", fontWeight: 600 }}>{label}</span>
                        </div>
                        {bgUrl === url && (
                          <div style={{ position: "absolute", top: 4, right: 4, background: "var(--accent)",
                            borderRadius: "50%", width: 16, height: 16, display: "grid", placeItems: "center" }}>
                            <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3"><path d="M5 12l5 5L20 7"/></svg>
                          </div>
                        )}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            )}

            {/* Preview */}
            <div>
              <div style={{ fontWeight: 500, marginBottom: 8, fontSize: "0.85rem" }}>ตัวอย่าง</div>
              <div style={{
                height: 220, borderRadius: 12, overflow: "hidden",
                border: "1px solid var(--line)", position: "relative",
                // เสมอมี gradient เป็น fallback
                background: "linear-gradient(145deg,#0f2044 0%,#1d4ed8 55%,#0ea5e9 100%)",
              }}>
                {/* รูปจาก URL */}
                {bgType === "url" && bgUrl && (
                  <img src={bgUrl} alt="bg preview"
                    style={{
                      position: "absolute", inset: 0,
                      width: "100%", height: "100%", objectFit: "cover",
                      opacity: imgStatus === "ok" ? 1 : 0,
                      transition: "opacity .3s",
                    }}
                    onLoad={() => setImgStatus("ok")}
                    onError={() => setImgStatus("error")}/>
                )}
                {/* สถานะ error */}
                {imgStatus === "error" && bgType === "url" && bgUrl && (
                  <div style={{
                    position: "absolute", top: "50%", left: "50%",
                    transform: "translate(-50%,-50%)", textAlign: "center",
                    color: "rgba(255,255,255,0.9)",
                  }}>
                    <div style={{ fontSize: "1.5rem", marginBottom: 6 }}>⚠️</div>
                    <div style={{ fontWeight: 600 }}>โหลดรูปไม่ได้</div>
                    <div style={{ fontSize: "0.78rem", opacity: 0.8, marginTop: 4 }}>URL ต้องเป็นลิงก์รูปภาพโดยตรง</div>
                  </div>
                )}
                {/* loading */}
                {imgStatus === "loading" && bgType === "url" && bgUrl && (
                  <div style={{
                    position: "absolute", top: "50%", left: "50%",
                    transform: "translate(-50%,-50%)", color: "rgba(255,255,255,0.7)",
                    fontSize: "0.85rem",
                  }}>กำลังโหลด…</div>
                )}
                {/* grid overlay */}
                <div style={{
                  position: "absolute", inset: 0,
                  backgroundImage: "linear-gradient(rgba(255,255,255,0.03) 1px, transparent 1px), linear-gradient(90deg,rgba(255,255,255,0.03) 1px, transparent 1px)",
                  backgroundSize: "40px 40px", pointerEvents: "none",
                }}/>
                {/* dark overlay เมื่อมีรูป */}
                {imgStatus === "ok" && (
                  <div style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,0.35)", pointerEvents: "none" }}/>
                )}
                <div style={{ position: "absolute", bottom: 16, left: 20, color: "#fff", pointerEvents: "none" }}>
                  <div style={{ fontWeight: 700, fontSize: "1.1rem" }}>ระบบจัดการอัจฉริยะ</div>
                  <div style={{ opacity: 0.7, fontSize: "0.8rem" }}>สำหรับห้องพักและที่จอดรถ</div>
                </div>
              </div>
            </div>

            {/* ข้อความบนหน้า Login */}
            <div style={{ borderTop: "1px solid var(--line)", paddingTop: 16 }}>
              <div style={{ fontWeight: 600, marginBottom: 12 }}>✏️ ข้อความบนหน้า Login</div>
              <div className="grid cols-2" style={{ gap: 12 }}>
                <Field label="ข้อความหลัก">
                  <input className="input" value={loginTitle}
                    onChange={e => setLoginTitle(e.target.value)}
                    placeholder="ระบบจัดการอัจฉริยะ"/>
                </Field>
                <Field label="ข้อความรอง">
                  <input className="input" value={loginSubtitle}
                    onChange={e => setLoginSubtitle(e.target.value)}
                    placeholder="สำหรับห้องพักและที่จอดรถ"/>
                </Field>
              </div>
            </div>

            <div className="row" style={{ justifyContent: "flex-end", gap: 10 }}>
              {bgSaved && <Pill tone="ok">✓ บันทึกแล้ว — มีผลทันทีที่ Login ครั้งถัดไป</Pill>}
              <button className="btn primary" onClick={saveBg} disabled={bgLoading}>
                <Icon name="check" size={16}/> {bgLoading ? "กำลังบันทึก…" : "บันทึก"}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ══ โปรไฟล์ ══ */}
      {tab === "profile" && (
        <div className="card" style={{ maxWidth: 480 }}>
          <div className="card-head"><h3>รูปโปรไฟล์ผู้ดูแลระบบ</h3></div>
          <div className="grid" style={{ gap: 20 }}>

            {/* Avatar display + upload */}
            <div className="row" style={{ gap: 20, alignItems: "center" }}>
              {/* รูปปัจจุบัน */}
              <div style={{
                width: 90, height: 90, borderRadius: "50%", flexShrink: 0,
                border: "3px solid var(--accent)", overflow: "hidden",
                background: "var(--surface-2)", display: "grid", placeItems: "center",
                position: "relative",
              }}>
                {adminAvatar
                  ? <img src={adminAvatar} style={{ width: "100%", height: "100%", objectFit: "cover" }} alt="avatar"/>
                  : <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="var(--ink-3)" strokeWidth="1.5"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/></svg>
                }
              </div>

              <div className="grid" style={{ gap: 10 }}>
                <label className="btn" style={{ cursor: "pointer", justifyContent: "center" }}>
                  <Icon name="camera" size={16}/> อัปโหลดรูปโปรไฟล์
                  <input type="file" accept="image/*" style={{ display: "none" }}
                    onChange={handleAvatarChange}/>
                </label>
                {adminAvatar && (
                  <button className="btn" style={{ color: "var(--danger)", borderColor: "var(--danger)", justifyContent: "center" }}
                    onClick={removeAvatar}>
                    <Icon name="trash" size={15}/> ลบรูปโปรไฟล์
                  </button>
                )}
                <div style={{ fontSize: "0.78rem", color: "var(--ink-3)", lineHeight: 1.5 }}>
                  รองรับ JPG, PNG, WebP<br/>ขนาดไม่เกิน 5MB · ปรับเป็น 160×160 อัตโนมัติ
                </div>
              </div>
            </div>

            {avatarSaved && (
              <div style={{ padding: "10px 14px", background: "var(--ok-soft)", borderRadius: 8,
                color: "var(--ok)", fontSize: "0.86rem", fontWeight: 500 }}>
                ✓ บันทึกรูปโปรไฟล์แล้ว — แสดงที่ sidebar ทันที
              </div>
            )}

            <div style={{ padding: "10px 14px", background: "var(--surface-2)", borderRadius: 8, fontSize: "0.82rem", color: "var(--ink-2)" }}>
              💡 รูปโปรไฟล์จะแสดงที่ด้านล่างซ้ายของ sidebar แทนตัวอักษร "A"
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.Settings = Settings;
