/* global React */
const { useEffect: useCartEffect, useState: useCartState } = React;

/* Accepted payment methods — logos shown on light chips so each brand stays legible. */
const PAY_METHODS = [
  { id: "paypal",  label: "PayPal",        src: "assets/pay/paypal.png" },
  { id: "bitcoin", label: "Bitcoin",       src: "assets/pay/bitcoin.png" },
  { id: "bank",    label: "Bank Transfer", src: "assets/pay/banktransfer-trim.png" },
  { id: "psc",     label: "Paysafecard",   src: "assets/pay/paysafecard.png" },
  { id: "amazon",  label: "Amazon.de",     src: "assets/pay/amazon.png" },
];

const SHIPPING = 4.95;
const PROCESSING = 0.10;
const eur = (n) => Number(n).toFixed(2).replace(".", ",") + " €";

function CartIcon({ size = 20 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path d="M3 4h2l2.2 11.2a1.5 1.5 0 0 0 1.5 1.2h8.4a1.5 1.5 0 0 0 1.47-1.18L21 8H6"
        stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx="9.5" cy="20" r="1.4" fill="currentColor" />
      <circle cx="17.5" cy="20" r="1.4" fill="currentColor" />
    </svg>
  );
}

function PayPalWordmark() {
  return (
    <span className="ppmark" aria-label="PayPal">
      <span className="ppmark__a">Pay</span><span className="ppmark__b">Pal</span>
    </span>
  );
}

function PayMethods() {
  return (
    <div className="cart-pay">
      <span className="cart-pay__label">Accepted payment methods</span>
      <div className="cart-pay__strip">
        {PAY_METHODS.map((m) => (
          <span key={m.id} className="pay-logo" title={m.label}>
            <img src={m.src} alt={m.label} />
          </span>
        ))}
      </div>
    </div>
  );
}

/* The basket drawer. Items live in App state — the basket starts EMPTY and only
   holds what the user actually adds. */
function Cart({ open, onClose, items = [], onChangeQty, onRemove }) {
  // Lock body scroll while the basket is open.
  useCartEffect(() => {
    if (open) {
      const prev = document.body.style.overflow;
      document.body.style.overflow = "hidden";
      return () => { document.body.style.overflow = prev; };
    }
  }, [open]);

  // Close on Escape.
  useCartEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  const count = items.reduce((s, i) => s + i.qty, 0);
  const subtotal = items.reduce((s, i) => s + i.price * i.qty, 0);
  const total = subtotal + SHIPPING + PROCESSING;
  const empty = items.length === 0;

  // The full checkout window (shipping details + payment-method choice).
  const [checkoutOpen, setCheckoutOpen] = useCartState(false);

  // Plain-text order summary used by the checkout window.
  const orderSummary =
    items.map((it) => `${it.qty}x ${it.name} (${it.type}) = ${eur(it.price * it.qty)}`).join("\n") +
    `\n\nSubtotal: ${eur(subtotal)}\nShipping: ${eur(SHIPPING)}\nProcessing fee: ${eur(PROCESSING)}\nTOTAL: ${eur(total)}`;

  return (
    <div className={`cart-root ${open ? "is-open" : ""}`} aria-hidden={!open}>
      <div className="cart-scrim" onClick={onClose} />

      <aside className="cart" role="dialog" aria-label="Your basket" aria-modal="true">
        <header className="cart-head">
          <div>
            <span className="eyebrow">Your basket</span>
            <h3 className="cart-title">The Den Reserve</h3>
            <span className="cart-count">{count === 0 ? "No items yet" : `${count} ${count === 1 ? "item" : "items"}`}</span>
          </div>
          <button className="cart-close" aria-label="Close basket" onClick={onClose}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" /></svg>
          </button>
        </header>

        <div className="cart-body">
          {empty ? (
            <div className="cart-empty">
              <span className="cart-empty__ring"><CartIcon size={30} /></span>
              <span className="cart-empty__title">Your basket is empty</span>
              <p className="cart-empty__sub">Browse the genetics carousel and add a reserve pack to get started.</p>
              <button className="btn-cart-go btn-cart-go--inline" onClick={onClose}>Browse genetics</button>
            </div>
          ) : (
            <ul className="cart-items">
              {items.map((it) => (
                <li key={it.name} className="cart-item">
                  <span className="cart-thumb" aria-hidden="true">
                    {it.img ? <img src={it.img} alt="" /> : <span className="cart-thumb__leaf" />}
                  </span>
                  <div className="cart-item__info">
                    <span className="cart-item__name street">{it.name}</span>
                    <span className="cart-item__type">{it.type}</span>
                    <div className="cart-qty">
                      <button aria-label="Decrease quantity" onClick={() => onChangeQty && onChangeQty(it.name, -1)}>−</button>
                      <span>{it.qty}</span>
                      <button aria-label="Increase quantity" onClick={() => onChangeQty && onChangeQty(it.name, 1)}>+</button>
                    </div>
                  </div>
                  <div className="cart-item__right">
                    <span className="cart-item__price">{eur(it.price * it.qty)}</span>
                    <button className="cart-item__remove" onClick={() => onRemove && onRemove(it.name)}>Remove</button>
                  </div>
                </li>
              ))}
            </ul>
          )}

          {!empty && (
            <div className="cart-summary">
              <div className="cart-row"><span>Subtotal</span><span>{eur(subtotal)}</span></div>
              <div className="cart-row"><span>Shipping</span><span>{eur(SHIPPING)}</span></div>
              <div className="cart-row"><span>Processing fee</span><span>{eur(PROCESSING)}</span></div>
            </div>
          )}
        </div>

        {!empty && (
          <footer className="cart-foot">
            <div className="cart-foot__total">
              <span>Total</span><span className="cart-foot__amt">{eur(total)}</span>
            </div>
            <button className="btn-cart-go" onClick={() => setCheckoutOpen(true)}>Go to the cart</button>

            <div className="cart-or"><span>or proceed with quick payment</span></div>

            <button className="btn-paypal" aria-label="Pay with PayPal">
              <PayPalWordmark />
            </button>
            <p className="cart-secure">
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M6 11V8a6 6 0 0 1 12 0v3" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/><rect x="4.5" y="11" width="15" height="9.5" rx="2" stroke="currentColor" strokeWidth="1.8"/></svg>
              Encrypted &amp; discreet checkout
            </p>

            <PayMethods />
          </footer>
        )}
      </aside>

      {checkoutOpen && window.CheckoutWindow &&
        <CheckoutWindow items={items} subtotal={subtotal} shipping={SHIPPING}
          processing={PROCESSING} total={total} summary={orderSummary}
          onClose={() => setCheckoutOpen(false)} />}
    </div>
  );
}

window.Cart = Cart;
window.CartIcon = CartIcon;
