// Economy: the catalog, like Game Manager's Economy > Catalogs. A save bumps the catalog version, and
// every running game is told to refetch it.

const LAR_EMPTY_ITEM = {
  itemId: "", catalog: "Main", itemClass: "", displayName: "", description: "", price: "",
  purchasable: false, uses: "", bundleItems: "", bundleGold: "", tags: "", customData: "",
};

function larItemForm(item) {
  return {
    ...LAR_EMPTY_ITEM,
    ...item,
    price: item.price == null ? "" : String(item.price),
    uses: item.uses == null ? "" : String(item.uses),
    bundleGold: item.bundleGold == null ? "" : String(item.bundleGold),
    bundleItems: (item.bundleItems || []).join(", "),
    tags: (item.tags || []).join(", "),
    customData: item.customData || "",
  };
}

const larList = (text) => text.split(",").map(s => s.trim()).filter(Boolean);
const larNum = (text) => (String(text).trim() === "" ? null : Math.floor(Number(text)));

function LarItemEditor({ item, isNew, onClose, onSaved }) {
  const [form, setForm] = React.useState(() => larItemForm(item));
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);
  const editable = can("catalog.edit");
  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.type === "checkbox" ? e.target.checked : e.target.value }));

  const save = async () => {
    const id = form.itemId.trim();
    if (!id) { setError("Item id is required"); return; }
    setBusy(true); setError(null);
    try {
      await larApi(`catalog/${encodeURIComponent(form.catalog.trim() || "Main")}/${encodeURIComponent(id)}`, {
        method: "PUT",
        body: {
          itemClass: form.itemClass, displayName: form.displayName, description: form.description,
          price: larNum(form.price), purchasable: form.purchasable, uses: larNum(form.uses),
          bundleItems: larList(form.bundleItems), bundleGold: larNum(form.bundleGold),
          tags: larList(form.tags), customData: form.customData || null,
        },
      });
      onSaved();
    } catch (e) { setError(e.message); setBusy(false); }
  };

  const remove = async () => {
    if (!confirm(`Delete ${form.catalog}/${form.itemId} from the catalog? Players keep any they own.`)) return;
    setBusy(true);
    try { await larApi(`catalog/${encodeURIComponent(form.catalog)}/${encodeURIComponent(form.itemId)}`, { method: "DELETE" }); onSaved(); }
    catch (e) { setError(e.message); setBusy(false); }
  };

  const freeWarning = form.purchasable && larNum(form.price) === 0;

  return (
    <>
      <div className="scrim" onClick={onClose}/>
      <div className="drawer" style={{width:"min(560px, 100vw)"}}>
        <div className="drawer-head">
          <div className="h-stack gap-10">
            <LarItemMark id={form.itemId || "new"} name={form.displayName || form.itemId || "+"} size={34}/>
            <div><div style={{fontWeight:600, fontSize:13.5}}>{isNew ? "New item" : form.displayName || form.itemId}</div><div className="tiny muted mono">{form.catalog}{form.itemId ? ` / ${form.itemId}` : ""}</div></div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="close" size={14}/></button>
        </div>
        <div className="drawer-body">
          <div className="lar-grid-form">
            <div className="field"><label>Item id</label><input className="input mono" value={form.itemId} disabled={!isNew || !editable} onChange={set("itemId")} placeholder="COWBOY_HAT"/></div>
            <div className="field"><label>Catalog</label>
              <select className="input" value={form.catalog} disabled={!isNew || !editable} onChange={set("catalog")}><option>Main</option><option>Items</option></select>
            </div>
            <div className="field"><label>Display name</label><input className="input" value={form.displayName} disabled={!editable} onChange={set("displayName")}/></div>
            <div className="field"><label>Item class</label><input className="input mono" value={form.itemClass} disabled={!editable} onChange={set("itemClass")} placeholder="HEAD, FACE, BODY, MONSTER…"/></div>
            <div className="field full"><label>Description</label><input className="input" value={form.description} disabled={!editable} onChange={set("description")}/></div>
            <div className="field"><label>Price (GD, empty = not sold for gold)</label><input className="input mono" type="number" min="0" value={form.price} disabled={!editable} onChange={set("price")}/></div>
            <div className="field"><label>Uses per purchase (consumables only)</label><input className="input mono" type="number" min="1" value={form.uses} disabled={!editable} onChange={set("uses")} placeholder="durable"/></div>
            <label className="lar-check full"><input type="checkbox" checked={form.purchasable} disabled={!editable} onChange={set("purchasable")}/> For sale in game (players can buy it with gold)</label>
            {freeWarning && <div className="lar-note full" style={{background:"var(--warn-soft)", color:"var(--warn)"}}>Free and for sale: any player can take this for nothing. Only do this for items meant to be free.</div>}
            <div className="field full"><label>Bundle contents (item ids, comma separated)</label><input className="input mono" value={form.bundleItems} disabled={!editable} onChange={set("bundleItems")}/></div>
            <div className="field"><label>Bundle gold</label><input className="input mono" type="number" min="0" value={form.bundleGold} disabled={!editable} onChange={set("bundleGold")}/></div>
            <div className="field"><label>Tags (comma separated)</label><input className="input" value={form.tags} disabled={!editable} onChange={set("tags")}/></div>
            <div className="field full"><label>Custom data</label><textarea className="input" value={form.customData} disabled={!editable} onChange={set("customData")}/></div>
          </div>
          <LarError error={error}/>
        </div>
        {editable && (
          <div className="drawer-foot">
            <button className="btn btn-sm btn-accent" disabled={busy} onClick={save}>{isNew ? "Create item" : "Save"}</button>
            {!isNew && <button className="btn btn-sm btn-danger" disabled={busy} onClick={remove}>Delete</button>}
            <span className="tiny muted">Saving tells every running game to refetch the catalog.</span>
          </div>
        )}
      </div>
    </>
  );
}

function LarCatalogPage() {
  const { data, error, loading, reload } = useLarLoad(() => larApi("catalog"), []);
  const [catalog, setCatalog] = React.useState("all");
  const [query, setQuery] = React.useState("");
  const [onlySale, setOnlySale] = React.useState(false);
  const [editing, setEditing] = React.useState(null);

  const items = (data?.items || []).filter(it =>
    (catalog === "all" || it.catalog === catalog) &&
    (!onlySale || it.purchasable) &&
    (!query || it.itemId.toLowerCase().includes(query.toLowerCase()) || (it.displayName || "").toLowerCase().includes(query.toLowerCase()) || (it.itemClass || "").toLowerCase().includes(query.toLowerCase())));

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Economy</h1>
          <p className="page-subtitle">The catalog (version {data?.version ?? "…"}). Prices are in gold (GD). Only items marked for sale can be bought by players; everything else arrives through grants, quests or bundles.</p>
        </div>
        {can("catalog.edit") && <div className="page-head-actions"><button className="btn btn-sm btn-accent" onClick={() => setEditing({ item: { ...LAR_EMPTY_ITEM }, isNew: true })}><Icon name="plus" size={12}/> New item</button></div>}
      </div>

      <div className="card card-flush">
        <div className="toolbar">
          {[["all", "All"], ["Main", "Main"], ["Items", "Items"]].map(([id, lab]) => <button key={id} className="filter-pill" data-active={catalog === id} onClick={() => setCatalog(id)}>{lab}</button>)}
          <label className="lar-check" style={{marginLeft:8}}><input type="checkbox" checked={onlySale} onChange={e => setOnlySale(e.target.checked)}/> For sale only</label>
          <div style={{flex:1}}/>
          <div className="search-field" style={{maxWidth:300}}><Icon name="search" size={14}/><input placeholder="Search id, name or class…" value={query} onChange={e => setQuery(e.target.value)}/></div>
          <span className="tiny muted">{items.length} items</span>
        </div>
        {error && <div className="tiny" style={{color:"var(--danger)", padding:"0 16px 12px"}}>{error}</div>}
        <table className="tbl">
          <thead><tr><th>Item</th><th>Class</th><th>Catalog</th><th style={{textAlign:"right"}}>Price</th><th>Status</th></tr></thead>
          <tbody>
            {items.map(it => (
              <tr key={`${it.catalog}/${it.itemId}`} className="lar-row-click" onClick={() => setEditing({ item: it, isNew: false })}>
                <td><div className="p-row"><LarItemMark id={it.itemId} name={it.displayName || it.itemId}/><div><div className="p-name">{it.displayName || it.itemId}</div><div className="tiny muted mono">{it.itemId}</div></div></div></td>
                <td className="mono tiny">{it.itemClass || "—"}</td>
                <td className="tiny">{it.catalog}</td>
                <td className="mono" style={{textAlign:"right"}}>{it.price == null ? "—" : fmt.num(it.price)}</td>
                <td>
                  {it.purchasable ? <span className="tag tag-success">For sale</span> : <span className="tag">Grant only</span>}
                  {it.bundleItems?.length > 0 && <span className="tag tag-info" style={{marginLeft:4}}>Bundle · {it.bundleItems.length}</span>}
                  {it.uses != null && <span className="tag" style={{marginLeft:4}}>×{it.uses}</span>}
                </td>
              </tr>
            ))}
            {!loading && items.length === 0 && <tr><td colSpan={5}><div className="empty"><h3>No items</h3><p>{data?.items?.length ? "Nothing matches." : "The catalog is empty. Import it from PlayFab on the Migration page."}</p></div></td></tr>}
            {loading && <tr><td colSpan={5}><div className="empty"><h3>Loading…</h3></div></td></tr>}
          </tbody>
        </table>
      </div>

      {editing && <LarItemEditor item={editing.item} isNew={editing.isNew} onClose={() => setEditing(null)} onSaved={() => { setEditing(null); reload(); }}/>}
    </div>
  );
}

window.LarCatalogPage = LarCatalogPage;
