// ============================================================
// Farm Fresh — Manager (prices) & Developer (everything) panels
// ============================================================
const { useState: useStateA } = React;

// ---- Staff PIN gate: routes to manager or developer by PIN ----
function StaffGate({ onPass, onCancel }) {
  const [pin, setPin] = useStateA("");
  const [err, setErr] = useStateA(false);
  React.useEffect(() => {
    if (pin.length !== 4) return;
    const person = FF.findByPin(pin);
    if (person && (person.role === "manager" || person.role === "developer")) {
      onPass(person.role);
    } else {
      setErr(true); setTimeout(() => { setErr(false); setPin(""); }, 600);
    }
  }, [pin]);
  const onKey = (k) => setPin(p => { const nv = FF.applyKey(p, k, false); return nv.length > 4 ? p : nv; });
  return (
    <div className="scrim center" onClick={onCancel}>
      <div className="modal-card" onClick={(e) => e.stopPropagation()} style={{ padding:"26px 22px 22px", textAlign:"center" }}>
        <div style={{ fontSize:34, marginBottom:6 }}>🔐</div>
        <h2 style={{ margin:"0 0 2px", fontSize:22, fontWeight:800 }}>Staff Access</h2>
        <p style={{ margin:"0 0 18px", color:"var(--ink-soft)", fontSize:13.5, fontWeight:600 }}>Enter your Manager PIN</p>
        <div style={{ display:"flex", gap:12, justifyContent:"center", marginBottom:18,
          animation: err ? "ff-shake .5s" : "none" }}>
          {[0,1,2,3].map(i => (
            <span key={i} style={{ width:15, height:15, borderRadius:"50%",
              background: i < pin.length ? "var(--terra)" : "transparent",
              border:"2px solid " + (err ? "var(--terra)" : (i < pin.length ? "var(--terra)" : "var(--line)")) }} />
          ))}
        </div>
        <Keypad onKey={onKey} allowDecimal={false} />
        <button className="btn btn-ghost" onClick={onCancel} style={{ width:"100%", marginTop:14 }}>Cancel</button>
      </div>
    </div>
  );
}

// ---- shared footer credit ----
function CreditFooter() {
  return (
    <div style={{ textAlign:"center", marginTop:28, paddingTop:18, borderTop:"1.5px solid var(--line-soft)" }}>
      <div style={{ fontSize:13, fontWeight:800, color:"var(--green-ink)" }}>Farm Fresh</div>
      <div style={{ fontSize:11.5, fontWeight:700, color:"var(--ink-faint)" }}>licensed by <span style={{ color:"var(--terra-ink)" }}>C-us.com</span></div>
    </div>
  );
}

// ---- panel header ----
function PanelHead({ emoji, title, subtitle, onExit, accent }) {
  return (
    <div style={{ display:"flex", alignItems:"center", gap:12, padding:"16px 18px 12px",
      borderBottom:"1.5px solid var(--line)", flex:"none" }}>
      <span style={{ fontSize:26 }}>{emoji}</span>
      <div style={{ flex:1 }}>
        <h1 style={{ margin:0, fontSize:22, fontWeight:800, letterSpacing:"-.01em" }}>{title}</h1>
        <div style={{ fontSize:12.5, color:"var(--ink-faint)", fontWeight:600 }}>{subtitle}</div>
      </div>
      <button className={"btn " + (accent || "btn-green")} onClick={onExit} style={{ padding:"10px 18px", fontSize:15 }}>Done</button>
    </div>
  );
}

// ============================================================
// MANAGER — can ONLY change prices
// ============================================================
function ManagerScreen({ catalog, setCatalog, onExit }) {
  const update = (id, patch) => setCatalog(catalog.map(c => c.id === id ? { ...c, ...patch } : c));
  const cats = FF.orderedCategories(catalog);
  return (
    <div style={{ height:"100%", display:"flex", flexDirection:"column", background:"var(--bg)" }}>
      <PanelHead emoji="🏷️" title="Manager" subtitle="Update prices" onExit={onExit} />
      <div className="scroll" style={{ flex:1, padding:"16px 16px 30px" }}>
        <p style={{ margin:"0 0 16px", fontSize:13, color:"var(--ink-soft)", fontWeight:600, lineHeight:1.5 }}>
          Tap a price to update it. To add items, change names, or manage logins, ask the Developer.
        </p>
        {cats.map(cat => {
          const items = catalog.filter(i => (i.cat || "Other") === cat);
          if (!items.length) return null;
          return (
            <div key={cat} style={{ marginBottom:18 }}>
              <div className="cat-head"><span className="lbl">{cat}</span><span className="rule" /><span className="n">{items.length}</span></div>
              {items.map(item => (
                <div key={item.id} style={{ display:"flex", alignItems:"center", gap:12, padding:"10px 12px", marginBottom:9,
                  background:"var(--surface)", border:"1.5px solid var(--line)", borderRadius:14, boxShadow:"var(--shadow-card)" }}>
                  <span style={{ fontSize:30 }}>{item.emoji}</span>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontWeight:700, fontSize:15.5 }}>{item.name}</div>
                    <div className="mono" style={{ fontSize:11.5, color:"var(--ink-faint)", fontWeight:700, textTransform:"uppercase", letterSpacing:".04em" }}>
                      {item.unit === "lb" ? "per lb" : "each"}</div>
                  </div>
                  <div style={{ display:"flex", alignItems:"center", gap:4, background:"var(--bg-2)",
                    border:"1.5px solid var(--line)", borderRadius:11, padding:"6px 11px" }}>
                    <span className="mono" style={{ fontSize:17, fontWeight:700, color:"var(--ink-soft)" }}>$</span>
                    <input className="mono" inputMode="decimal" value={item.price}
                      onChange={(e) => update(item.id, { price: parseFloat(e.target.value) || 0 })}
                      style={{ width:62, border:"none", background:"transparent", fontSize:18, fontWeight:700,
                        color:"var(--green-ink)", textAlign:"right", outline:"none" }} />
                  </div>
                </div>
              ))}
            </div>
          );
        })}
        <CreditFooter />
      </div>
    </div>
  );
}

// ============================================================
// DEVELOPER — full control: items, categories, people, PINs
// ============================================================

// emoji picker
function EmojiPicker({ value, onPick, onClose }) {
  return (
    <div className="scrim center" onClick={onClose}>
      <div className="modal-card" onClick={(e) => e.stopPropagation()} style={{ padding:"18px 16px" }}>
        <h2 style={{ margin:"0 0 12px", fontSize:18, fontWeight:800 }}>Pick an icon</h2>
        <div style={{ display:"grid", gridTemplateColumns:"repeat(6,1fr)", gap:8, maxHeight:300, overflowY:"auto" }}>
          {FF.emojiChoices.map(e => (
            <button key={e} onClick={() => { onPick(e); onClose(); }}
              style={{ fontSize:30, padding:"8px 0", borderRadius:11,
                background: e === value ? "var(--green-bg)" : "var(--bg-2)",
                border:"1.5px solid " + (e === value ? "var(--green)" : "var(--line)") }}>{e}</button>
          ))}
        </div>
      </div>
    </div>
  );
}

// full item editor
function DevItem({ item, onChange, onDelete }) {
  const [pickEmoji, setPickEmoji] = useStateA(false);
  return (
    <div style={{ background:"var(--surface)", border:"1.5px solid var(--line)", borderRadius:16,
      padding:14, marginBottom:11, boxShadow:"var(--shadow-card)" }}>
      <div style={{ display:"flex", gap:11, alignItems:"flex-start" }}>
        <button onClick={() => setPickEmoji(true)}
          style={{ fontSize:34, width:58, height:58, borderRadius:13, background:"var(--bg-2)",
            border:"1.5px solid var(--line)", flex:"none" }}>{item.emoji}</button>
        <div style={{ flex:1, display:"flex", flexDirection:"column", gap:9 }}>
          <div className="adm-field">
            <label>Name</label>
            <input className="adm-input" value={item.name} onChange={(e) => onChange({ name:e.target.value })} />
          </div>
          <div style={{ display:"flex", gap:9 }}>
            <div className="adm-field" style={{ flex:1 }}>
              <label>Price ($)</label>
              <input className="adm-input mono" inputMode="decimal" value={item.price}
                onChange={(e) => onChange({ price: parseFloat(e.target.value) || 0 })} />
            </div>
            <div className="adm-field" style={{ flex:1.3 }}>
              <label>Sold by</label>
              <div className="seg">
                <button className={item.unit === "each" ? "on" : ""} onClick={() => onChange({ unit:"each" })}>Each</button>
                <button className={item.unit === "lb" ? "on" : ""} onClick={() => onChange({ unit:"lb" })}>Weight</button>
              </div>
            </div>
          </div>
          <div className="adm-field">
            <label>Category / tab</label>
            <input className="adm-input" list="ff-cats" value={item.cat || ""} placeholder="Produce"
              onChange={(e) => onChange({ cat: e.target.value || "Other" })} />
          </div>
        </div>
      </div>
      <button onClick={onDelete} style={{ marginTop:11, width:"100%", padding:"9px", borderRadius:10,
        color:"var(--terra-ink)", background:"var(--terra-bg)", fontWeight:700, fontSize:13.5 }}>
        Remove {item.name || "item"}
      </button>
      {pickEmoji && <EmojiPicker value={item.emoji} onPick={(e) => onChange({ emoji:e })} onClose={() => setPickEmoji(false)} />}
    </div>
  );
}

// person / login editor
function PersonRow({ person, dupPin, canDelete, onChange, onDelete }) {
  const roleColor = person.role === "developer" ? "var(--terra-ink)" : person.role === "manager" ? "var(--green-ink)" : "var(--ink-soft)";
  return (
    <div style={{ background:"var(--surface)", border:"1.5px solid var(--line)", borderRadius:16,
      padding:14, marginBottom:11, boxShadow:"var(--shadow-card)" }}>
      <div className="adm-field" style={{ marginBottom:9 }}>
        <label>Name</label>
        <input className="adm-input" value={person.name} onChange={(e) => onChange({ name:e.target.value })} />
      </div>
      <div style={{ display:"flex", gap:9, alignItems:"flex-end" }}>
        <div className="adm-field" style={{ flex:1 }}>
          <label>4-digit PIN</label>
          <input className="adm-input mono" inputMode="numeric" maxLength={4} value={person.pin}
            onChange={(e) => onChange({ pin: e.target.value.replace(/\D/g,"").slice(0,4) })}
            style={ dupPin ? { borderColor:"var(--terra)", color:"var(--terra-ink)" } : null } />
        </div>
        <div className="adm-field" style={{ flex:1.6 }}>
          <label>Role</label>
          <div className="seg">
            <button className={person.role === "cashier" ? "on" : ""} onClick={() => onChange({ role:"cashier" })}>Cashier</button>
            <button className={person.role === "manager" ? "on" : ""} onClick={() => onChange({ role:"manager" })}>Manager</button>
            <button className={person.role === "developer" ? "on" : ""} onClick={() => onChange({ role:"developer" })}>Dev</button>
          </div>
        </div>
      </div>
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginTop:10 }}>
        <span style={{ fontSize:12, fontWeight:700, color:roleColor }}>
          {dupPin ? "⚠ PIN already in use" : FF.roleLabel(person.role) + " access"}
        </span>
        {canDelete
          ? <button onClick={onDelete} style={{ fontSize:12.5, fontWeight:700, color:"var(--terra-ink)",
              background:"var(--terra-bg)", padding:"6px 12px", borderRadius:9 }}>Remove</button>
          : <span style={{ fontSize:11.5, color:"var(--ink-faint)", fontWeight:600 }}>last developer — kept</span>}
      </div>
    </div>
  );
}

// ---- owner tool: create a new customer stand + login ----
function NewStandModal({ onClose }) {
  const [standName, setStandName] = useStateA("");
  const [ownerName, setOwnerName] = useStateA("");
  const [email, setEmail] = useStateA("");
  const [password, setPassword] = useStateA("");
  const [busy, setBusy] = useStateA(false);
  const [err, setErr] = useStateA("");
  const [done, setDone] = useStateA(null);

  const gen = () => setPassword("farm" + Math.floor(1000 + Math.random() * 9000));

  const submit = async () => {
    if (!standName || !email || !password) { setErr("Fill in stand name, email, and a password."); return; }
    setBusy(true); setErr("");
    try {
      const r = await FF.createStand({ standName: standName, ownerName: ownerName, email: email, password: password });
      setDone({ standName: r.standName || standName, email: email, password: password });
    } catch (e) { setErr((e && e.message) || "Could not create the stand."); }
    finally { setBusy(false); }
  };

  return (
    <div className="scrim center" onClick={onClose} style={{ zIndex:90 }}>
      <div className="modal-card" onClick={(e) => e.stopPropagation()} style={{ padding:"22px 20px 20px", maxWidth:380 }}>
        {done ? (
          <div>
            <div style={{ fontSize:34, textAlign:"center", marginBottom:6 }}>🎉</div>
            <div style={{ fontWeight:800, fontSize:20, textAlign:"center", marginBottom:4 }}>Stand created!</div>
            <div style={{ fontSize:13.5, color:"var(--ink-soft)", fontWeight:600, textAlign:"center", marginBottom:16 }}>
              Give <b>{done.standName}</b> these to sign in at farmfresh.c-us.com:
            </div>
            <div style={{ background:"var(--bg-2)", border:"1.5px solid var(--line)", borderRadius:14, padding:"14px 16px", marginBottom:16 }}>
              <div style={{ fontSize:11.5, fontWeight:700, color:"var(--ink-faint)", textTransform:"uppercase", letterSpacing:".05em" }}>Email</div>
              <div className="mono" style={{ fontSize:16, fontWeight:700, marginBottom:10, wordBreak:"break-all" }}>{done.email}</div>
              <div style={{ fontSize:11.5, fontWeight:700, color:"var(--ink-faint)", textTransform:"uppercase", letterSpacing:".05em" }}>Temporary password</div>
              <div className="mono" style={{ fontSize:16, fontWeight:700 }}>{done.password}</div>
            </div>
            <button className="btn btn-green" onClick={onClose} style={{ width:"100%" }}>Done</button>
          </div>
        ) : (
          <div>
            <div style={{ fontWeight:800, fontSize:20, marginBottom:2 }}>New Customer Stand</div>
            <div style={{ fontSize:13, color:"var(--ink-soft)", fontWeight:600, marginBottom:16, lineHeight:1.45 }}>
              Sets up a separate stand with its own login and the starter produce list.
            </div>
            <div style={{ display:"flex", flexDirection:"column", gap:11 }}>
              <div className="adm-field"><label>Stand name</label>
                <input className="adm-input" value={standName} onChange={(e) => setStandName(e.target.value)} placeholder="Smith Family Produce" /></div>
              <div className="adm-field"><label>Owner's name</label>
                <input className="adm-input" value={ownerName} onChange={(e) => setOwnerName(e.target.value)} placeholder="John Smith" /></div>
              <div className="adm-field"><label>Their login email</label>
                <input className="adm-input" type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="john@email.com" /></div>
              <div className="adm-field"><label>Temporary password</label>
                <div style={{ display:"flex", gap:8 }}>
                  <input className="adm-input mono" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="at least 6 characters" style={{ flex:1 }} />
                  <button className="btn btn-soft" onClick={gen} style={{ padding:"0 14px", fontSize:13 }}>Make one</button>
                </div>
              </div>
            </div>
            {err && <div style={{ fontSize:13, fontWeight:700, color:"var(--terra-ink)", marginTop:12, lineHeight:1.4 }}>{err}</div>}
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1.4fr", gap:10, marginTop:16 }}>
              <button className="btn btn-ghost" onClick={onClose} disabled={busy}>Cancel</button>
              <button className="btn btn-green" onClick={submit} disabled={busy}>{busy ? "Creating…" : "Create stand"}</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function DeveloperScreen({ catalog, setCatalog, people, setPeople, onExit, me, onManageStands }) {
  const [showNewStand, setShowNewStand] = useStateA(false);
  const update = (id, patch) => setCatalog(catalog.map(c => c.id === id ? { ...c, ...patch } : c));
  const del = (id) => setCatalog(catalog.filter(c => c.id !== id));
  const add = () => setCatalog([...catalog, { id: FF.uuid(), name:"New Item", emoji:"🥗", price:1.00, unit:"each", cat:"Produce" }]);
  const [askReset, setAskReset] = useStateA(false);

  const devCount = people.filter(p => p.role === "developer").length;
  const pinCounts = {};
  people.forEach(p => { pinCounts[p.pin] = (pinCounts[p.pin] || 0) + 1; });
  const updPerson = (id, patch) => setPeople(people.map(p => p.id === id ? { ...p, ...patch } : p));
  const delPerson = (id) => setPeople(people.filter(p => p.id !== id));
  const addPerson = () => setPeople([...people, { id:"u_"+Date.now(), name:"New Person", pin:"0000", role:"cashier" }]);

  return (
    <div style={{ height:"100%", display:"flex", flexDirection:"column", background:"var(--bg)" }}>
      <PanelHead emoji="🧰" title="Developer" subtitle="Full control · C-us.com" onExit={onExit} accent="btn-terra" />
      <div className="scroll" style={{ flex:1, padding:"16px 16px 30px" }}>

        {/* ---- Rentals (platform owner only) ---- */}
        {me && me.isPlatformAdmin && (
          <div style={{ background:"var(--green-bg)", border:"1.5px solid var(--green)", borderRadius:16, padding:"14px 15px", marginBottom:22 }}>
            <div style={{ fontSize:15, fontWeight:800, color:"var(--green-ink)", marginBottom:2 }}>🏪 Rentals</div>
            <div style={{ fontSize:12.5, color:"var(--green-ink)", fontWeight:600, marginBottom:12, opacity:.85, lineHeight:1.45 }}>
              Set up a new customer's stand — their own private register, login, and starter prices.
            </div>
            <div style={{ display:"flex", gap:10 }}>
              <button className="btn btn-soft" onClick={() => onManageStands && onManageStands()} style={{ flex:1 }}>🏪&nbsp; My Stands</button>
              <button className="btn btn-green" onClick={() => setShowNewStand(true)} style={{ flex:1 }}>＋&nbsp; New Stand</button>
            </div>
          </div>
        )}

        {/* ---- People & logins ---- */}
        <h2 style={{ margin:"0 0 4px", fontSize:15, fontWeight:800, textTransform:"uppercase", letterSpacing:".05em", color:"var(--ink-soft)" }}>
          People &amp; Logins ({people.length})</h2>
        <p style={{ margin:"0 0 12px", fontSize:12.5, color:"var(--ink-faint)", fontWeight:600, lineHeight:1.5 }}>
          Set or reset anyone's PIN here if they lose it. Cashier runs the register · Manager can change prices · Developer controls everything.
        </p>
        {people.map(p => (
          <PersonRow key={p.id} person={p} dupPin={pinCounts[p.pin] > 1}
            canDelete={!(p.role === "developer" && devCount <= 1)}
            onChange={(patch) => updPerson(p.id, patch)} onDelete={() => delPerson(p.id)} />
        ))}
        <button className="btn btn-soft" onClick={addPerson} style={{ width:"100%", marginTop:4, marginBottom:26 }}>
          ＋&nbsp; Add a person
        </button>

        {/* ---- Items ---- */}
        <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:10 }}>
          <h2 style={{ margin:0, fontSize:15, fontWeight:800, textTransform:"uppercase", letterSpacing:".05em", color:"var(--ink-soft)" }}>
            Items ({catalog.length})</h2>
          <button onClick={() => setAskReset(true)} style={{ fontSize:12.5, fontWeight:700, color:"var(--ink-faint)", textDecoration:"underline" }}>Reset to starter</button>
        </div>
        {catalog.map(item => (
          <DevItem key={item.id} item={item} onChange={(p) => update(item.id, p)} onDelete={() => del(item.id)} />
        ))}
        <datalist id="ff-cats">
          {FF.orderedCategories(catalog).map(c => <option key={c} value={c} />)}
        </datalist>
        <button className="btn btn-soft" onClick={add} style={{ width:"100%", marginTop:4 }}>
          ＋&nbsp; Add new item
        </button>

        <CreditFooter />
      </div>

      {askReset && (
        <ConfirmModal
          title="Reset all items?"
          message="Every item goes back to the starter list. Price and menu changes will be lost."
          confirmLabel="Reset" cancelLabel="Keep mine" tone="terra"
          onConfirm={() => { setCatalog(FF.defaultCatalog().map(c => ({ ...c, id: FF.uuid() }))); setAskReset(false); }}
          onCancel={() => setAskReset(false)} />
      )}
      {showNewStand && <NewStandModal onClose={() => setShowNewStand(false)} />}
    </div>
  );
}

// ============================================================
// MY STANDS — platform owner: see rentals, billing, manage logins
// ============================================================
function StandCard({ stand, onChanged }) {
  const [open, setOpen] = useStateA(false);
  const [busy, setBusy] = useStateA(false);
  const [msg, setMsg] = useStateA("");
  const [email, setEmail] = useStateA(stand.ownerEmail || "");
  const [pw, setPw] = useStateA("");
  const [name, setName] = useStateA(stand.name || "");
  const [rent, setRent] = useStateA(stand.rentAmount || 0);
  const [due, setDue] = useStateA(stand.nextDue || "");
  const [confirmDel, setConfirmDel] = useStateA(false);

  const status = FF.billStatus(stand);
  const si = {
    overdue: { label: "OVERDUE",    bg: "var(--terra)",     fg: "#fff" },
    due:     { label: "DUE TODAY",  bg: "var(--terra-bg)",  fg: "var(--terra-ink)" },
    paid:    { label: "PAID",       bg: "var(--green-bg)",  fg: "var(--green-ink)" },
    none:    { label: "NO BILL",    bg: "var(--bg-2)",      fg: "var(--ink-faint)" },
  }[status];

  const run = (action, payload, okMsg) => {
    setBusy(true); setMsg("");
    FF.manageStand(action, payload)
      .then(() => { setMsg(okMsg || "Saved ✓"); setBusy(false); onChanged(); })
      .catch(e => { setMsg((e && e.message) || "Error"); setBusy(false); });
  };
  const gen = () => setPw("farm" + Math.floor(1000 + Math.random() * 9000));

  return (
    <div style={{ background:"var(--surface)", border:"1.5px solid var(--line)", borderRadius:16, padding:14, marginBottom:12, boxShadow:"var(--shadow-card)" }}>
      <div style={{ display:"flex", alignItems:"flex-start", gap:10 }}>
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ fontWeight:800, fontSize:16 }}>{stand.name}</div>
          <div style={{ fontSize:12.5, color:"var(--ink-soft)", fontWeight:600, wordBreak:"break-all" }}>
            {(stand.ownerName || "—") + " · " + (stand.ownerEmail || "no email")}
          </div>
        </div>
        <span style={{ fontSize:10.5, fontWeight:800, color:si.fg, background:si.bg, padding:"3px 9px", borderRadius:999, whiteSpace:"nowrap" }}>{si.label}</span>
      </div>
      <div style={{ display:"flex", alignItems:"center", gap:10, marginTop:10 }}>
        <div style={{ flex:1, fontSize:12, color:"var(--ink-faint)", fontWeight:700 }}>
          Rent {FF.money(stand.rentAmount)}{stand.nextDue ? " · due " + FF.prettyDate(stand.nextDue) : " · no due date"}
        </div>
        <button className="btn btn-green" disabled={busy} onClick={() => run("markPaid", { standId: stand.standId }, "Marked paid ✓")}
          style={{ padding:"9px 14px", fontSize:13.5 }}>Mark paid</button>
      </div>
      <button onClick={() => setOpen(o => !o)} style={{ marginTop:10, fontSize:13, fontWeight:700, color:"var(--ink-soft)" }}>{open ? "▲ Hide manage" : "▾ Manage"}</button>

      {open && (
        <div style={{ marginTop:10, borderTop:"1.5px solid var(--line-soft)", paddingTop:12, display:"flex", flexDirection:"column", gap:12 }}>
          <div className="adm-field"><label>Stand name</label>
            <div style={{ display:"flex", gap:8 }}>
              <input className="adm-input" value={name} onChange={e => setName(e.target.value)} style={{ flex:1 }} />
              <button className="btn btn-soft" disabled={busy} onClick={() => run("rename", { standId: stand.standId, name: name }, "Renamed ✓")} style={{ padding:"0 14px", fontSize:13 }}>Save</button>
            </div>
          </div>
          <div className="adm-field"><label>Login email</label>
            <div style={{ display:"flex", gap:8 }}>
              <input className="adm-input" type="email" value={email} onChange={e => setEmail(e.target.value)} style={{ flex:1 }} />
              <button className="btn btn-soft" disabled={busy || !stand.ownerId} onClick={() => run("updateEmail", { userId: stand.ownerId, email: email }, "Email changed ✓")} style={{ padding:"0 14px", fontSize:13 }}>Save</button>
            </div>
          </div>
          <div className="adm-field"><label>Reset password</label>
            <div style={{ display:"flex", gap:8 }}>
              <input className="adm-input mono" value={pw} onChange={e => setPw(e.target.value)} placeholder="new password" style={{ flex:1, minWidth:0 }} />
              <button className="btn btn-soft" onClick={gen} style={{ padding:"0 11px", fontSize:12.5 }}>Make</button>
              <button className="btn btn-soft" disabled={busy || !stand.ownerId || pw.length < 6} onClick={() => run("resetPassword", { userId: stand.ownerId, password: pw }, "Password reset ✓")} style={{ padding:"0 11px", fontSize:13 }}>Set</button>
            </div>
          </div>
          <div style={{ display:"flex", gap:8 }}>
            <div className="adm-field" style={{ flex:1 }}><label>Rent ($/mo)</label>
              <input className="adm-input mono" inputMode="decimal" value={rent} onChange={e => setRent(e.target.value)} /></div>
            <div className="adm-field" style={{ flex:1.3 }}><label>Next due</label>
              <input className="adm-input" type="date" value={due || ""} onChange={e => setDue(e.target.value)} /></div>
          </div>
          <button className="btn btn-soft" disabled={busy} onClick={() => run("setBilling", { standId: stand.standId, rentAmount: parseFloat(rent) || 0, nextDue: due || null }, "Billing saved ✓")}>Save billing</button>

          {!confirmDel ? (
            <button onClick={() => setConfirmDel(true)} style={{ fontSize:13, fontWeight:700, color:"var(--terra-ink)", background:"var(--terra-bg)", padding:"10px", borderRadius:11 }}>Delete this stand</button>
          ) : (
            <div style={{ display:"flex", gap:8, alignItems:"center" }}>
              <span style={{ fontSize:12.5, fontWeight:700, color:"var(--terra-ink)", flex:1 }}>Delete {stand.name}? Can't undo.</span>
              <button className="btn btn-ghost" onClick={() => setConfirmDel(false)} style={{ padding:"8px 12px", fontSize:13 }}>No</button>
              <button className="btn btn-terra" disabled={busy} onClick={() => run("delete", { standId: stand.standId, ownerId: stand.ownerId }, "Deleted ✓")} style={{ padding:"8px 12px", fontSize:13 }}>Delete</button>
            </div>
          )}
          {msg && <div style={{ fontSize:12.5, fontWeight:700, color:"var(--green-ink)" }}>{msg}</div>}
        </div>
      )}
    </div>
  );
}

function MyStandsScreen({ onExit }) {
  const [stands, setStands] = useStateA(null);
  const [err, setErr] = useStateA("");
  const load = () => {
    setErr("");
    FF.manageStand("list").then(r => setStands(r.stands || [])).catch(e => { setErr((e && e.message) || "Couldn't load stands."); setStands([]); });
  };
  React.useEffect(() => { load(); }, []);
  const count = stands ? stands.length : 0;
  const owed = stands ? stands.filter(s => FF.billStatus(s) === "overdue" || FF.billStatus(s) === "due").reduce((a, s) => a + (s.rentAmount || 0), 0) : 0;

  return (
    <div style={{ height:"100%", display:"flex", flexDirection:"column", background:"var(--bg)" }}>
      <PanelHead emoji="🏪" title="My Stands" subtitle={count + " rented" + (owed > 0 ? " · " + FF.money(owed) + " owed" : "")} onExit={onExit} accent="btn-terra" />
      <div className="scroll" style={{ flex:1, padding:"16px 16px 30px" }}>
        {stands === null && <div style={{ textAlign:"center", padding:40, color:"var(--ink-faint)", fontWeight:700 }}>Loading…</div>}
        {err && <div style={{ color:"var(--terra-ink)", fontWeight:700, fontSize:13.5, marginBottom:12, lineHeight:1.4 }}>{err}</div>}
        {stands && stands.length === 0 && !err && (
          <div style={{ textAlign:"center", padding:"44px 20px", color:"var(--ink-faint)" }}>
            <div style={{ fontSize:40, marginBottom:8 }}>🏪</div>
            <div style={{ fontWeight:700 }}>No customer stands yet</div>
            <div style={{ fontSize:13, marginTop:3 }}>Use “New Customer Stand” to add one.</div>
          </div>
        )}
        {stands && stands.map(s => <StandCard key={s.standId} stand={s} onChanged={load} />)}
      </div>
    </div>
  );
}

Object.assign(window, { StaffGate, ManagerScreen, DeveloperScreen, MyStandsScreen });
