/* Relay — POS / New manual (phone) order */
function POSScreen({ branch, onPlace, onCancel }) {
  const { CATALOG, FULFILLMENT, createManualOrder } = window.RelayData;
  const [type, setType] = React.useState("food");
  const [cat, setCat] = React.useState("all");
  const [search, setSearch] = React.useState("");
  const [cart, setCart] = React.useState([]); // {id,name,price,qty,mods:[]}
  const [customer, setCustomer] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [area, setArea] = React.useState("");
  const [fulfillment, setFulfillment] = React.useState("Pickup");
  const [note, setNote] = React.useState("");

  const menu = CATALOG.filter((i) => i.type === type && i.available);
  const categories = React.useMemo(() => ["all", ...[...new Set(menu.map((i) => i.category))].sort()], [type]);
  React.useEffect(() => { setCat("all"); setFulfillment(FULFILLMENT[type][0]); }, [type]);

  const shown = menu.filter((i) => (cat === "all" || i.category === cat) &&
    (!search.trim() || i.name.toLowerCase().includes(search.trim().toLowerCase())));

  function addToCart(item) {
    setCart((prev) => {
      const ex = prev.find((c) => c.id === item.id && c.mods.length === 0);
      if (ex) return prev.map((c) => c === ex ? { ...c, qty: c.qty + 1 } : c);
      return [...prev, { id: item.id, name: item.name, price: item.price, qty: 1, mods: [] }];
    });
  }
  function setQty(idx, delta) {
    setCart((prev) => prev.map((c, i) => i === idx ? { ...c, qty: Math.max(0, c.qty + delta) } : c).filter((c) => c.qty > 0));
  }
  function toggleMod(idx, mod) {
    setCart((prev) => prev.map((c, i) => i === idx ? { ...c, mods: c.mods.includes(mod) ? c.mods.filter((m) => m !== mod) : [...c.mods, mod] } : c));
  }

  const subtotal = cart.reduce((s, c) => s + c.price * c.qty, 0);
  const count = cart.reduce((s, c) => s + c.qty, 0);
  const canPlace = cart.length > 0;

  function place() {
    if (!canPlace) return;
    const order = createManualOrder({
      type, customer: customer.trim(), phone: phone.trim(), area: area.trim(),
      fulfillment, note: note.trim(),
      items: cart.map((c) => ({ name: c.name, qty: c.qty, price: c.price, sku: null, mods: c.mods })),
      branchId: branch.id,
    });
    onPlace(order);
  }

  const catModsFor = (id) => (CATALOG.find((c) => c.id === id) || {}).mods || [];

  return (
    <div style={{ display: "flex", height: "100%", minHeight: 0 }}>
      {/* LEFT: catalog picker */}
      <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", borderRight: "1px solid var(--border)" }}>
        <div style={{ padding: "18px 22px 14px", borderBottom: "1px solid var(--border)", display: "flex", flexDirection: "column", gap: 13 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <button onClick={onCancel} style={{ width: 34, height: 34, borderRadius: 8, border: "1px solid var(--border)", background: "var(--surface)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--text-2)" }}><I.x size={17} /></button>
            <div>
              <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: "-.01em" }}>Yeni sipariş</div>
              <div style={{ fontSize: 12.5, color: "var(--text-3)" }}>Telefon / Gel-Al · {branch.name}</div>
            </div>
            <div style={{ flex: 1 }} />
            <Segmented options={[{ id: "food", label: "Yemek" }, { id: "retail", label: "Perakende" }]} value={type} onChange={setType} />
          </div>
          <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
            <div style={{ position: "relative", flex: 1 }}>
              <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--text-3)" }}><I.search size={16} /></span>
              <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Eklenecek ürünleri ara…" style={{ width: "100%", padding: "9px 12px 9px 36px", borderRadius: "var(--radius-sm)", border: "1px solid var(--border)", background: "var(--surface-2)", fontSize: 13, outline: "none" }} />
            </div>
          </div>
          <div style={{ display: "flex", gap: 7, flexWrap: "wrap" }}>
            {categories.map((c) => (
              <button key={c} onClick={() => setCat(c)} style={{ padding: "5px 12px", fontSize: 12, fontWeight: 600, borderRadius: 999, border: "1px solid " + (cat === c ? "var(--graphite)" : "var(--border)"), background: cat === c ? "var(--graphite)" : "var(--surface)", color: cat === c ? "#fff" : "var(--text-2)" }}>{c === "all" ? "Tümü" : c}</button>
            ))}
          </div>
        </div>
        <div style={{ flex: 1, overflowY: "auto", padding: 18 }}>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(170px, 1fr))", gap: 12 }}>
            {shown.map((it) => (
              <button key={it.id} onClick={() => addToCart(it)} style={{
                textAlign: "left", background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--radius)",
                padding: 14, boxShadow: "var(--shadow-sm)", cursor: "pointer", display: "flex", flexDirection: "column", gap: 8, transition: "all .12s", minHeight: 104,
              }} onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--new)"; e.currentTarget.style.transform = "translateY(-1px)"; }} onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--border)"; e.currentTarget.style.transform = "none"; }}>
                <span style={{ fontSize: 10, fontWeight: 600, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".04em" }}>{it.category}</span>
                <span style={{ fontWeight: 600, fontSize: 13.5, lineHeight: 1.3, flex: 1 }}>{it.name}</span>
                <span style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                  <span className="mono" style={{ fontSize: 15, fontWeight: 600 }}>AED {it.price}</span>
                  <span style={{ width: 24, height: 24, borderRadius: 7, background: "var(--new-bg)", color: "var(--new)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><I.plus size={15} /></span>
                </span>
              </button>
            ))}
            {shown.length === 0 && <div style={{ gridColumn: "1/-1", textAlign: "center", color: "var(--text-3)", padding: 40, fontSize: 13 }}>Ürün bulunamadı.</div>}
          </div>
        </div>
      </div>

      {/* RIGHT: cart / ticket */}
      <div style={{ width: 380, flexShrink: 0, display: "flex", flexDirection: "column", background: "var(--surface)" }}>
        <div style={{ padding: "16px 18px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 9, fontWeight: 700, fontSize: 15 }}>
            <span style={{ width: 30, height: 30, borderRadius: 8, background: "#475569", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><I.phone size={16} /></span>
            Sipariş Fişi
          </div>
          <span className="mono" style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-2)", background: "var(--surface-3)", borderRadius: 999, padding: "2px 10px" }}>{count} ürün</span>
        </div>

        {/* cart items */}
        <div style={{ flex: 1, overflowY: "auto", padding: cart.length ? "12px 16px" : 0 }}>
          {cart.length === 0 ? (
            <div style={{ height: "100%", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", color: "var(--text-3)", gap: 10, padding: 30, textAlign: "center" }}>
              <span style={{ width: 48, height: 48, borderRadius: 12, background: "var(--surface-3)", display: "flex", alignItems: "center", justifyContent: "center" }}><I.receipt size={22} /></span>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--text-2)" }}>Henüz ürün eklenmedi</div>
              <div style={{ fontSize: 12.5 }}>Sipariş oluşturmak için soldaki ürünlere dokunun.</div>
            </div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {cart.map((c, idx) => {
                const mods = catModsFor(c.id);
                return (
                  <div key={idx} style={{ border: "1px solid var(--border)", borderRadius: 9, padding: "10px 12px", background: "var(--surface-2)" }}>
                    <div style={{ display: "flex", alignItems: "flex-start", gap: 8 }}>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontWeight: 600, fontSize: 13.5 }}>{c.name}</div>
                        <div className="mono" style={{ fontSize: 12, color: "var(--text-3)", marginTop: 1 }}>AED {c.price} adet</div>
                      </div>
                      <span className="mono" style={{ fontWeight: 600, fontSize: 13.5 }}>{fmtMoney(c.price * c.qty)}</span>
                    </div>
                    {mods.length > 0 && (
                      <div style={{ display: "flex", flexWrap: "wrap", gap: 5, marginTop: 8 }}>
                        {mods.map((m) => {
                          const on = c.mods.includes(m);
                          return <button key={m} onClick={() => toggleMod(idx, m)} style={{ fontSize: 11, fontWeight: 600, padding: "3px 8px", borderRadius: 999, border: "1px solid " + (on ? "var(--new)" : "var(--border-strong)"), background: on ? "var(--new-bg)" : "var(--surface)", color: on ? "var(--new)" : "var(--text-2)" }}>{on ? "✓ " : "+ "}{m}</button>;
                        })}
                      </div>
                    )}
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 9 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 0, border: "1px solid var(--border-strong)", borderRadius: 7, overflow: "hidden" }}>
                        <button onClick={() => setQty(idx, -1)} style={{ width: 28, height: 28, border: "none", background: "var(--surface)", color: "var(--text)", fontSize: 16, display: "flex", alignItems: "center", justifyContent: "center" }}>–</button>
                        <span className="mono" style={{ width: 30, textAlign: "center", fontWeight: 600, fontSize: 13.5 }}>{c.qty}</span>
                        <button onClick={() => setQty(idx, 1)} style={{ width: 28, height: 28, border: "none", background: "var(--surface)", color: "var(--text)", fontSize: 16, display: "flex", alignItems: "center", justifyContent: "center" }}>+</button>
                      </div>
                      <button onClick={() => setQty(idx, -c.qty)} style={{ border: "none", background: "transparent", color: "var(--text-3)", fontSize: 12, fontWeight: 600 }}>Kaldır</button>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* customer details + place */}
        <div style={{ borderTop: "1px solid var(--border)", padding: 16, display: "flex", flexDirection: "column", gap: 10, background: "var(--surface-2)" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
            <Field label="Müşteri" value={customer} onChange={setCustomer} placeholder="Adı" />
            <Field label="Telefon" value={phone} onChange={setPhone} placeholder="+90 5…" mono />
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
            <div>
              <FieldLabel>Teslimat Şekli</FieldLabel>
              <div style={{ display: "flex", gap: 5 }}>
                {FULFILLMENT[type].map((f) => (
                  <button key={f} onClick={() => setFulfillment(f)} style={{ flex: 1, padding: "7px 4px", fontSize: 11.5, fontWeight: 600, borderRadius: 7, border: "1px solid " + (fulfillment === f ? "var(--graphite)" : "var(--border-strong)"), background: fulfillment === f ? "var(--graphite)" : "var(--surface)", color: fulfillment === f ? "#fff" : "var(--text-2)" }}>{f}</button>
                ))}
              </div>
            </div>
            <Field label="Bölge" value={area} onChange={setArea} placeholder="Teslimat bölgesi" />
          </div>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "6px 2px 2px" }}>
            <span style={{ fontSize: 14, fontWeight: 600 }}>Toplam</span>
            <span className="mono" style={{ fontSize: 20, fontWeight: 700 }}>AED {fmtMoney(subtotal)}</span>
          </div>
          <Btn kind="primary" full onClick={place} style={{ padding: "12px", fontSize: 14, opacity: canPlace ? 1 : 0.45, pointerEvents: canPlace ? "auto" : "none" }}>
            <I.check size={17} />Siparişi ver · mutfağa gönder
          </Btn>
        </div>
      </div>
    </div>
  );
}

function FieldLabel({ children }) {
  return <label style={{ fontSize: 10.5, fontWeight: 600, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".04em", display: "block", marginBottom: 5 }}>{children}</label>;
}
function Field({ label, value, onChange, placeholder, mono }) {
  return (
    <div>
      <FieldLabel>{label}</FieldLabel>
      <input value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} className={mono ? "mono" : ""} style={{ width: "100%", padding: "8px 10px", borderRadius: 7, border: "1px solid var(--border-strong)", background: "var(--surface)", fontSize: 13, outline: "none" }} />
    </div>
  );
}

Object.assign(window, { POSScreen });
