/* ============ First-run setup & store picker ============ */

const LOGO_SRC = (window.__resources && window.__resources.logoInk) || "assets/giraffe-logo-ink.png";
function Logo({ size = 36, variant = "tile" }) {
  if (variant === "plain") {
    return <img src={LOGO_SRC} alt="Giraffe" style={{ width: size, height: size, display: "block" }} />;
  }
  return (
    <div className="logo-tile" style={{ width: size, height: size, borderRadius: size * 0.28 }}>
      <img src={LOGO_SRC} alt="Giraffe" style={{ width: "74%", height: "74%" }} />
    </div>
  );
}

function SetupView({ onCloud, onLocal, error }) {
  const [text, setText] = useState("");
  const [err, setErr] = useState(error || "");
  const [busy, setBusy] = useState(false);

  const connect = async () => {
    setErr("");
    let cfg;
    try { cfg = Backend.parseLooseConfig(text); }
    catch (e) { setErr(e.message); return; }
    setBusy(true);
    try { await onCloud(cfg); }
    catch (e) { setErr(e.message || String(e)); setBusy(false); }
  };

  return (
    <div className="login-wrap" style={{ justifyContent: "flex-start", paddingTop: 48 }}>
      <Logo size={96} />
      <h1 style={{ marginTop: 14 }}>Giraffe 在庫管理</h1>
      <p className="lead">はじめに、データの保存先を設定します。</p>

      <div className="card" style={{ width: "100%", maxWidth: 440 }}>
        <div className="card-body">
          <div className="setup-badge">推奨・複数店舗/複数端末</div>
          <h3 style={{ margin: "8px 0 4px", fontSize: 17 }}>☁️ クラウド同期（Firebase）</h3>
          <p style={{ margin: "0 0 12px", fontSize: 13, color: "var(--ink-2)" }}>
            全スタッフのスマホが同じ在庫をリアルタイムで共有します。Aさんが更新した数字が、Bさんの画面にもすぐ反映されます。
          </p>
          <div className="field">
            <label>Firebase の firebaseConfig を貼り付け</label>
            <textarea
              value={text}
              onChange={e => setText(e.target.value)}
              placeholder={'{\n  apiKey: "AIza...",\n  authDomain: "xxx.firebaseapp.com",\n  projectId: "xxx",\n  ...\n}'}
              style={{ minHeight: 140, fontFamily: "ui-monospace, Menlo, monospace", fontSize: 12 }}
            />
            <div className="hint">Firebaseコンソール › プロジェクトの設定 › マイアプリ（ウェブ）に表示される設定です。手順は同梱の「セットアップ手順.md」を参照。</div>
          </div>
          {err && <div className="form-error">{err}</div>}
          <button className="btn primary block" onClick={connect} disabled={busy || !text.trim()}>
            {busy ? "接続中…" : "クラウドに接続する"}
          </button>
        </div>
      </div>

      <div className="card" style={{ width: "100%", maxWidth: 440, marginTop: 12 }}>
        <div className="card-body">
          <h3 style={{ margin: "0 0 4px", fontSize: 15 }}>📱 この端末だけで使う</h3>
          <p style={{ margin: "0 0 12px", fontSize: 12.5, color: "var(--ink-2)" }}>
            お試し用。データはこのスマホの中だけに保存され、他の端末とは共有されません。
          </p>
          <button className="btn secondary block" onClick={onLocal}>端末内モードで始める</button>
        </div>
      </div>
    </div>
  );
}

function StorePicker({ stores, onPick, user, onLogout }) {
  return (
    <div className="login-wrap" style={{ justifyContent: "flex-start", paddingTop: 56 }}>
      <Logo size={72} />
      <h1 style={{ marginTop: 12 }}>店舗を選択</h1>
      <p className="lead">{user.name} さん、作業する店舗を選んでください。</p>
      <div style={{ width: "100%", maxWidth: 440 }}>
        {stores.length === 0 && (
          <div className="empty-state">
            <div className="title">担当店舗がありません</div>
            <div className="sub">管理者に店舗の割り当てを依頼してください。</div>
          </div>
        )}
        {stores.map(s => <StoreTile key={s.id} store={s} onClick={() => onPick(s.id)} />)}
        <button className="btn ghost block" style={{ marginTop: 8 }} onClick={onLogout}>ログアウト</button>
      </div>
    </div>
  );
}

function StoreSwitcherSheet({ open, stores, currentId, onPick, onClose }) {
  return (
    <UIP.Sheet open={open} onClose={onClose} title="どの店舗の在庫を見ますか？">
      <p className="small-copy" style={{ marginTop: 0 }}>タップすると、その店舗の在庫に切り替わります。</p>
      {stores.map(s => <StoreTile key={s.id} store={s} active={s.id === currentId} onClick={() => onPick(s.id)} />)}
    </UIP.Sheet>
  );
}

function StoreTile({ store, active, onClick }) {
  const t = Store.storeType(store);
  return (
    <button className={"store-tile" + (active ? " active" : "")} onClick={onClick} style={{ "--st": t.color, "--st-soft": t.soft }}>
      <span className="store-tile-mark">{t.icon}</span>
      <span className="store-tile-body">
        <span className="store-tile-type">{t.label}</span>
        <span className="store-tile-name">{store.name}</span>
      </span>
      <span className="store-tile-arrow">{active ? "表示中 ✓" : "切替 ›"}</span>
    </button>
  );
}

/* Big, obvious "current store" bar with a switch button */
function StoreBar({ store, canSwitch, onSwitch }) {
  const t = Store.storeType(store);
  return (
    <div className="store-bar" style={{ "--st": t.color, "--st-soft": t.soft }}>
      <div className="store-bar-mark">{t.icon}</div>
      <div className="store-bar-body">
        <div className="store-bar-label">いま表示中の店舗（{t.label}）</div>
        <div className="store-bar-name">{store.name}</div>
      </div>
      {canSwitch && (
        <button className="store-bar-btn" onClick={onSwitch}>
          <span className="store-bar-btn-icn">⇄</span>
          <span>店舗を<br/>切替</span>
        </button>
      )}
    </div>
  );
}

/* Product thumbnail: real photo if available, else emoji */
function ItemThumb({ item, size = 56, radius = 14 }) {
  const [err, setErr] = useState(false);
  const src = item && item.image;
  return (
    <div className="item-thumb" style={{ width: size, height: size, borderRadius: radius, fontSize: size * 0.54 }}>
      {src && !err ? <img src={src} alt="" onError={() => setErr(true)} /> : <span>{(item && item.emoji) || "📦"}</span>}
    </div>
  );
}

window.Setup = { Logo, SetupView, StorePicker, StoreSwitcherSheet, StoreTile, StoreBar, ItemThumb };
