/* global React, Heading, WAIcon, waLink, OfficialSeal,
   cartGet, cartRemove, cartSetQty, cartClear, orderCreate, newFolio,
   priceNum, money, useStore, PAYMENT_HOLDER, PAYMENT_METHODS, BRAND */
const { useState: useStateCt } = React;

/* ---------- Resumen de importe ---------- */
function cartTotals(items) {
  const subtotal = items.reduce((n, i) => n + priceNum(i.price) * (i.qty || 1), 0);
  const count = items.reduce((n, i) => n + (i.qty || 1), 0);
  return { subtotal, count };
}

/* ---------- Vista: carrito ---------- */
function CartList({ items, onContinue }) {
  const { subtotal, count } = cartTotals(items);
  return (
    <div className="cart-layout">
      <div className="cart-items">
        {items.map((i) => (
          <div className="cart-line gold-frame corners" key={i.id}>
            <i className="tl" /><i className="tr" /><i className="bl" /><i className="br" />
            <div className="cart-thumb">
              <image-slot id={"cart-" + i.id} class="cart-slot" shape="rect" placeholder="Foto"></image-slot>
            </div>
            <div className="cart-info">
              <h3 className="gold-text">{i.code}</h3>
              <p className="cart-line-sub">{i.line} · {i.cat}</p>
              <span className="cart-unit">{i.price} <em>MXN c/u</em></span>
            </div>
            <div className="cart-qty">
              <button onClick={() => cartSetQty(i.id, (i.qty || 1) - 1)} aria-label="Menos">–</button>
              <span>{i.qty || 1}</span>
              <button onClick={() => cartSetQty(i.id, (i.qty || 1) + 1)} aria-label="Más">+</button>
            </div>
            <div className="cart-line-total">{money(priceNum(i.price) * (i.qty || 1))}</div>
            <button className="cart-remove" onClick={() => cartRemove(i.id)} aria-label="Quitar">×</button>
          </div>
        ))}
      </div>

      <aside className="cart-summary parchment">
        <h3 className="cart-sum-h">Resumen del pedido</h3>
        <div className="cart-sum-row"><span>Ejemplares ({count})</span><b>{money(subtotal)}</b></div>
        <div className="cart-sum-row"><span>Envío</span><em>Se cotiza por separado</em></div>
        <div className="cart-sum-divider" />
        <div className="cart-sum-row total"><span>Subtotal</span><b className="gold-text">{money(subtotal)} <em>MXN</em></b></div>
        <button className="btn-gold cart-continue" onClick={onContinue}>Generar pedido →</button>
        <p className="cart-fine">El envío no está incluido. Al generar el pedido recibes un folio y los datos de pago. Confirmamos disponibilidad final por WhatsApp.</p>
        <button className="cart-clear" onClick={cartClear}>Vaciar carrito</button>
      </aside>
    </div>
  );
}

/* ---------- Vista: pago (datos + comprobante) ---------- */
function Checkout({ order, onClose }) {
  const waMsg =
    "Hola, generé el pedido " + order.folio + " en la página oficial de Rancho La Vega.\n\n" +
    order.items.map((i) => "• " + (i.qty || 1) + "× " + i.code + " (" + i.line + ") — " + i.price).join("\n") +
    "\n\nSubtotal: " + money(order.subtotal) + " MXN.\nYa realicé el pago / transferencia y adjunto mi comprobante.";

  return (
    <div className="checkout">
      <div className="checkout-head parchment">
        <div>
          <p className="eyebrow">Pedido generado</p>
          <h2 className="gold-text folio-code">{order.folio}</h2>
          <p className="checkout-date">{order.date}</p>
        </div>
        <OfficialSeal />
      </div>

      <div className="checkout-grid">
        <div className="pay-block gold-frame corners">
          <i className="tl" /><i className="tr" /><i className="bl" /><i className="br" />
          <h3 className="pay-h">Datos de pago oficiales</h3>
          <p className="pay-holder">Titular: <strong>{PAYMENT_HOLDER}</strong></p>
          <div className="pay-methods">
            {PAYMENT_METHODS.map((m) => (
              <div className="pay-method" key={m.bank}>
                <div className="pay-method-top">
                  <span className="pay-bank">{m.bank}</span>
                  <span className="pay-kind">{m.kind}</span>
                </div>
                <button className="pay-number" onClick={() => copyNum(m.number)} title="Copiar">
                  {m.number}<CopyIco />
                </button>
                {m.extra && (
                  <button className="pay-number small" onClick={() => copyNum(m.extra.value)} title="Copiar">
                    <em>{m.extra.label}:</em> {m.extra.value}<CopyIco />
                  </button>
                )}
              </div>
            ))}
          </div>
          <p className="pay-warn">Realiza el pago únicamente a estos datos oficiales. Rancho La Vega no se hace responsable por depósitos a cuentas no publicadas aquí.</p>
        </div>

        <div className="pay-side">
          <div className="pay-steps parchment">
            <h3 className="pay-h">¿Cómo continúo?</h3>
            <ol className="pay-step-list">
              <li><b>Realiza el pago</b> por transferencia o depósito a una de las cuentas.</li>
              <li><b>Guarda tu comprobante</b> (captura o foto del recibo).</li>
              <li><b>Envíanos el comprobante</b> por WhatsApp junto con tu folio.</li>
              <li>Confirmamos tu pago y coordinamos la entrega o envío.</li>
            </ol>
          </div>
          <div className="pay-receipt parchment">
            <h4>Adjunta tu comprobante</h4>
            <image-slot id={"receipt-" + order.folio} class="receipt-slot" shape="rect" placeholder="Arrastra aquí tu comprobante de pago"></image-slot>
            <a className="btn-gold pay-wa" href={waLink(waMsg)} target="_blank" rel="noopener noreferrer">
              <WAIcon size={15} /> Ya pagué — enviar comprobante
            </a>
          </div>
        </div>
      </div>

      <div className="checkout-foot">
        <button className="cart-clear" onClick={onClose}>← Volver al catálogo</button>
        <span className="checkout-folio-note">Guarda tu folio <b>{order.folio}</b> para dar seguimiento a tu pedido.</span>
      </div>
    </div>
  );
}

function copyNum(v) {
  const clean = v.replace(/\s/g, "");
  if (navigator.clipboard) navigator.clipboard.writeText(clean);
}
function CopyIco() {
  return (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <rect x="9" y="9" width="11" height="11" rx="2" /><path d="M5 15V5a2 2 0 0 1 2-2h10" />
    </svg>
  );
}

/* ---------- Página de carrito ---------- */
function Cart() {
  useStore();
  const [order, setOrder] = useStateCt(null);
  const items = cartGet();

  const generate = () => {
    const { subtotal } = cartTotals(items);
    const o = {
      folio: newFolio(),
      date: new Date().toLocaleString("es-MX", { dateStyle: "long", timeStyle: "short" }),
      items: items.map((i) => ({ ...i })),
      subtotal,
      status: "Pendiente de pago",
    };
    orderCreate(o);
    setOrder(o);
    cartClear();
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  return (
    <section className="section-pad wood" id="carrito">
      <div className="wrap">
        <Heading kicker={order ? "Pago" : "Tu pedido"} title={order ? "Datos de pago" : "Carrito de compras"} />
        {order ? (
          <Checkout order={order} onClose={() => { setOrder(null); location.href = "ejemplares.html"; }} />
        ) : items.length === 0 ? (
          <div className="cart-empty reveal">
            <CartBig />
            <h3>Tu carrito está vacío</h3>
            <p>Explora el catálogo y añade los ejemplares disponibles que te interesen.</p>
            <a className="btn-gold" href="ejemplares.html">Ver ejemplares</a>
          </div>
        ) : (
          <div className="reveal"><CartList items={items} onContinue={generate} /></div>
        )}
      </div>
    </section>
  );
}

function CartBig() {
  return (
    <svg viewBox="0 0 24 24" width="56" height="56" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <circle cx="9" cy="20" r="1.4" /><circle cx="18" cy="20" r="1.4" />
      <path d="M2 3h2.2l2.1 12.2a1.5 1.5 0 0 0 1.5 1.3h8.6a1.5 1.5 0 0 0 1.5-1.2L21 7H5.3" />
    </svg>
  );
}

Object.assign(window, { Cart });
