/* global React, window, BOXES, PICKUP_WINDOWS, CAL_DAYS, PH, Price, fmt */
// =======================================================================
//  Carrinho + drawer + checkout  ·  WooCommerce ou simulado
//
//  Lógica:
//    - Se window.ZUZU_JD_CONFIG.wcEnabled === true  →  usa WC AJAX
//      * "Adicionar" chama ?wc-ajax=add_to_cart (sem redirecionar)
//      * "Fechar pedido" redireciona para wc_get_cart_url()
//    - Caso contrário  →  drawer simulado original (toast + fake checkout)
// =======================================================================

const { useState: useStateC, useEffect: useEffectC } = React;

/* ---------- helpers ---------- */

function findBox(id) { return window.BOXES.find((b) => b.id === id); }

const cfg        = window.ZUZU_JD_CONFIG || {};
const wcEnabled  = !!cfg.wcEnabled;
const wcIds      = cfg.wcIds     || {};
const wcCartUrl  = cfg.wcCartUrl || '/cart';

/* ===================== WC AJAX helpers ===================== */

async function wcAddToCart(productId) {
  const ajaxUrl = (window.wc_add_to_cart_params?.wc_ajax_url || '/?wc-ajax=%%endpoint%%')
    .replace('%%endpoint%%', 'add_to_cart');

  const body = new URLSearchParams({ product_id: productId, quantity: 1 });

  try {
    const res  = await fetch(ajaxUrl, {
      method : 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
      body   : body.toString(),
    });
    const json = await res.json();
    return !json.error;
  } catch {
    return false;
  }
}

/* ===================== BoxModal ===================== */

function BoxModal({ openId, onClose, onAdd, inCart }) {
  const box = openId ? findBox(openId) : null;
  const [activeThumb, setActiveThumb] = useStateC(0);
  const [loading, setLoading]         = useStateC(false);

  useEffectC(() => { setActiveThumb(0); }, [openId]);
  useEffectC(() => {
    function onEsc(e) { if (e.key === 'Escape') onClose(); }
    if (openId) window.addEventListener('keydown', onEsc);
    return () => window.removeEventListener('keydown', onEsc);
  }, [openId, onClose]);

  async function handleAdd() {
    if (!box) return;
    setLoading(true);
    await onAdd(box.id);
    setLoading(false);
  }

  return (
    <div className={`modal-scrim ${openId ? 'open' : ''}`} onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="close" onClick={onClose} aria-label="Fechar"></button>
        {box && (
          <>
            <div className="gallery">
              <PH className="hero-ph" label={`foto · ${box.name.toLowerCase()} · ângulo ${activeThumb + 1}`} />
              <div className="thumbs">
                {Array.from({ length: 4 }).map((_, i) => (
                  <PH
                    key={i}
                    label={`${i + 1}/4`}
                    style={{ outline: activeThumb === i ? '1px solid var(--accent)' : 'none' }}
                    onClick={() => setActiveThumb(i)}
                  />
                ))}
              </div>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 4 }}>
                {box.chips.map((c) => <span key={c} className="chip">{c}</span>)}
              </div>
            </div>
            <div className="content">
              <div className="eyebrow">{box.serves}</div>
              <h2>{box.name}</h2>
              <p className="lede">{box.poetic} {box.tagline}</p>
              <ul className="ingredients">
                {box.items.map((it, i) => (
                  <li key={i}>
                    <span>{it.text}</span>
                    <span className="qty">{it.qty}</span>
                  </li>
                ))}
              </ul>
              <div className="footer">
                <Price value={box.price} suffix="à vista" large />
                <button className="add" onClick={handleAdd} disabled={loading}>
                  {loading ? 'Adicionando…' : inCart ? 'Adicionar mais 1' : 'Adicionar ao carrinho'}
                </button>
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

/* ===================== CartDrawer — simulado (sem Woo) ===================== */

function CartDrawerSimulated({
  open, onClose, items, onInc, onDec, onRemove,
  date, window: pickup, onCheckout, success, onResetSuccess,
}) {
  const subtotal = items.reduce((sum, it) => {
    const b = findBox(it.id);
    return sum + (b ? b.price * it.qty : 0);
  }, 0);

  return (
    <>
      <div className={`drawer-scrim ${open ? 'open' : ''}`} onClick={onClose}></div>
      <aside className={`drawer ${open ? 'open' : ''}`} aria-hidden={!open}>
        <header className="drawer-head">
          <h3>{success ? 'Pedido feito' : 'Sua caixinha'}</h3>
          <button className="qty-btn" onClick={onClose} aria-label="Fechar" style={{ width: 32, height: 32 }}>✕</button>
        </header>

        {success ? (
          <div className="success">
            <div className="ring"><span className="heart" aria-hidden="true"></span></div>
            <h3>Recebemos com carinho.</h3>
            <p>Em alguns minutos enviaremos um WhatsApp confirmando data, horário e a forma de pagamento.</p>
            <button className="add" style={{ marginTop: 12 }} onClick={() => { onResetSuccess(); onClose(); }}>
              Continuar navegando
            </button>
          </div>
        ) : items.length === 0 ? (
          <div className="drawer-empty">
            <div className="poetic">Está vazinha por enquanto.</div>
            <p>Escolha uma caixa, uma tábua ou reserve o jantar.</p>
          </div>
        ) : (
          <>
            <div className="drawer-body">
              {items.map((it) => {
                const b = findBox(it.id);
                if (!b) return null;
                return (
                  <div className="drawer-item" key={it.id}>
                    <PH className="thumb" label={b.name.split(' ').slice(-1)[0]} />
                    <div>
                      <div className="name">{b.name}</div>
                      <div className="qty-row">
                        <button className="qty-btn" onClick={() => onDec(it.id)}>−</button>
                        <span style={{ minWidth: 20, textAlign: 'center' }}>{it.qty}</span>
                        <button className="qty-btn" onClick={() => onInc(it.id)}>+</button>
                        <button className="qty-btn" onClick={() => onRemove(it.id)} style={{ marginLeft: 8 }} aria-label="Remover">×</button>
                      </div>
                    </div>
                    <div className="row-price">R$ {fmt(b.price * it.qty)}</div>
                  </div>
                );
              })}
            </div>
            <footer className="drawer-foot">
              <div className="totals">
                <div className="row"><span>Subtotal</span><span>R$ {fmt(subtotal)}</span></div>
                <div className="row">
                  <span>Retirada</span>
                  <span>{date ? `${date} jun · ${pickup}` : 'selecionar'}</span>
                </div>
                <div className="row total"><span>Total</span><span>R$ {fmt(subtotal)}</span></div>
              </div>
              <button className="checkout" onClick={onCheckout} disabled={!date}>
                <span>{date ? 'Fechar pedido' : 'Escolha uma data primeiro'}</span>
                {date && <span style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 16 }}>→</span>}
              </button>
              <p style={{ fontSize: 11, letterSpacing: '0.08em', color: 'var(--ink-soft)', marginTop: 12, textAlign: 'center' }}>
                Pagamento por Pix · confirmação no WhatsApp em até 30 min
              </p>
            </footer>
          </>
        )}
      </aside>
    </>
  );
}

/* ===================== CartDrawer — WooCommerce ===================== */

function CartDrawerWoo({ open, onClose, wcCount }) {
  return (
    <>
      <div className={`drawer-scrim ${open ? 'open' : ''}`} onClick={onClose}></div>
      <aside className={`drawer ${open ? 'open' : ''}`} aria-hidden={!open}>
        <header className="drawer-head">
          <h3>Sua caixinha</h3>
          <button className="qty-btn" onClick={onClose} aria-label="Fechar" style={{ width: 32, height: 32 }}>✕</button>
        </header>

        <div className="drawer-body" style={{ paddingTop: 32, paddingBottom: 32, textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 20 }}>
          {wcCount > 0 ? (
            <>
              <div className="ring"><span className="heart" aria-hidden="true"></span></div>
              <p style={{ fontSize: 18, fontFamily: 'var(--font-display)', fontStyle: 'italic', color: 'var(--ink)', maxWidth: '24ch' }}>
                {wcCount === 1 ? '1 item' : `${wcCount} itens`} na caixinha.
              </p>
              <p style={{ fontSize: 13, color: 'var(--ink-soft)', maxWidth: '34ch' }}>
                Finalize a reserva no checkout — escolha data e horário de retirada no próximo passo.
              </p>
            </>
          ) : (
            <>
              <p className="poetic" style={{ fontSize: 18, color: 'var(--ink-soft)', maxWidth: '28ch' }}>
                Está vazinha por enquanto.
              </p>
              <p style={{ fontSize: 13, color: 'var(--ink-soft)' }}>
                Escolha uma caixa ou reserve o jantar.
              </p>
            </>
          )}
        </div>

        <footer className="drawer-foot">
          <a
            className="checkout"
            href={wcCartUrl}
            style={{
              display       : 'flex',
              justifyContent: 'space-between',
              alignItems    : 'center',
              textDecoration: 'none',
              pointerEvents : wcCount > 0 ? 'auto' : 'none',
              opacity       : wcCount > 0 ? 1 : 0.45,
            }}
          >
            <span>Ver carrinho &amp; finalizar pedido</span>
            <span style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 16 }}>→</span>
          </a>
          <p style={{ fontSize: 11, letterSpacing: '0.08em', color: 'var(--ink-soft)', marginTop: 12, textAlign: 'center' }}>
            Checkout seguro via WooCommerce · Pix ou cartão
          </p>
        </footer>
      </aside>
    </>
  );
}

/* ===================== CartDrawer — roteador público ===================== */

function CartDrawer(props) {
  if (wcEnabled) {
    return <CartDrawerWoo open={props.open} onClose={props.onClose} wcCount={props.wcCount || 0} />;
  }
  return <CartDrawerSimulated {...props} />;
}

Object.assign(window, {
  BoxModal,
  CartDrawer,
  wcEnabled,
  wcIds,
  wcAddToCart,
});
