/* global React, Icon, euro, FEEST, Button */

/* Lookups op basis van de ACTUELE FEEST.menu (niet vastleggen bij laden: de serverconfig
   wordt pas ná het laden ingeladen, dus een snapshot zou verouderde prijzen geven). */
function allItems() { return (FEEST.menu || []).flatMap((c) => c.items); }
function itemById() { return Object.fromEntries(allItems().map((i) => [i.id, i])); }

/* build cart lines + total from order state */
function buildOrder(state) {
  const lines = [];
  allItems().forEach((it) => {
    const q = state.order.items[it.id] || 0;
    if (q > 0) lines.push({ key: it.id, name: it.name, qty: q, price: it.price, total: q * it.price });
  });
  if (state.order.tokens > 0) {
    lines.push({ key: "tokens", name: "Drinkmuntjes", sub: euro(FEEST.tokenPrice) + " per muntje", qty: state.order.tokens, price: FEEST.tokenPrice, total: state.order.tokens * FEEST.tokenPrice, kind: "token" });
  }
  if (state.order.donation > 0) {
    lines.push({ key: "donation", name: "Bijdrage Ouderraad (OR)", qty: 1, price: state.order.donation, total: state.order.donation, kind: "donation" });
  }
  // Korting: kindermenu gratis voor kinderen op school (1 per school-kind).
  const { freeCount, discount } = window.kidsMenuDiscount(state.kids, state.order.items, FEEST);
  if (discount > 0) {
    lines.push({ key: "kidskorting", name: "Kindermenu (kinderen op school)", sub: freeCount + "× gratis", qty: freeCount, price: 0, total: -discount, kind: "discount" });
  }
  // Servicebijdrage: vaste transactiekosten (iDEAL), alleen als er iets te betalen is.
  const subtotal = lines.reduce((s, l) => s + l.total, 0);
  const fee = subtotal > 0 ? window.serviceFee(FEEST, subtotal) : 0;
  if (fee > 0) {
    lines.push({ key: "servicefee", name: "Servicebijdrage", sub: "transactiekosten", qty: 1, price: fee, total: fee, kind: "fee" });
  }
  const total = lines.reduce((s, l) => s + l.total, 0);
  const count = lines.filter((l) => l.kind !== "donation" && l.kind !== "discount" && l.kind !== "fee").reduce((s, l) => s + l.qty, 0);
  return { lines, total, count, subtotal, fee };
}

/* ---------- Cart sidebar ---------- */
function Cart({ state, onPrimary, primaryLabel = "Naar overzicht", primaryDisabled, footnote, desktop }) {
  const { lines, total, count } = buildOrder(state);
  return (
    <aside className={"cart" + (desktop ? " cart--desktop" : "")}>
      <div className="card">
        <h3><Icon name="bag" size={20} /> Je mandje</h3>
        {lines.length === 0 ? (
          <div className="empty">
            <Icon name="bag" size={28} /><br />
            Nog niets toegevoegd.<br />Kies hierboven je eten en drinken.
          </div>
        ) : (
          <React.Fragment>
            <div className="cart-lines">
              {lines.map((l) => (
                <div className="cart-line" key={l.key}>
                  <span className="ql">{(l.kind === "donation" || l.kind === "discount" || l.kind === "fee") ? "" : l.qty + "×"}</span>
                  <span className="nm">{l.name}{l.sub && <small>{l.sub}</small>}</span>
                  <span className="pr tnum">{euro(l.total)}</span>
                </div>
              ))}
            </div>
            <div className="cart-total">
              <span className="t-lbl">Totaal</span>
              <span className="t-val tnum">{euro(total)}</span>
            </div>
          </React.Fragment>
        )}
        {onPrimary && (
          <div style={{ marginTop: 18 }}>
            <Button block iconRight="right" onClick={onPrimary} disabled={primaryDisabled}>{primaryLabel}</Button>
            {footnote && <p className="muted" style={{ fontSize: 12.5, textAlign: "center", margin: "12px 0 0" }}>{footnote}</p>}
          </div>
        )}
      </div>
    </aside>
  );
}

/* ---------- Mobile sticky cart bar ---------- */
function CartBar({ state, onPrimary, primaryLabel = "Verder", disabled }) {
  const { total, count } = buildOrder(state);
  return (
    <div className="cartbar">
      <div className="ct-info">
        <small>{count} {count === 1 ? "item" : "items"} in mandje</small>
        <b className="tnum">{euro(total)}</b>
      </div>
      <Button iconRight="right" onClick={onPrimary} disabled={disabled}>{primaryLabel}</Button>
    </div>
  );
}

Object.assign(window, { buildOrder, allItems, itemById, Cart, CartBar });
