/* ============ Admin Tab (multi-store, backend-driven) ============ */

const EMOJI_CHOICES = [
  "🧴","🧼","💧","🫧","💦","🥛","🪥","☁️","💈","🪒","🧻","🧽","🪞","🧷",
  "🥤","🧃","🍺","🍵","☕","⚡","🍦","🍧","🍨","🍬","🍫","🍙",
  "🧢","🧣","👕","🩴","🏷️","🎁","🛍️","📦"
];
const intOr0 = v => Math.max(0, parseInt(v || "0", 10) || 0);

/* ---- Item editor ---- */
function ItemEditor({ open, initial, onClose, onSave }) {
  const blank = () => ({ id: Store.uid("itm"), emoji: "🧴", name: "", unit: "本", stock: 0, threshold: 5, cat: "", image: "" });
  const imgRef = useRef(null);
  const onImg = async e => {
    const f = e.target.files && e.target.files[0]; e.target.value = "";
    if (!f) return;
    try { const d = await Gemini.fileToDataUrl(f, 1280, 0.85); set("image", await Gemini.makeThumb(d, 320, 0.8)); } catch (err) {}
  };
  const [form, setForm] = useState(blank);
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  useEffect(() => { if (open) setForm(initial ? { cat: "", image: "", ...initial } : blank()); }, [open, initial]);
  if (!open) return null;
  const isNew = !initial;
  return (
    <UIP.Sheet open={open} onClose={onClose} title={isNew ? "商品を追加" : "商品を編集"}>
      <div className="field">
        <label>商品画像</label>
        <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
          <Setup.ItemThumb item={form} size={72} radius={14} />
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            <button type="button" className="btn sm secondary" onClick={() => imgRef.current && imgRef.current.click()}>📷 写真を選ぶ／撮る</button>
            {form.image && <button type="button" className="btn sm ghost" onClick={() => set("image", "")}>画像を外す（アイコン表示）</button>}
          </div>
          <input ref={imgRef} type="file" accept="image/*" style={{ display: "none" }} onChange={onImg} />
        </div>
      </div>
      <div className="field">
        <label>アイコン</label>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
          {EMOJI_CHOICES.map(e => (
            <button key={e} type="button" onClick={() => set("emoji", e)} className={"emoji-pick" + (form.emoji === e ? " on" : "")}>{e}</button>
          ))}
        </div>
      </div>
      <div className="field">
        <label>商品名</label>
        <input type="text" value={form.name} onChange={e => set("name", e.target.value)} placeholder="例: シャンプー / ポカリスエット" />
      </div>
      <div className="field">
        <label>カテゴリ（任意）</label>
        <input type="text" list="cat-options" value={form.cat || ""} onChange={e => set("cat", e.target.value)} placeholder="例: ドリンク / アイス / グッズ" />
        <datalist id="cat-options">
          {["アメニティ","ドリンク","アイス","食品","物販","グッズ"].map(c => <option key={c} value={c} />)}
        </datalist>
      </div>
      <div className="row-3">
        <div className="field"><label>単位</label><input type="text" value={form.unit} onChange={e => set("unit", e.target.value)} /></div>
        <div className="field">
          <label>{isNew ? "初期在庫" : "現在庫"}</label>
          <input type="number" inputMode="numeric" value={form.stock} disabled={!isNew} onChange={e => set("stock", intOr0(e.target.value))} />
        </div>
        <div className="field"><label>発注閾値</label><input type="number" inputMode="numeric" value={form.threshold} onChange={e => set("threshold", intOr0(e.target.value))} /></div>
      </div>
      {!isNew && <div className="hint" style={{ margin: "-4px 2px 12px" }}>在庫数の変更は「入庫登録」またはカウントで行います（同時更新の整合性を保つため）。</div>}
      <div className="row-2">
        <button className="btn secondary" onClick={onClose}>キャンセル</button>
        <button className="btn primary" onClick={() => {
          if (!form.name.trim()) return;
          const out = { id: form.id, emoji: form.emoji, name: form.name.trim(), unit: form.unit.trim() || "個", threshold: form.threshold, cat: (form.cat || "").trim(), image: form.image || "" };
          if (isNew) out.stock = form.stock;
          onSave(out, isNew);
        }}>保存</button>
      </div>
    </UIP.Sheet>
  );
}

/* ---- Restock ---- */
function RestockSheet({ open, items, onClose, onRestock }) {
  const [itemId, setItemId] = useState("");
  const [qty, setQty] = useState(10);
  const [busy, setBusy] = useState(false);
  useEffect(() => { if (open) { setItemId(items[0]?.id || ""); setQty(10); setBusy(false); } }, [open]);
  if (!open) return null;
  const item = items.find(i => i.id === itemId);
  return (
    <UIP.Sheet open={open} onClose={onClose} title="入庫を登録">
      <div className="field">
        <label>商品</label>
        <select value={itemId} onChange={e => setItemId(e.target.value)}>
          {items.map(i => <option key={i.id} value={i.id}>{i.emoji} {i.name}（現在 {i.stock}{i.unit}）</option>)}
        </select>
      </div>
      <div className="field">
        <label>入庫数量</label>
        <input type="number" inputMode="numeric" value={qty} onChange={e => setQty(intOr0(e.target.value))} />
      </div>
      <div className="row-2">
        <button className="btn secondary" onClick={onClose}>キャンセル</button>
        <button className="btn primary" disabled={busy || !item || qty <= 0} onClick={async () => { setBusy(true); await onRestock(item.id, qty); setBusy(false); }}>
          {busy ? "保存中…" : "入庫を確定"}
        </button>
      </div>
    </UIP.Sheet>
  );
}

/* ---- Staff editor (with store assignment) ---- */
function StaffEditor({ open, initial, stores, onClose, onSave }) {
  const blank = () => ({ id: Store.uid("u"), name: "", pin: "", role: "staff", storeIds: [] });
  const [form, setForm] = useState(blank);
  useEffect(() => { if (open) setForm(initial ? { storeIds: [], ...initial } : blank()); }, [open, initial]);
  if (!open) return null;
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const toggleStore = id => set("storeIds", form.storeIds.includes(id) ? form.storeIds.filter(x => x !== id) : [...form.storeIds, id]);
  return (
    <UIP.Sheet open={open} onClose={onClose} title={initial ? "スタッフを編集" : "スタッフを追加"}>
      <div className="field"><label>名前</label><input type="text" value={form.name} onChange={e => set("name", e.target.value)} /></div>
      <div className="field">
        <label>4桁PIN</label>
        <input type="text" inputMode="numeric" maxLength={4} value={form.pin} onChange={e => set("pin", e.target.value.replace(/\D/g, "").slice(0, 4))} />
        <div className="hint">同じPINは登録できません。</div>
      </div>
      <div className="field">
        <label>権限</label>
        <div className="role-switch" style={{ background: "#fff8ea" }}>
          <button className={form.role === "staff" ? "active" : ""} onClick={() => set("role", "staff")}>スタッフ</button>
          <button className={form.role === "admin" ? "active" : ""} onClick={() => set("role", "admin")}>管理者</button>
        </div>
      </div>
      {form.role === "staff" && (
        <div className="field">
          <label>担当店舗</label>
          <div className="chip-row">
            <button type="button" className={"chip" + (form.storeIds.length === 0 ? " on" : "")} onClick={() => set("storeIds", [])}>全店舗</button>
            {stores.map(s => (
              <button type="button" key={s.id} className={"chip" + (form.storeIds.includes(s.id) ? " on" : "")} onClick={() => toggleStore(s.id)}>{s.name}</button>
            ))}
          </div>
          <div className="hint">未選択（全店舗）の場合、すべての店舗を操作できます。管理者は常に全店舗。</div>
        </div>
      )}
      <div className="row-2">
        <button className="btn secondary" onClick={onClose}>キャンセル</button>
        <button className="btn primary" onClick={() => {
          if (!form.name.trim() || form.pin.length !== 4) return;
          onSave({ ...form, name: form.name.trim(), storeIds: form.role === "admin" ? [] : form.storeIds });
        }}>保存</button>
      </div>
    </UIP.Sheet>
  );
}

/* ---- Store editor ---- */
function StoreEditor({ open, initial, stores, onClose, onSave }) {
  const [name, setName] = useState("");
  const [webhook, setWebhook] = useState("");
  const [copyFrom, setCopyFrom] = useState("__default");
  const [type, setType] = useState("hotel");
  const [busy, setBusy] = useState(false);
  useEffect(() => {
    if (open) { setName(initial?.name || ""); setWebhook(initial?.slackWebhook || ""); setType(initial?.type || "hotel"); setCopyFrom(initial ? "" : "__default"); setBusy(false); }
  }, [open, initial]);
  if (!open) return null;
  return (
    <UIP.Sheet open={open} onClose={onClose} title={initial ? "店舗を編集" : "店舗を追加"}>
      <div className="field">
        <label>店舗の種類</label>
        <div className="type-pick">
          {Object.entries(Store.STORE_TYPES).map(([k, t]) => (
            <button key={k} type="button" className={"type-opt" + (type === k ? " on" : "")} style={{ "--st": t.color, "--st-soft": t.soft }}
              onClick={() => { setType(k); if (!initial) setCopyFrom(k === "sauna" ? "__sauna" : "__default"); }}>
              <span className="type-icn">{t.icon}</span><span>{t.label}</span>
            </button>
          ))}
        </div>
      </div>
      <div className="field"><label>店舗名</label><input type="text" value={name} onChange={e => setName(e.target.value)} placeholder={type === "sauna" ? "例: サウナGiraffe 南天神" : "例: Giraffe 博多"} /></div>
      {!initial && (
        <div className="field">
          <label>商品マスタの初期値</label>
          <select value={copyFrom} onChange={e => setCopyFrom(e.target.value)}>
            <option value="__sauna">サウナ標準（ドリンク・アイス・グッズ24品目・写真付き）</option>
            <option value="__default">ホテル標準（アメニティ12品目）</option>
            {stores.map(s => <option key={s.id} value={s.id}>「{s.name}」の商品構成をコピー</option>)}
            <option value="__empty">空（あとで登録）</option>
          </select>
          <div className="hint">商品名・単位・閾値をコピーします。在庫数は0から始まります。</div>
        </div>
      )}
      <div className="field">
        <label>この店舗のSlack Webhook（任意）</label>
        <input type="url" value={webhook} onChange={e => setWebhook(e.target.value.trim())} placeholder="未入力なら共通のWebhookへ通知" />
      </div>
      <div className="row-2">
        <button className="btn secondary" onClick={onClose}>キャンセル</button>
        <button className="btn primary" disabled={busy || !name.trim()} onClick={async () => { setBusy(true); try { await onSave({ name: name.trim(), slackWebhook: webhook, copyFrom, type }); } finally { setBusy(false); } }}>
          {busy ? "保存中…" : "保存"}
        </button>
      </div>
    </UIP.Sheet>
  );
}

/* ---- Admin main ---- */
function AdminView({ backend, meta, items, storeId, currentUser, pushToast, onLogout, onDisconnect }) {
  const { confirm, node: confirmNode } = UIP.useConfirm();
  const [itemEditor, setItemEditor] = useState({ open: false, initial: null });
  const [restock, setRestock] = useState(false);
  const [staffEditor, setStaffEditor] = useState({ open: false, initial: null });
  const [storeEditor, setStoreEditor] = useState({ open: false, initial: null });
  const [settings, setSettings] = useState(meta.settings);
  useEffect(() => setSettings(meta.settings), [meta.settings]);
  const store = meta.stores.find(s => s.id === storeId);

  const run = async (fn, okMsg) => {
    try { await fn(); if (okMsg) pushToast(okMsg, "ok"); return true; }
    catch (e) { console.error(e); pushToast("保存に失敗: " + (e.message || e), "err"); return false; }
  };

  /* settings */
  const saveSettings = () => run(() => backend.saveMeta({ settings: { ...settings } }), "設定を保存しました（全端末に反映）");
  const testSlack = () => run(() => Slack.sendSlackTest(storeId), "Slackへテスト送信しました ✅");

  /* items */
  const saveItem = async (item, isNew) => {
    if (await run(() => backend.upsertItem(storeId, item), "商品を保存しました")) setItemEditor({ open: false, initial: null });
  };
  const deleteItem = async it => {
    if (!await confirm({ title: "商品を削除", body: `「${store?.name}」から「${it.name}」を削除します。`, danger: true, okLabel: "削除する" })) return;
    run(() => backend.deleteItem(storeId, it.id), "削除しました");
  };
  const doRestock = async (itemId, qty) => {
    const ok = await run(() => backend.restock(storeId, itemId, qty), `+${qty} 入庫しました`);
    if (ok) setRestock(false);
  };

  /* staff */
  const saveStaff = async u => {
    if (meta.staff.find(x => x.id !== u.id && x.pin === u.pin)) { pushToast("そのPINは他のスタッフが使用中です", "err"); return; }
    const staff = meta.staff.some(x => x.id === u.id) ? meta.staff.map(x => x.id === u.id ? u : x) : [...meta.staff, u];
    if (!staff.some(x => x.role === "admin")) { pushToast("管理者は最低1名必要です", "err"); return; }
    if (await run(() => backend.saveMeta({ staff }), "スタッフを保存しました")) setStaffEditor({ open: false, initial: null });
  };
  const deleteStaff = async u => {
    if (u.id === currentUser.id) { pushToast("ログイン中の自分は削除できません", "err"); return; }
    if (u.role === "admin" && meta.staff.filter(x => x.role === "admin").length <= 1) { pushToast("管理者は最低1名必要です", "err"); return; }
    if (!await confirm({ title: "スタッフを削除", body: `「${u.name}」を削除します。`, danger: true, okLabel: "削除する" })) return;
    run(() => backend.saveMeta({ staff: meta.staff.filter(x => x.id !== u.id) }), "削除しました");
  };

  /* stores */
  const saveStore = async ({ name, slackWebhook, copyFrom, type }) => {
    const init = storeEditor.initial;
    if (init) {
      const stores = meta.stores.map(s => s.id === init.id ? { ...s, name, slackWebhook, type } : s);
      if (await run(() => backend.saveMeta({ stores }), "店舗を更新しました")) setStoreEditor({ open: false, initial: null });
      return;
    }
    let tmpl = [];
    if (copyFrom === "__default") tmpl = Store.DEFAULT_ITEMS;
    else if (copyFrom === "__sauna") tmpl = Store.SAUNA_ITEMS;
    else if (copyFrom !== "__empty") {
      // copy item master from an existing store (current store's items are already loaded)
      tmpl = copyFrom === storeId ? items : ((await backend.exportAll()).stores[copyFrom]?.items || []);
    }
    const newItems = tmpl.map(it => ({ id: it.id, emoji: it.emoji, name: it.name, unit: it.unit, threshold: it.threshold, stock: 0, cat: it.cat || "", image: it.image || "" }));
    const st = { id: Store.uid("store"), name, slackWebhook, type };
    if (await run(() => backend.createStore(st, newItems), `「${name}」を追加しました`)) setStoreEditor({ open: false, initial: null });
  };
  const deleteStore = async s => {
    if (meta.stores.length <= 1) { pushToast("店舗は最低1つ必要です", "err"); return; }
    if (s.id === storeId) { pushToast("表示中の店舗は削除できません。先に他店舗へ切り替えてください", "err"); return; }
    if (!await confirm({ title: "店舗を削除", body: `「${s.name}」の在庫・履歴をすべて削除します。元に戻せません。`, danger: true, okLabel: "削除する" })) return;
    run(() => backend.deleteStore(s.id), "店舗を削除しました");
  };

  /* data */
  const doExport = async () => {
    try {
      const data = await backend.exportAll();
      const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
      const url = URL.createObjectURL(blob);
      const d = new Date(), p = n => String(n).padStart(2, "0");
      const a = document.createElement("a");
      a.href = url; a.download = `giraffe-inventory-${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}.json`;
      document.body.appendChild(a); a.click(); a.remove();
      setTimeout(() => URL.revokeObjectURL(url), 1000);
      pushToast("エクスポートしました", "ok");
    } catch (e) { pushToast("エクスポート失敗: " + e.message, "err"); }
  };
  const importRef = useRef(null);
  const onImportFile = async e => {
    const file = e.target.files && e.target.files[0]; e.target.value = "";
    if (!file) return;
    try {
      const json = JSON.parse(await file.text());
      if (!await confirm({ title: "インポート実行", body: "同じIDのデータは上書きされます。よろしいですか？", danger: true, okLabel: "インポート" })) return;
      await backend.importAll(json);
      pushToast("インポートしました", "ok");
    } catch (err) { pushToast("インポート失敗: " + (err.message || err), "err"); }
  };
  const migrateLocal = async () => {
    if (!await confirm({ title: "端末内データをクラウドへ", body: "この端末に保存されている以前のデータ（在庫・履歴・スタッフ）をクラウドに取り込みます。", okLabel: "取り込む" })) return;
    run(async () => backend.importAll(await Backend.createLocalBackend().exportAll()), "クラウドに取り込みました");
  };

  const copyShare = async () => {
    const cfg = backend.mode === "cloud" ? JSON.parse(localStorage.getItem("giraffe_firebase_config") || "null") || (window.GIRAFFE_CONFIG && window.GIRAFFE_CONFIG.firebase) : null;
    if (!cfg) return;
    const link = Backend.shareLink(cfg);
    try { await navigator.clipboard.writeText(link); pushToast("接続リンクをコピーしました", "ok"); }
    catch (e) { prompt("このリンクを他の端末で開いてください", link); }
  };
  const baked = !!(window.GIRAFFE_CONFIG && window.GIRAFFE_CONFIG.firebase);

  return (
    <div className="view">
      <h2>管理</h2>
      <p className="lead">表示中: <b>{store?.name}</b></p>

      {meta.staff.some(u => u.pin === "0000" || u.pin === "1111") && (
        <div className="alert-banner" style={{ alignItems: "flex-start" }}>
          <span className="icn">🔒</span>
          <span>
            初期PIN（0000 / 1111）のままのスタッフがいます：
            <b>{meta.staff.filter(u => u.pin === "0000" || u.pin === "1111").map(u => u.name).join("、")}</b>
            <br /><span style={{ fontWeight: 500 }}>下の「スタッフ」から ✏️ を押してPINを変更してください。</span>
          </span>
        </div>
      )}

      {/* Connection */}
      <div className="admin-section">
        <h3>データ同期</h3>
        <div className="card"><div className="card-body">
          {backend.mode === "cloud" ? (
            <>
              <div className="sync-status ok"><span className="dot" />クラウド同期中 <span className="mono">{backend.projectId}</span></div>
              <p className="small-copy">全端末・全店舗のデータがリアルタイムで共有されています。在庫の増減はトランザクションで処理されるため、同時に更新しても数がずれません。</p>
              {!baked && (
                <>
                  <button className="btn secondary block" onClick={copyShare}>🔗 他の端末用の接続リンクをコピー</button>
                  <div className="hint" style={{ marginTop: 6 }}>スタッフのスマホでこのリンクを一度開くだけで同じデータに接続されます。</div>
                </>
              )}
              {Backend.hasLocalData() && (
                <button className="btn secondary block" style={{ marginTop: 10 }} onClick={migrateLocal}>📥 この端末の旧データをクラウドへ取り込む</button>
              )}
              {!baked && <button className="btn ghost block" style={{ marginTop: 6 }} onClick={onDisconnect}>接続設定をやり直す</button>}
            </>
          ) : (
            <>
              <div className="sync-status warn"><span className="dot" />端末内モード（この端末のみ）</div>
              <p className="small-copy">現在のデータはこのスマホだけに保存されています。複数スタッフ・複数店舗で使うにはクラウド同期に切り替えてください。</p>
              <button className="btn primary block" onClick={onDisconnect}>☁️ クラウド同期に切り替える</button>
            </>
          )}
        </div></div>
      </div>

      {/* Stores */}
      <div className="admin-section">
        <h3>店舗（{meta.stores.length}）</h3>
        {meta.stores.map(s => (
          <div key={s.id} className="list-row">
            <div className="emoji">{Store.storeType(s).icon}</div>
            <div className="body" onClick={() => setStoreEditor({ open: true, initial: s })}>
              <div className="name">{s.name} {s.id === storeId && <span className="me-tag">表示中</span>}</div>
              <div className="sub">{Store.storeType(s).label} ・ Slack: {s.slackWebhook ? "店舗専用" : "共通"}</div>
            </div>
            <button className="icon-btn" onClick={() => setStoreEditor({ open: true, initial: s })} aria-label="編集">✏️</button>
            <button className="icon-btn" onClick={() => deleteStore(s)} aria-label="削除">🗑️</button>
          </div>
        ))}
        <button className="btn secondary block" onClick={() => setStoreEditor({ open: true, initial: null })}>＋ 店舗を追加</button>
      </div>

      {/* Items */}
      <div className="admin-section">
        <h3>商品マスタ — {store?.name}（{items.length}品）</h3>
        {items.map(it => (
          <div key={it.id} className="list-row">
            <Setup.ItemThumb item={it} size={40} radius={10} />
            <div className="body" onClick={() => setItemEditor({ open: true, initial: it })}>
              <div className="name">{it.name}</div>
              <div className="sub">{it.cat ? it.cat + " ・ " : ""}現在 {it.stock}{it.unit} ・ 閾値 {it.threshold}{it.unit}</div>
            </div>
            <button className="icon-btn" onClick={() => setItemEditor({ open: true, initial: it })} aria-label="編集">✏️</button>
            <button className="icon-btn" onClick={() => deleteItem(it)} aria-label="削除">🗑️</button>
          </div>
        ))}
        <button className="btn secondary block" onClick={() => setItemEditor({ open: true, initial: null })}>＋ 商品を追加</button>
      </div>

      {/* Restock */}
      <div className="admin-section">
        <h3>入庫登録 — {store?.name}</h3>
        <div className="card"><div className="card-body">
          <p className="small-copy" style={{ marginTop: 0 }}>納品分をまとめて手動で入庫できます。写真から入庫する場合はカウント画面で「入庫」を選んでください。</p>
          <button className="btn primary block" onClick={() => setRestock(true)}>📦 入庫を登録する</button>
        </div></div>
      </div>

      {/* Staff */}
      <div className="admin-section">
        <h3>スタッフ（{meta.staff.length}名・全店舗共通）</h3>
        {meta.staff.map(u => {
          const names = u.role === "admin" || !u.storeIds?.length ? "全店舗" : u.storeIds.map(id => meta.stores.find(s => s.id === id)?.name).filter(Boolean).join("、");
          return (
            <div key={u.id} className="list-row">
              <div className="emoji">{u.role === "admin" ? "👑" : "👤"}</div>
              <div className="body" onClick={() => setStaffEditor({ open: true, initial: u })}>
                <div className="name">{u.name} {u.id === currentUser.id && <span className="me-tag">自分</span>}</div>
                <div className="sub">{u.role === "admin" ? "管理者" : "スタッフ"} ・ {names}</div>
              </div>
              <button className="icon-btn" onClick={() => setStaffEditor({ open: true, initial: u })} aria-label="編集">✏️</button>
              <button className="icon-btn" onClick={() => deleteStaff(u)} aria-label="削除">🗑️</button>
            </div>
          );
        })}
        <button className="btn secondary block" onClick={() => setStaffEditor({ open: true, initial: null })}>＋ スタッフを追加</button>
      </div>

      {/* Integrations */}
      <div className="admin-section">
        <h3>連携設定（全店舗共通）</h3>
        <div className="card"><div className="card-body">
          <div className="field">
            <label>ブランド名（通知タイトル等）</label>
            <input type="text" value={settings.hotelName || ""} onChange={e => setSettings(s => ({ ...s, hotelName: e.target.value }))} />
          </div>
          <div className="field">
            <label>Gemini APIキー</label>
            <input type="password" value={settings.geminiKey || ""} placeholder="AIza..." onChange={e => setSettings(s => ({ ...s, geminiKey: e.target.value.trim() }))} />
            <div className="hint">取得: <a href="https://aistudio.google.com/app/apikey" target="_blank" rel="noopener">Google AI Studio</a>{backend.mode === "cloud" ? " ・ 保存すると全端末で使えます。" : ""}</div>
          </div>
          <div className="field">
            <label>Geminiモデル</label>
            <select value={settings.geminiModel || "gemini-3-flash-preview"} onChange={e => setSettings(s => ({ ...s, geminiModel: e.target.value }))}>
              <option value="gemini-3-flash-preview">gemini-3-flash-preview（推奨・高速）</option>
              <option value="gemini-3.1-pro-preview">gemini-3.1-pro-preview（高精度）</option>
              <option value="gemini-2.5-flash">gemini-2.5-flash（旧・一部キーで廃止済み）</option>
            </select>
          </div>
          <div className="field">
            <label>共通 Slack Webhook URL</label>
            <input type="url" value={settings.slackWebhook || ""} placeholder="https://hooks.slack.com/services/..." onChange={e => setSettings(s => ({ ...s, slackWebhook: e.target.value.trim() }))} />
            <div className="hint">店舗専用のWebhookが未設定の店舗はこちらへ通知されます。</div>
          </div>
          <div className="row-2">
            <button className="btn secondary" onClick={testSlack} disabled={!(store?.slackWebhook || settings.slackWebhook)}>Slackテスト送信</button>
            <button className="btn primary" onClick={saveSettings}>設定を保存</button>
          </div>
        </div></div>
      </div>

      {/* Data */}
      <div className="admin-section">
        <h3>データ管理</h3>
        <div className="card"><div className="card-body">
          <div className="row-2">
            <button className="btn secondary" onClick={doExport}>⬇️ エクスポート</button>
            <button className="btn secondary" onClick={() => importRef.current && importRef.current.click()}>⬆️ インポート</button>
          </div>
          <input ref={importRef} type="file" accept="application/json,.json" style={{ display: "none" }} onChange={onImportFile} />
          <div className="hint" style={{ marginTop: 6 }}>全店舗のバックアップ（JSON）。旧バージョンのエクスポートも読み込めます。</div>
        </div></div>
      </div>

      <div className="admin-section">
        <button className="btn secondary block" onClick={onLogout}>ログアウト</button>
      </div>

      <ItemEditor open={itemEditor.open} initial={itemEditor.initial} onClose={() => setItemEditor({ open: false, initial: null })} onSave={saveItem} />
      <RestockSheet open={restock} items={items} onClose={() => setRestock(false)} onRestock={doRestock} />
      <StaffEditor open={staffEditor.open} initial={staffEditor.initial} stores={meta.stores} onClose={() => setStaffEditor({ open: false, initial: null })} onSave={saveStaff} />
      <StoreEditor open={storeEditor.open} initial={storeEditor.initial} stores={meta.stores} onClose={() => setStoreEditor({ open: false, initial: null })} onSave={saveStore} />
      {confirmNode}
    </div>
  );
}

function StaffSettingsView({ meta, storeId, currentUser, backend, onLogout }) {
  const store = meta.stores.find(s => s.id === storeId);
  return (
    <div className="view">
      <h2>設定</h2>
      <div className="card"><div className="card-body">
        <div className="field">
          <label>ログイン中</label>
          <div style={{ fontWeight: 700, fontSize: 16 }}>👤 {currentUser.name}</div>
          <div className="hint">スタッフ</div>
        </div>
        <div className="field"><label>店舗</label><div>{store?.name}</div></div>
        <div className="field">
          <label>データ同期</label>
          {backend.mode === "cloud"
            ? <div className="sync-status ok"><span className="dot" />クラウド同期中</div>
            : <div className="sync-status warn"><span className="dot" />端末内モード</div>}
        </div>
        <div className="hint" style={{ marginBottom: 12 }}>商品・スタッフ・店舗・連携設定の変更には管理者権限が必要です。</div>
        <button className="btn secondary block" onClick={onLogout}>ログアウト</button>
      </div></div>
    </div>
  );
}

window.AdminView = AdminView;
window.StaffSettingsView = StaffSettingsView;
