/* ============================================================
   ATUKASA SUSHI — Componentes
   ============================================================ */
const { useState, useEffect, useRef } = React;

/* ---------- helpers ---------- */
const fmt = (n) => n.toLocaleString("es-DO");

/* ---------- placeholder de imagen (sin fotos reales) ---------- */
function DishImage({ product, kind }) {
  const tile = window.ATUKASA.TILE[product.cat] || ["#1F3B34", "#15302B"];
  const letter = product.name.replace(/^[^A-Za-zÁÉÍÓÚÑ]+/, "").charAt(0).toUpperCase();
  const style = { "--c1": tile[0], "--c2": tile[1] };
  // Buscar imagen real del producto
  const allProducts = window.ATUKASA.PRODUCTS || [];
  const found = allProducts.find(p => p.name === product.name || p.id === product.id);
  const imgSrc = found && found.images && found.images[0] ? found.images[0] : null;
  if (imgSrc) {
    return (
      <div className={"dish dish--" + kind} style={style}>
        <img src={imgSrc} alt={product.name} style={{width:"100%",height:"100%",objectFit:"cover",borderRadius:"inherit"}} />
      </div>
    );
  }
  return (
    <div className={"dish dish--" + kind} style={style}>
      <span className="dish__glyph">{letter}</span>
      <span className="dish__tag">foto</span>
    </div>
  );
}

/* ---------- stepper cantidad ---------- */
function Stepper({ value, onChange, min = 1 }) {
  return (
    <div className="stepper">
      <button className="stepper__btn" onClick={() => onChange(Math.max(min, value - 1))} aria-label="Quitar">−</button>
      <span className="stepper__val">{value}</span>
      <button className="stepper__btn" onClick={() => onChange(value + 1)} aria-label="Agregar">+</button>
    </div>
  );
}

/* ---------- rail de categorías ---------- */
function CategoryRail({ cats, active, onPick, countByCat }) {
  return (
    <nav className="rail" aria-label="Categorías">
      {cats.map((c) => (
        <button
          key={c.id}
          className={"railitem" + (active === c.id ? " is-active" : "")}
          onClick={() => onPick(c.id)}
        >
          <DishImage product={{ cat: c.id, name: c.name }} kind="tile" />
          {c.img && <img src={c.img} alt={c.name} className="railitem__img" />}
          <span className="railitem__name">{c.short || c.name}</span>
          {active === c.id && <span className="railitem__bar" />}
        </button>
      ))}
    </nav>
  );
}

/* ---------- tarjeta de producto ---------- */
function ProductCard({ product, onOpen }) {
  const startPrice = product.variants ? product.variants[0].price : product.price;
  return (
    <article className="card" onClick={() => onOpen(product)}>
      <div className="card__media">
        {product.images
          ? <img src={product.images[0]} alt={product.name} className="card__img" />
          : <DishImage product={product} kind="card" />}
        {product.badge && (
          Array.isArray(product.badge)
            ? <div className="badges">{product.badge.map((b,i) => <span key={i} className="badge badge--multi">{b}</span>)}</div>
            : <span className="badge">{product.badge}</span>
        )}
      </div>
      <div className="card__body">
        <h3 className="card__name">{product.name}</h3>
        <p className="card__desc">{product.desc}</p>
        <div className="card__foot">
          <span className="card__price">
            
            {product.regular && <s className="card__was">RD$ {fmt(product.regular)}</s>}
            RD$ {fmt(startPrice)}
            {product.unitNote && <em className="card__unit"> /{product.unitNote.replace("por ", "")}</em>}
          </span>
          <button className="btn btn--add" onClick={(e) => { e.stopPropagation(); onOpen(product); }}>
            Ordenar
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M9 6l6 6-6 6" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>
        </div>
      </div>
    </article>
  );
}

/* ---------- modal de producto (variantes + modificadores) ---------- */
function ProductModal({ product, onClose, onAdd }) {
  const variants = product.variants || null;
  const customizable = !!variants;
  const hasSides = !!(product.sides && product.sides.length);
  const [vIdx, setVIdx] = useState(0);
  const [side, setSide] = useState(hasSides ? null : undefined);
  const [mods, setMods] = useState([]);
  const [qty, setQty] = useState(1);
  const [imgIdx, setImgIdx] = useState(0);
  const [sideError, setSideError] = useState(false);
  const images = product.images || null;

  useEffect(() => {
    const onKey = (e) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, []);

  if (!product) return null;
  const allMods = window.ATUKASA.MODIFIERS;

  const toggleMod = (m) => {
    setMods((cur) =>
      cur.find((x) => x.id === m.id) ? cur.filter((x) => x.id !== m.id) : [...cur, m]
    );
  };

  const base = variants ? variants[vIdx].price : product.price;
  const scaleFactor = variants ? (variants[vIdx].porc === 8 ? 1 : variants[vIdx].porc === 12 ? 1.2 : 1.5) : 1;
  const isWednesday = new Date().getDay() === 3;
  const scaledMod = (m) => (isWednesday && m.id === "empanizado") ? 0 : Math.round(m.price * scaleFactor);
  const modsTotal = mods.reduce((s, m) => s + scaledMod(m), 0);
  const unit = base + modsTotal;
  const total = unit * qty;

  const handleAdd = () => {
    if (hasSides && !side) { setSideError(true); return; }
    onAdd({
      key: product.id + "-" + (variants ? variants[vIdx].porc : "u") + "-" + (side || "") + "-" + mods.map((m) => m.id).sort().join(""),
      id: product.id,
      name: product.name,
      cat: product.cat,
      variant: variants ? variants[vIdx].porc : null,
      side: side || null,
      mods: mods.map((m) => ({ ...m, price: scaledMod(m) })),
      unit,
      qty,
    });
    onClose();
  };

  return (
    <div className="modal" onClick={onClose}>
      <div className="modal__panel" onClick={(e) => e.stopPropagation()}>
        <button className="modal__close" onClick={onClose} aria-label="Cerrar">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
        </button>

        <div className="modal__hero">
          {images ? (
            <div className="carousel">
              <img src={images[imgIdx]} alt={product.name} className="carousel__main" />
              {images.length > 1 && (
                <>
                  <button className="carousel__arr carousel__arr--prev" onClick={() => setImgIdx((imgIdx - 1 + images.length) % images.length)} aria-label="Anterior">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M15 18l-6-6 6-6" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  </button>
                  <button className="carousel__arr carousel__arr--next" onClick={() => setImgIdx((imgIdx + 1) % images.length)} aria-label="Siguiente">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M9 6l6 6-6 6" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  </button>
                  <div className="carousel__thumbs">
                    {images.map((src, i) => (
                      <button key={i} className={"carousel__thumb" + (i === imgIdx ? " is-active" : "")} onClick={() => setImgIdx(i)}>
                        <img src={src} alt={"Vista " + (i + 1)} />
                      </button>
                    ))}
                  </div>
                </>
              )}
            </div>
          ) : (
            <DishImage product={product} kind="hero" />
          )}
          {product.badge && (
            Array.isArray(product.badge)
              ? <div className="badges badges--hero">{product.badge.map((b,i) => <span key={i} className="badge badge--hero badge--multi">{b}</span>)}</div>
              : <span className="badge badge--hero">{product.badge}</span>
          )}
        </div>

        <div className="modal__scroll">
          <h2 className="modal__name">{product.name}</h2>
          <p className="modal__desc">{product.desc}</p>

          {hasSides && (
            <section className="optblock">
              <div className={"optblock__head" + (sideError ? " optblock__head--err" : "")}>
                <h4>{product.sidesLabel || "Guarnición"}</h4>
                <span className={"optblock__hint" + (sideError ? " optblock__hint--err" : "")}>{sideError ? "¡Elige una!" : "Obligatorio"}</span>
              </div>
              <div className="segmented">
                {product.sides.map((s) => (
                  <button
                    key={s}
                    className={"seg" + (side === s ? " is-active" : "")}
                    onClick={() => { setSide(s); setSideError(false); }}
                  >
                    <span className="seg__label" style={{fontSize:"15px"}}>{s}</span>
                  </button>
                ))}
              </div>
            </section>
          )}

          {customizable && (
            <section className="optblock">
              <div className="optblock__head">
                <h4>Tamaño</h4>
                <span className="optblock__hint">Obligatorio</span>
              </div>
              <div className="segmented">
                {variants.map((v, i) => (
                  <button
                    key={v.porc}
                    className={"seg" + (vIdx === i ? " is-active" : "")}
                    onClick={() => setVIdx(i)}
                  >
                    <span className="seg__label">{v.porc}</span>
                    <span className="seg__unit">porciones</span>
                    <span className="seg__price">RD$ {fmt(v.price)}</span>
                  </button>
                ))}
              </div>
            </section>
          )}

          {customizable && (
            <section className="optblock">
              <div className="optblock__head">
                <h4>Agrega toppings</h4>
                <span className="optblock__hint">{mods.length} seleccionados</span>
              </div>
              <div className="mods">
                {allMods.map((m) => {
                  const on = !!mods.find((x) => x.id === m.id);
                  return (
                    <button
                      key={m.id}
                      className={"modrow" + (on ? " is-on" : "")}
                      onClick={() => toggleMod(m)}
                    >
                      <span className={"check" + (on ? " is-on" : "")}>
                        {on && <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M5 13l4 4L19 7" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg>}
                      </span>
                      <span className="modrow__name">{m.name}{isWednesday && m.id === "empanizado" && <span style={{marginLeft:"8px",fontSize:"10px",background:"#e63946",color:"#fff",borderRadius:"4px",padding:"1px 6px",fontWeight:700}}>¡GRATIS HOY!</span>}</span>
                      <span className="modrow__price">{isWednesday && m.id === "empanizado" ? <><span style={{textDecoration:"line-through",opacity:0.5,marginRight:"6px"}}>+RD$ 120</span><span style={{color:"#4caf50",fontWeight:700}}>RD$ 0</span></> : <>+RD$ {fmt(scaledMod(m))}</>}</span>
                    </button>
                  );
                })}
              </div>
            </section>
          )}
        </div>

        <div className="modal__foot">
          <Stepper value={qty} onChange={setQty} />
          <button className="btn btn--primary btn--block" onClick={handleAdd}>
            <span>Agregar</span>
            <span className="btn__price">RD$ {fmt(total)}</span>
          </button>
        </div>
      </div>
    </div>
  );
}

/* ---------- línea del carrito ---------- */
function CartLine({ item, onQty, onRemove }) {
  const modNames = item.mods.map((m) => m.name).join(", ");
  return (
    <div className="cline">
      <DishImage product={{ cat: item.cat, name: item.name }} kind="thumb" />
      <div className="cline__info">
        <h4 className="cline__name">{item.name}</h4>
        <p className="cline__meta">
          {item.variant ? item.variant + " porciones" : ""}
          {item.variant && (item.side || modNames) ? " · " : ""}
          {item.side ? item.side : ""}
          {item.side && modNames ? " · " : ""}
          {modNames}
          {!item.variant && !item.side && !modNames ? "Sin extras" : ""}
        </p>
        <div className="cline__row">
          <Stepper value={item.qty} onChange={(q) => onQty(item.key, q)} />
          <span className="cline__price">RD$ {fmt(item.unit * item.qty)}</span>
        </div>
      </div>
      <button className="cline__del" onClick={() => onRemove(item.key)} aria-label="Eliminar">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M6 7h12M9 7V5h6v2M8 7l1 12h6l1-12" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>
      </button>
    </div>
  );
}

/* ===================== CHECKOUT ===================== */
const DELIVERY_FEE = 100;          // RD$ — exento de ITBIS
const CARDNET_ENABLED = true;    // ← cambiar a true cuando Hansel confirme el Acquiring Code

/* estilos del checkout (autocontenidos, no requieren tocar p2.css) */
(function () {
  if (document.getElementById("atukasa-checkout-css")) return;
  var s = document.createElement("style");
  s.id = "atukasa-checkout-css";
  s.textContent = [
    ".ck__field{display:flex;flex-direction:column;gap:6px;margin-bottom:14px}",
    ".ck__label{font-size:12px;letter-spacing:.08em;text-transform:uppercase;opacity:.75}",
    ".ck__input{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.14);border-radius:10px;color:inherit;font:inherit;padding:12px 14px;outline:none;width:100%}",
    ".ck__input:focus{border-color:#e02424}",
    ".ck__input--err{border-color:#e02424;background:rgba(224,36,36,.08)}",
    ".ck__err{color:#ff8a8a;font-size:12px}",
    ".ck__pay{display:flex;flex-direction:column;gap:8px;margin-bottom:14px}",
    ".ck__payopt{display:flex;align-items:center;gap:10px;border:1px solid rgba(255,255,255,.14);border-radius:10px;padding:12px 14px;cursor:pointer;background:rgba(255,255,255,.04);font:inherit;color:inherit;text-align:left;width:100%}",
    ".ck__payopt.is-on{border-color:#37d67a;background:rgba(55,214,122,.10)}",
    ".ck__payopt:disabled{opacity:.45;cursor:not-allowed}",
    ".ck__radio{width:16px;height:16px;border-radius:50%;border:2px solid rgba(255,255,255,.4);flex-shrink:0;position:relative}",
    ".is-on .ck__radio{border-color:#37d67a}",
    ".is-on .ck__radio::after{content:'';position:absolute;inset:3px;border-radius:50%;background:#37d67a}",
    ".ck__paysoon{margin-left:auto;font-size:11px;opacity:.7;border:1px solid rgba(255,255,255,.2);border-radius:99px;padding:2px 8px}",
    ".ck__cards{display:flex;gap:8px;align-items:center;padding:6px 14px 0 40px;opacity:.55}",
    ".ck__cardbadge{display:inline-flex;align-items:center;justify-content:center;background:#fff;border-radius:4px;height:20px;min-width:32px;padding:0 4px}",
    ".ck__rows{border-top:1px solid rgba(255,255,255,.1);padding-top:12px;margin-bottom:12px}",
    ".ck__row{display:flex;justify-content:space-between;font-size:14px;padding:3px 0;opacity:.9}",
    ".ck__row--total{font-size:17px;font-weight:700;opacity:1;padding-top:8px}",
    ".ck__free{color:#37d67a;font-weight:600}",
    ".ck__back{background:none;border:none;color:inherit;font:inherit;display:flex;align-items:center;gap:6px;cursor:pointer;opacity:.8;padding:0;margin-bottom:4px}",
    ".ck__back:hover{opacity:1}",
    ".ck__success{display:flex;flex-direction:column;align-items:center;text-align:center;gap:10px;padding:34px 22px}",
    ".ck__success-icon{font-size:46px}",
    ".ck__success h3{margin:0;font-size:22px}",
    ".ck__success p{margin:0;opacity:.85;font-size:14px;line-height:1.5}",
    ".ck__ordernum{font-size:13px;letter-spacing:.1em;text-transform:uppercase;opacity:.7}",
    ".ck__senderr{background:rgba(224,36,36,.12);border:1px solid rgba(224,36,36,.45);border-radius:10px;padding:10px 12px;font-size:13px;margin-bottom:12px}",
    ".acct{width:36px;height:36px;border-radius:50%;display:flex;align-items:center;justify-content:center;border:1px solid rgba(255,255,255,.18);background:rgba(255,255,255,.05);color:inherit;cursor:pointer;position:relative;flex-shrink:0;font:inherit;padding:0}",
    ".acct--on{background:#e02424;border-color:#e02424;font-weight:700;font-size:16px}",
    ".acct__pop{position:absolute;top:calc(100% + 10px);right:0;background:#161213;border:1px solid rgba(255,255,255,.12);border-radius:12px;padding:14px;min-width:240px;z-index:90;box-shadow:0 12px 30px rgba(0,0,0,.55);text-align:left;cursor:default}",
    ".acct__pop-name{font-weight:700;font-size:15px;margin-bottom:2px}",
    ".acct__pop-line{font-size:12.5px;opacity:.8;line-height:1.45;word-break:break-word}",
    ".acct__pop-member{display:inline-flex;align-items:center;gap:6px;font-size:12px;color:#37d67a;margin-top:8px;font-weight:600}",
    ".acct__pop-del{margin-top:12px;background:none;border:1px solid rgba(255,255,255,.18);border-radius:8px;color:inherit;font:inherit;font-size:12px;padding:7px 10px;cursor:pointer;opacity:.8;width:100%}",
    ".acct__pop-del:hover{opacity:1;border-color:#e02424;color:#ff8a8a}",
    ".ck__club{display:flex;align-items:flex-start;gap:10px;border:1px solid rgba(55,214,122,.4);background:rgba(55,214,122,.07);border-radius:10px;padding:12px;cursor:pointer;margin-bottom:14px;font:inherit;color:inherit;text-align:left;width:100%}",
    ".ck__club.is-on{border-color:#37d67a;background:rgba(55,214,122,.13)}",
    ".ck__clubcheck{width:18px;height:18px;border-radius:5px;border:2px solid rgba(255,255,255,.4);flex-shrink:0;display:flex;align-items:center;justify-content:center;margin-top:1px}",
    ".is-on .ck__clubcheck{background:#37d67a;border-color:#37d67a;color:#0b0b0b}",
    ".ck__clubtxt{font-size:13.5px;line-height:1.45}",
    ".ck__clubtxt b{color:#37d67a}",
    ".ck__clubmember{display:flex;align-items:center;gap:8px;color:#37d67a;font-size:13px;font-weight:600;border:1px solid rgba(55,214,122,.4);background:rgba(55,214,122,.08);border-radius:10px;padding:11px 12px;margin-bottom:14px}",
    ".club__divider{display:flex;align-items:center;gap:10px;font-size:12px;letter-spacing:.08em;text-transform:uppercase;opacity:.65;margin:18px 0 8px}",
    ".club__divider::before,.club__divider::after{content:'';flex:1;height:1px;background:rgba(255,255,255,.15)}",
    ".club__phone{display:flex;gap:8px;margin-top:8px}",
    ".club__phone .ck__input{flex:1}",
    ".club__activate{background:#e02424;border:none;border-radius:10px;color:#fff;font:inherit;font-weight:700;padding:0 18px;cursor:pointer;flex-shrink:0}",
    ".club__activate:disabled{opacity:.6;cursor:wait}",
    ".ck__club{display:flex;gap:11px;align-items:flex-start;border:1px dashed rgba(55,214,122,.55);background:rgba(55,214,122,.07);border-radius:10px;padding:12px;cursor:pointer;margin-bottom:14px;font:inherit;color:inherit;text-align:left;width:100%}",
    ".ck__club .check{margin-top:1px}",
    ".ck__club-title{font-weight:700;font-size:13.5px}",
    ".ck__club-sub{font-size:12px;opacity:.8;line-height:1.45}",
    ".ck__clubon{display:flex;align-items:center;gap:8px;border:1px solid rgba(55,214,122,.45);background:rgba(55,214,122,.08);border-radius:10px;padding:11px 12px;font-size:13px;color:#37d67a;font-weight:600;margin-bottom:14px}",
    ".club__phone{display:flex;gap:8px;margin-top:10px}",
    ".club__phone .ck__input{flex:1}",
    ".club__activate{background:#e02424;border:none;border-radius:10px;color:#fff;font:inherit;font-weight:700;padding:0 16px;cursor:pointer}",
    ".club__divider{display:flex;align-items:center;gap:10px;opacity:.55;font-size:12px;margin:18px 0 4px;text-transform:uppercase;letter-spacing:.08em}",
    ".club__divider::before,.club__divider::after{content:'';flex:1;height:1px;background:rgba(255,255,255,.18)}",
    ".ck__mode{display:flex;gap:8px;margin-bottom:14px}",
    ".ck__modeopt{flex:1;display:flex;flex-direction:column;align-items:center;gap:5px;border:1px solid rgba(255,255,255,.14);border-radius:10px;padding:12px 8px;cursor:pointer;background:rgba(255,255,255,.04);font:inherit;color:inherit;font-size:13px;font-weight:600;transition:border-color .15s,background .15s}",
    ".ck__modeopt:hover{border-color:rgba(255,255,255,.3)}",
    ".ck__modeopt.is-on{border-color:#e02424;background:rgba(224,36,36,.12)}",
    ".ck__modeopt-icon{font-size:22px;line-height:1}"
  ].join("");
  document.head.appendChild(s);
})();

function CheckoutPanel({ items, subtotal, member, notes, onBack, onDone, onSuccess }) {
  const saved = (() => {
    try { return JSON.parse(localStorage.getItem("atukasa_customer") || "{}"); }
    catch (e) { return {}; }
  })();
  const [phone, setPhone]     = useState(saved.phone || "");
  const [name, setName]       = useState(saved.name || "");
  const [address, setAddress] = useState(saved.address || "");
  const [email, setEmail]     = useState(saved.email || "");
  const [joinClub, setJoin]   = useState(false);
  const [pay, setPay]         = useState("cod");
  const [pickup, setPickup]   = useState(false);
  const [errs, setErrs]       = useState({});
  const [sending, setSending] = useState(false);
  const [sendErr, setSendErr] = useState(null);

  const isMember = !!member;            // ya pertenece al Club (este dispositivo)
  const clubActive = isMember || joinClub;
  const delivery = pickup ? 0 : (clubActive ? 0 : DELIVERY_FEE);
  const total    = subtotal + delivery;

  const [cobertura, setCobertura] = React.useState(null);

  const validate = () => {
    const e = {};
    const digits = phone.replace(/\D/g, "");
    if (digits.length < 10) e.phone = "Escribe un teléfono válido (10 dígitos)";
    if (name.trim().length < 2) e.name = "Escribe tu nombre";
    if (!pickup && address.trim().length < 4) e.address = "Escribe una referencia completa de entrega";    if (pay === "card" && !email.trim()) e.email = "El correo es necesario para pagos con tarjeta";
    if ((joinClub || pay === "card") && email.trim() && !/^\S+@\S+\.\S+$/.test(email.trim())) e.email = "Ese correo no parece válido";
    setErrs(e);
    return Object.keys(e).length === 0;
  };

  const confirm = async () => {
    if (sending) return;
    if (!validate()) return;
    if (!pickup && (!cobertura || !cobertura.pase)) {
      setSendErr("Confirma tu ubicación en el mapa para poder enviarte el pedido.");
      return;
    }
    setSending(true);
    if (typeof fbq === 'function') fbq('track', 'Contact');
    setSendErr(null);
    const customer = { phone: phone.replace(/\D/g, ""), name: name.trim(), address: address.trim(), email: email.trim() };
    localStorage.setItem("atukasa_customer", JSON.stringify(customer));
    window.dispatchEvent(new Event("atukasa:customer"));
    try {
      const res = await fetch("/atukasa-checkout.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          customer,
          payment: pay,
          service: pickup ? "pickup" : "delivery",
          cobertura: (!pickup && cobertura) ? { pase: cobertura.pase, lat: cobertura.lat, lng: cobertura.lng, zona: cobertura.zona } : null,
          pickup: pickup,
          club: joinClub,
          notes: (notes || "").trim(),
          items: items.map((it) => ({
            name: it.name,
            qty: it.qty,
            unit: it.unit,
            detail: [
              it.variant ? it.variant + " porciones" : null,
              it.side || null,
              it.mods && it.mods.length ? "+ " + it.mods.map((m) => m.name).join(", ") : null,
            ].filter(Boolean).join(" · "),
          })),
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.ok) throw new Error(data.message || "No se pudo registrar el pedido");

      // el servidor manda la última palabra sobre membresía y total
      const srvMember = !!data.member;
      const srvTotal  = (typeof data.total === "number") ? data.total : total;
      const srvDeliv  = srvMember ? 0 : DELIVERY_FEE;

      if (srvMember) {
        localStorage.setItem("atukasa_club", JSON.stringify({ name: customer.name, phone: customer.phone, joined: Date.now() }));
        window.dispatchEvent(new Event("atukasa:club"));
      }

        // — Cardnet: solo redirigir si el cliente eligió tarjeta y Cardnet está activo
        if (pay === "card" && CARDNET_ENABLED && data.payment_url) {
          window.location.href = data.payment_url;
          return;
        }
      const num = data.number || data.id;
      let msg = "¡Hola Atukasa! 🍣 Acabo de confirmar mi pedido *#" + num + "* en la web:\n\n";
      items.forEach((it) => {
        msg += "• " + it.qty + "x " + it.name;
        if (it.variant) msg += " (" + it.variant + " porciones)";
        if (it.side) msg += " · " + it.side;
        if (it.mods && it.mods.length) msg += " + " + it.mods.map((m) => m.name).join(", ");
        msg += " — RD$ " + fmt(it.unit * it.qty) + "\n";
      });
      if (notes && notes.trim()) msg += "\n📝 Notas: " + notes.trim();
      msg += "\n👤 " + customer.name;
      msg += "\n📍 " + customer.address;
      msg += "\n" + (pickup ? "🏪 Recoger en local (General Cabral #90, San Cristóbal)" : "🛵 Delivery: " + (srvMember ? "Gratis (Club Atukasa)" : "RD$ " + fmt(srvDeliv)));
      msg += "\n💵 Pago: " + (pay === "cod" ? "efectivo al recibir" : "tarjeta");
      msg += "\n\n*Total: RD$ " + fmt(srvTotal) + "* (ITBIS incluido)";

      onSuccess && onSuccess({ number: num, msg: msg, firstName: customer.name.split(" ")[0], phone: customer.phone, club: srvMember, justJoined: srvMember && !isMember, pickup: pickup, pay: pay });
      // payment_url redirect already handled above
    } catch (err) {
      setSendErr(err.message + ". Inténtalo de nuevo o pide por WhatsApp.");
    } finally {
      setSending(false);
    }
  };

  return (
    <div className="drawer__list">
      <button className="ck__back" onClick={onBack}>
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M15 18l-6-6 6-6" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
        Volver al pedido
      </button>

      {/* ── Modalidad ── */}
      <div className="ck__field">
        <span className="ck__label">① ¿Cómo quieres recibir tu pedido?</span>
        <div className="ck__mode">
          <button type="button" className={"ck__modeopt" + (!pickup ? " is-on" : "")} onClick={() => setPickup(false)}>
            <span className="ck__modeopt-icon">🛵</span>
            Delivery
          </button>
          <button type="button" className={"ck__modeopt" + (pickup ? " is-on" : "")} onClick={() => setPickup(true)}>
            <span className="ck__modeopt-icon">🏪</span>
            Recoger en local
          </button>
        </div>
        {pickup && <p style={{fontSize:"12px",opacity:.7,margin:"-6px 0 0",lineHeight:1.4}}>📍 General Cabral #90, San Cristóbal · Mié–Dom 5–10 PM</p>}
      </div>

      <div className="ck__field">
        <label className="ck__label" htmlFor="ck-phone">② Teléfono</label>
        <input id="ck-phone" className={"ck__input" + (errs.phone ? " ck__input--err" : "")}
          type="tel" inputMode="tel" autoComplete="tel" placeholder="809-000-0000"
          value={phone} onChange={(e) => setPhone(e.target.value)} />
        {errs.phone && <span className="ck__err">{errs.phone}</span>}
      </div>

      <div className="ck__field">
        <label className="ck__label" htmlFor="ck-name">③ Nombre</label>
        <input id="ck-name" className={"ck__input" + (errs.name ? " ck__input--err" : "")}
          type="text" autoComplete="name" placeholder="Tu nombre"
          value={name} onChange={(e) => setName(e.target.value)} />
        {errs.name && <span className="ck__err">{errs.name}</span>}
      </div>

      {!pickup && (
        <CoberturaBox valor={cobertura} onResult={setCobertura} onPickup={() => setPickup(true)} />
      )}

      {!pickup && (
        <div className="ck__field">
          <label className="ck__label" htmlFor="ck-address">⑤ Referencia para el motorista</label>
          <textarea id="ck-address" className={"ck__input" + (errs.address ? " ck__input--err" : "")}
            autoComplete="street-address" rows={2}
            placeholder="Ej: casa amarilla de dos niveles, portón negro, al lado del colmado"
            value={address} onChange={(e) => setAddress(e.target.value)} />
          {errs.address && <span className="ck__err">{errs.address}</span>}
        </div>
      )}


      {/* ── Club Atukasa ── */}
      {pay === "card" && (<div className="ck__field"><label className="ck__label" htmlFor="ck-cardemail">Correo (necesario para tarjeta)</label><input id="ck-cardemail" className={"ck__input" + (errs.email ? " ck__input--err" : "")} type="email" inputMode="email" autoComplete="email" placeholder="tucorreo@ejemplo.com" value={email} onChange={(e) => setEmail(e.target.value)} />{errs.email && <span className="ck__err">{errs.email}</span>}</div>)}{isMember ? (
        <div className="ck__clubmember">
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M5 13l4 4L19 7" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
          Club Atukasa · Tu delivery es gratis
        </div>
      ) : (
        <React.Fragment>
          <button type="button" className={"ck__club" + (joinClub ? " is-on" : "")} onClick={() => setJoin(!joinClub)}>
            <span className="ck__clubcheck">
              {joinClub && <svg width="12" height="12" viewBox="0 0 24 24" fill="none"><path d="M5 13l4 4L19 7" stroke="currentColor" strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round"/></svg>}
            </span>
            <span className="ck__clubtxt">
              <b>Únete al Club Atukasa</b> — recibe ofertas exclusivas por WhatsApp y tu delivery es <b>gratis, siempre</b> 🛵
            </span>
          </button>
          {joinClub && pay !== "card" && (
            <div className="ck__field">
              <label className="ck__label" htmlFor="ck-email">Correo (opcional)</label>
              <input id="ck-email" className={"ck__input" + (errs.email ? " ck__input--err" : "")}
                type="email" inputMode="email" autoComplete="email" placeholder="tucorreo@ejemplo.com"
                value={email} onChange={(e) => setEmail(e.target.value)} />
              {errs.email && <span className="ck__err">{errs.email}</span>}
            </div>
          )}
        </React.Fragment>
      )}

      <div className="ck__field">
        <span className="ck__label">④ Método de pago</span>
        <div className="ck__pay">
          <button type="button" className={"ck__payopt" + (pay === "cod" ? " is-on" : "")} onClick={() => setPay("cod")}>
            <span className="ck__radio" /> Efectivo al recibir</button><button type="button" className={"ck__payopt" + (pay === "transfer" ? " is-on" : "")} onClick={() => setPay("transfer")}><span className="ck__radio" /> Transferencia bancaria
          </button>
          <button type="button" disabled={!CARDNET_ENABLED}
            className={"ck__payopt" + (pay === "card" ? " is-on" : "")}
            onClick={() => CARDNET_ENABLED && setPay("card")}>
            <span className="ck__radio" /> Pagar con tarjeta
            {!CARDNET_ENABLED && <span className="ck__paysoon">Próximamente</span>}
          </button>
          {/* Marcas de tarjeta — reemplazar por el badge oficial cuando Cardnet envíe su código */}
          <div className="ck__cards" aria-hidden="true">
            <span className="ck__cardbadge">
              <svg width="28" height="10" viewBox="0 0 28 10"><text x="14" y="8.5" textAnchor="middle" fontFamily="Arial, sans-serif" fontWeight="bold" fontStyle="italic" fontSize="9" fill="#1A1F71">VISA</text></svg>
            </span>
            <span className="ck__cardbadge">
              <svg width="26" height="16" viewBox="0 0 26 16">
                <circle cx="10" cy="8" r="6.5" fill="#EB001B"/>
                <circle cx="16" cy="8" r="6.5" fill="#F79E1B" fillOpacity="0.9"/>
              </svg>
            </span>
            <span style={{fontSize:"11px"}}>Pago seguro vía Cardnet</span>
          </div>
        </div>
      </div>

      <div className="ck__rows">
        <div className="ck__row"><span>Subtotal</span><span>RD$ {fmt(subtotal)}</span></div>
        <div className="ck__row">
          <span>Delivery San Cristóbal</span>
          {pickup ? <span className="ck__free">Gratis · Recoger en local</span> : clubActive ? <span className="ck__free">Gratis · Club Atukasa</span> : <span>RD$ {fmt(delivery)}</span>}
        </div>
        <div className="ck__row ck__row--total"><span>Total</span><span>RD$ {fmt(total)}</span></div>
      </div>

      {sendErr && <div className="ck__senderr">⚠️ {sendErr}</div>}

      <button className="btn btn--primary btn--block" onClick={confirm} disabled={sending}>
        {sending ? "Enviando pedido…" : "CONFIRMAR PEDIDO · RD$ " + fmt(total)}
      </button>
      <p className="drawer__tax" style={{marginTop:"10px"}}>Precios con ITBIS incluido · Delivery exento de ITBIS · Solo San Cristóbal</p>
    </div>
  );
}

/* ---------- drawer del carrito ---------- */
function CartDrawer({ open, items, onClose, onQty, onRemove, onClear, user, onOpenLoyalty }) {
  const subtotal = items.reduce((s, it) => s + it.unit * it.qty, 0);
  const count = items.reduce((s, it) => s + it.qty, 0);
  const member = !!user;
  const deliveryFee = (member || items.length === 0) ? 0 : DELIVERY_FEE;
  const total = subtotal + deliveryFee;
  const [notes, setNotes] = useState(() => localStorage.getItem("atukasa_notes") || "");
  const [checkout, setCheckout] = useState(false);
  const [successData, setSuccessData] = useState(null); // {number, msg, firstName, phone, justJoined}

  useEffect(() => { localStorage.setItem("atukasa_notes", notes); }, [notes]);
  useEffect(() => { if (!open) { setCheckout(false); } }, [open]);

  const handleOrderSuccess = (data) => {
    setSuccessData(data);
    setCheckout(false);
  };

  const finishOrder = () => {
    setSuccessData(null);
    onClear();
    localStorage.setItem("atukasa_cart", "[]"); // guardado inmediato: evita que el carrito viejo regrese si el navegador se va a segundo plano (WhatsApp) antes de que React termine de guardar
    localStorage.removeItem("atukasa_notes");
    setNotes("");
    onClose();
  };

  return (
    <React.Fragment>
      <div className={"scrim" + (open ? " is-open" : "")} onClick={onClose} />
      <aside className={"drawer" + (open ? " is-open" : "")} aria-label="Tu pedido">
        <header className="drawer__head">
          <h2>{checkout ? "Confirmar pedido" : "Tu pedido"}</h2>
          <button className="drawer__close" onClick={onClose} aria-label="Cerrar">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
          </button>
        </header>

        {successData ? (
          <div className="ck__success">
            <div className="ck__success-icon">🎉</div>
            <span className="ck__ordernum">Pedido #{successData.number}</span>
            <h3>¡Pedido recibido!</h3>
            <p>Ya está en cocina, <strong>{successData.firstName}</strong>. Te contactaremos al <strong>{successData.phone}</strong> para coordinar{successData.pickup ? " el retiro en General Cabral #90" : " la entrega"}{successData.pay === "cod" ? " · pagas en efectivo al recibir" : ""}.</p>
            {successData.justJoined && (
              <p style={{color:"#37d67a",fontWeight:600}}>🎁 ¡Bienvenido al Club Atukasa! Tu delivery será gratis en todos tus pedidos.</p>
            )}
            <a className="btn btn--wa btn--block" target="_blank"
              onClick={finishOrder}
              href={"https://api.whatsapp.com/send?phone=" + window.ATUKASA.BUSINESS.whatsapp}>
              Abrir WhatsApp
            </a>
            <button className="btn btn--primary btn--block" onClick={finishOrder}>Volver al menú</button>
          </div>
        ) : checkout ? (
          <CheckoutPanel
            items={items}
            subtotal={subtotal}
            member={member}
            notes={notes}
            onBack={() => setCheckout(false)}
            onDone={finishOrder}
            onSuccess={handleOrderSuccess}
          />
        ) : items.length === 0 ? (
          <div className="drawer__empty">
            <div className="drawer__emptyglyph">🍱</div>
            <p>Tu pedido está vacío</p>
            <span>Agrega rolls, combos o entradas para empezar.</span>
          </div>
        ) : (
          <React.Fragment>
            <div className="drawer__list">
              {items.map((it) => (
                <CartLine key={it.key} item={it} onQty={onQty} onRemove={onRemove} />
              ))}
              <button className="drawer__clear" onClick={onClear}>Vaciar pedido</button>
            </div>
            <footer className="drawer__foot">
              {!user && onOpenLoyalty && (
                <button className="drawer__loyalty-invite" onClick={() => { onClose(); setTimeout(onOpenLoyalty, 200); }}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                    <path d="M20 12v10H4V12M22 7H2v5h20V7zM12 22V7M12 7H7.5a2.5 2.5 0 010-5C11 2 12 7 12 7zM12 7h4.5a2.5 2.5 0 000-5C13 2 12 7 12 7z" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                  <span>Hazte miembro gratis · Recibe delivery gratis</span>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{marginLeft:"auto",flexShrink:0}}><path d="M9 6l6 6-6 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </button>
              )}
              {user && (
                <div className="drawer__loyalty">
                  <svg width="15" height="15" viewBox="0 0 24 24" fill="none"><path d="M5 13l4 4L19 7" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  Delivery gratis · Beneficio Miembro Atukasa
                </div>
              )}
              <div className="drawer__total">
                <span>Subtotal ({count})</span>
                <strong>RD$ {fmt(subtotal)}</strong>
              </div>
              <div className="drawer__discount-row">
                <span>Delivery San Cristóbal</span>
                {member
                  ? <span className="drawer__discount-val">Gratis · Club Atukasa</span>
                  : <span>RD$ {fmt(deliveryFee)}</span>}
              </div>
              <div className="drawer__notes">
                <label className="drawer__notes-label">📝 Notas del pedido</label>
                <textarea
                  className="drawer__notes-input"
                  placeholder="Instrucciones especiales, alergias, dirección de entrega..."
                  value={notes}
                  onChange={(e) => setNotes(e.target.value)}
                  rows={2}
                />
              </div>
              <p className="drawer__tax">Precios con ITBIS incluido · Delivery solo en San Cristóbal</p>
              <button className="btn btn--primary btn--block" onClick={() => setCheckout(true)}>
                Ir a pagar · RD$ {fmt(total)}
              </button>
            </footer>
          </React.Fragment>
        )}
      </aside>
    </React.Fragment>
  );
}

/* ---------- placeholder de foto (páginas editoriales) ---------- */
function Ph({ label, cat, className }) {
  const tile = (window.ATUKASA.TILE[cat] || ["#241012", "#140a0b"]);
  return (
    <div className={"ph " + (className || "")} style={{ "--c1": tile[0], "--c2": tile[1] }}>
      <span className="ph__tag">foto</span>
      {label && <span className="ph__label">{label}</span>}
    </div>
  );
}

/* ---------- menú de sitio (hamburguesa) ---------- */
function SiteMenu({ active }) {
  const [open, setOpen] = useState(false);
  const { BUSINESS } = window.ATUKASA;
  const links = [
    { id: "menu",     label: "Menú / Pedido", href: "Atukasa Sushi.html",             desc: "Ordena sushi ahora" },
    { id: "nosotros", label: "Atukasa",       href: "Atukasa - Nosotros.html",          desc: "Nuestra historia" },
    { id: "blog",     label: "Blog",          href: "Atukasa - Blog.html",              desc: "Historias y novedades" },
    { id: "vacantes", label: "Vacantes",      href: "Atukasa - Vacantes.html",          desc: "Únete al equipo" },
  ];
  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    const onKey = (e) => e.key === "Escape" && setOpen(false);
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open]);

  return (
    <React.Fragment>
      <button className="hamb" onClick={() => setOpen(true)} aria-label="Abrir menú">
        <span /><span /><span />
      </button>

      <div className={"sitemenu" + (open ? " is-open" : "")}>
        <div className="sitemenu__top">
          <a className="brand" href="Atukasa Sushi - Propuesta 2.html">
            <img className="brand__badge" src="/wp-content/uploads/atukasa/Isotipo atukasa sushi 2026.png" alt="Atukasa Sushi" />
            <span className="brand__txt">
              <span className="brand__word">ATUKASA</span>
              <span className="brand__sub">SUSHI</span>
            </span>
          </a>
          <button className="sitemenu__close" onClick={() => setOpen(false)} aria-label="Cerrar">
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
          </button>
        </div>

        <nav className="sitemenu__links">
          {links.map((l, i) => (
            <a key={l.id} href={l.href} className={"smlink" + (active === l.id ? " is-active" : "")}>
              <span className="smlink__num">0{i + 1}</span>
              <span className="smlink__label">{l.label}</span>
              <span className="smlink__desc">{l.desc}</span>
              <svg className="smlink__arr" width="26" height="26" viewBox="0 0 24 24" fill="none"><path d="M5 12h14M13 6l6 6-6 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </a>
          ))}
        </nav>

        <div className="sitemenu__foot">
          <div className="sitemenu__footcol">
            <span className="sitemenu__lbl">Visítanos</span>
            <p>{BUSINESS.address}<br />{BUSINESS.hoursLabel}</p>
          </div>
          <div className="sitemenu__footcol">
            <span className="sitemenu__lbl">Síguenos</span>
            <p>{BUSINESS.ig} · {BUSINESS.web}</p>
          </div>
          <a className="btn btn--wa" href={"https://wa.me/" + BUSINESS.whatsapp} target="_blank">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2a10 10 0 00-8.5 15.2L2 22l4.9-1.4A10 10 0 1012 2zm0 18a8 8 0 01-4.1-1.1l-.3-.2-2.9.8.8-2.8-.2-.3A8 8 0 1112 20zm4.4-5.9c-.2-.1-1.4-.7-1.6-.8-.2-.1-.4-.1-.5.1l-.7.9c-.1.2-.3.2-.5.1a6.5 6.5 0 01-3.2-2.8c-.1-.2 0-.4.1-.5l.4-.5c.1-.2.1-.3 0-.5l-.7-1.7c-.2-.4-.4-.4-.5-.4h-.5c-.2 0-.4.1-.6.3-.7.7-.9 1.6-.6 2.6.5 1.7 1.6 3.1 3.4 4.2 1.7 1 2.8 1 3.7.8.6-.1 1.4-.6 1.6-1.2.2-.5.2-1 .1-1.1l-.4-.1z"/></svg>
            Pedir por WhatsApp
          </a>
        </div>
      </div>
      <div className={"sitemenu__scrim" + (open ? " is-open" : "")} onClick={() => setOpen(false)} />
    </React.Fragment>
  );
}

/* ===================== CLUB ATUKASA (membresía por teléfono) ===================== */
const DELIVERY_DISCOUNT = 100;

function readClub() {
  try { return JSON.parse(localStorage.getItem("atukasa_club") || "null"); }
  catch (e) { return null; }
}
function saveClub(data) {
  localStorage.setItem("atukasa_club", JSON.stringify(data));
  window.dispatchEvent(new Event("atukasa:club"));
}
function clearClub() {
  localStorage.removeItem("atukasa_club");
  window.dispatchEvent(new Event("atukasa:club"));
}

function useClub() {
  const [user, setUser] = useState(readClub);
  useEffect(() => {
    const upd = () => setUser(readClub());
    window.addEventListener("atukasa:club", upd);
    return () => window.removeEventListener("atukasa:club", upd);
  }, []);
  return { user };
}
/* alias de compatibilidad */
const useLoyalty = () => { const { user } = useClub(); return { user, login: () => {}, logout: clearClub }; };

function LoyaltyChip({ user, onOpen }) {
  if (user) {
    return (
      <div className="lchip lchip--active">
        <span className="lchip__dot" />
        <span className="lchip__txt">Delivery gratis</span>
      </div>
    );
  }
  return (
    <button className="lchip" onClick={onOpen} title="Hazte miembro y recibe delivery gratis">
      <svg width="15" height="15" viewBox="0 0 24 24" fill="none">
        <path d="M20 12v10H4V12M22 7H2v5h20V7zM12 22V7M12 7H7.5a2.5 2.5 0 010-5C11 2 12 7 12 7zM12 7h4.5a2.5 2.5 0 000-5C13 2 12 7 12 7z" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
      <span className="lchip__txt">Delivery gratis</span>
    </button>
  );
}

function LoyaltyModal({ onClose }) {
  const [phone, setPhone]     = useState("");
  const [checking, setChecking] = useState(false);
  const [error, setError]     = useState(null);
  const [success, setSuccess] = useState(null);

  useEffect(() => {
    const onKey = (e) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, []);

  const activate = async () => {
    if (checking) return;
    const digits = phone.replace(/\D/g, "");
    if (digits.length < 10) { setError("Escribe el teléfono con el que hiciste tu pedido (10 dígitos)"); return; }
    setChecking(true);
    setError(null);
    try {
      const res = await fetch("/atukasa-club.php?phone=" + encodeURIComponent(digits));
      const data = await res.json().catch(() => ({}));
      if (data.member) {
        saveClub({ name: data.name || "Miembro", phone: digits, since: Date.now() });
        setSuccess(data.name || "Miembro");
        setTimeout(onClose, 2600);
      } else {
        setError("Ese número aún no está en el Club. Únete marcando la casilla al confirmar tu próximo pedido. 🍣");
      }
    } catch (err) {
      setError("No se pudo verificar ahora. Inténtalo de nuevo.");
    } finally {
      setChecking(false);
    }
  };

  return (
    <div className="modal" onClick={onClose}>
      <div className="modal__panel modal__panel--sm" onClick={(e) => e.stopPropagation()}>
        <button className="modal__close" onClick={onClose} aria-label="Cerrar">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
        </button>
        {success ? (
          <div className="loyalty-success">
            <div className="loyalty-success__icon">🎉</div>
            <h3>¡Hola de nuevo, {success}!</h3>
            <p>Tu beneficio del Club está activo en este dispositivo. El delivery de <strong>RD$ {fmt(DELIVERY_DISCOUNT)}</strong> es gratis en tus pedidos.</p>
            <div className="loyalty-success__note">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M5 13l4 4L19 7" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
              Beneficio activo en tu carrito
            </div>
          </div>
        ) : (
          <div className="modal__scroll">
            <div className="loyalty-modal__top">
              <img src="/wp-content/uploads/atukasa/Isotipo atukasa sushi 2026.png" alt="" className="loyalty-modal__logo" />
              <div className="loyalty-modal__badge">Club Atukasa</div>
            </div>
            <h2 className="loyalty-modal__title">Delivery gratis,<br/>siempre.</h2>
            <p className="loyalty-modal__sub">Únete al Club Atukasa y recibe ofertas exclusivas por WhatsApp + delivery gratis en la zona de cobertura de San Cristóbal.</p>
            <div className="loyalty-modal__amount">
              <span className="loyalty-modal__amount-val">−RD$ {fmt(DELIVERY_DISCOUNT)}</span>
              <span className="loyalty-modal__amount-txt">en cada pedido,<br/>aplicado automáticamente</span>
            </div>
            <p className="loyalty-modal__micro">¿Cómo me uno? Marca la casilla <strong>"Únete al Club Atukasa"</strong> al confirmar tu pedido. Sin formularios, sin contraseñas.</p>

            <div className="club__divider">¿Ya eres miembro?</div>
            <p className="loyalty-modal__micro" style={{marginBottom:0}}>Activa tu beneficio en este dispositivo con tu teléfono:</p>
            <div className="club__phone">
              <input className="ck__input" type="tel" inputMode="tel" autoComplete="tel"
                placeholder="809-000-0000" value={phone} onChange={(e) => setPhone(e.target.value)} />
              <button className="club__activate" onClick={activate} disabled={checking}>
                {checking ? "..." : "Activar"}
              </button>
            </div>
            {error && <p className="ck__err" style={{marginTop:"8px"}}>{error}</p>}

            <p className="loyalty-modal__legal">Al unirte aceptas recibir ofertas y novedades de Atukasa Sushi por WhatsApp. Puedes salir del Club cuando quieras respondiendo "BAJA". Beneficio válido en zona de cobertura de San Cristóbal, no acumulable con otros cupones.</p>
          </div>
        )}
      </div>
    </div>
  );
}


/* ===================== INDICADOR DE SESIÓN (header) ===================== */
function AccountChip({ memberUser, onOpenLoyalty }) {
  const read = () => {
    try { return JSON.parse(localStorage.getItem("atukasa_customer") || "null"); }
    catch (e) { return null; }
  };
  const [cust, setCust] = useState(read);
  const [open, setOpen] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    const upd = () => setCust(read());
    window.addEventListener("atukasa:customer", upd);
    return () => window.removeEventListener("atukasa:customer", upd);
  }, []);

  useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    const onKey = (e) => e.key === "Escape" && setOpen(false);
    document.addEventListener("mousedown", onDoc);
    document.addEventListener("keydown", onKey);
    return () => { document.removeEventListener("mousedown", onDoc); document.removeEventListener("keydown", onKey); };
  }, [open]);

  const isClubMember = !!(memberUser && memberUser.name);

  /* Sin membresía del Club → ícono genérico (aunque haya datos de autollenado) */
  if (!isClubMember) {
    return (
      <button className="acct" onClick={onOpenLoyalty} aria-label="Club Atukasa" title="Club Atukasa">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
          <circle cx="12" cy="8" r="3.6" stroke="currentColor" strokeWidth="1.8"/>
          <path d="M4.5 19.5c1.6-3.2 4.3-4.8 7.5-4.8s5.9 1.6 7.5 4.8" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/>
        </svg>
      </button>
    );
  }

  /* Miembro del Club → inicial en círculo rojo + popover con sus datos */
  const initial = memberUser.name.trim().charAt(0).toUpperCase();
  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button className="acct acct--on" onClick={() => setOpen(!open)} aria-label={"Cuenta de " + memberUser.name} title={memberUser.name}>
        {initial}
      </button>
      {open && (
        <div className="acct__pop">
          <div className="acct__pop-name">{memberUser.name}</div>
          {cust && cust.phone && <div className="acct__pop-line">📞 {cust.phone}</div>}
          {cust && cust.address && <div className="acct__pop-line">📍 {cust.address}</div>}
          <div className="acct__pop-member">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M5 13l4 4L19 7" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
            Club Atukasa · Delivery gratis
          </div>
          <button className="acct__pop-del" onClick={() => {
            localStorage.removeItem("atukasa_customer");
            clearClub();
            setCust(null); setOpen(false);
          }}>
            Salir del Club en este dispositivo
          </button>
        </div>
      )}
    </div>
  );
}

Object.assign(window, {
  fmt, DishImage, Ph, Stepper, CategoryRail, ProductCard, ProductModal, CartDrawer, CartLine, SiteMenu,
  useLoyalty, useClub, saveClub, clearClub, LoyaltyChip, LoyaltyModal,
  DELIVERY_DISCOUNT, DELIVERY_FEE, CheckoutPanel, AccountChip,
});


/* ── Cobertura de delivery ──────────────────────────────────────────
   Un solo boton. El GPS del telefono se afina solo (como Google Maps)
   y la respuesta sale sola. Si hace falta corregir, el pin se queda
   FIJO en el centro y el cliente mueve el mapa con el dedo — nadie
   tiene que arrastrar un pin diminuto.

   El mapa de zonas NO viaja al navegador: de aqui sale un punto y
   vuelve un si o un no. La fuente unica es n8n. ---------------------- */

var COB_CENTRO = [18.4125, -70.1024];
var COB_WHATSAPP = "https://wa.me/18097986648";

function cobEstilos() {
  if (document.getElementById("atukasa-cobertura-css")) return;
  var s = document.createElement("style");
  s.id = "atukasa-cobertura-css";
  s.textContent = [
    ".cob{margin:14px 0 4px}",
    ".cob__wrap{position:relative;width:100%;height:260px;border-radius:12px;overflow:hidden;margin:10px 0;background:#e8e8e8}",
    ".cob__mapa{position:absolute;inset:0}",
    ".cob__pin{position:absolute;left:50%;top:50%;transform:translate(-50%,-100%);pointer-events:none;z-index:500;filter:drop-shadow(0 2px 3px rgba(0,0,0,.4))}",
    ".cob__pulso{position:absolute;left:50%;top:50%;width:14px;height:14px;margin:-7px 0 0 -7px;border-radius:50%;background:rgba(30,110,255,.35);pointer-events:none;z-index:499}",
    ".cob__btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;width:100%;border:0;border-radius:12px;padding:15px 18px;font:inherit;font-size:16px;font-weight:700;cursor:pointer;background:#e11d2e;color:#fff}",
    ".cob__btn:disabled{opacity:.6;cursor:default}",
    ".cob__btn--alt{background:#fff;color:#111;border:1px solid #d5d5d5;margin-top:10px;font-weight:600}",
    ".cob__btn--mini{width:auto;padding:9px 14px;font-size:14px;font-weight:600;background:#fff;color:#111;border:1px solid #d5d5d5;margin-top:8px}",
    ".cob__aviso{border-radius:12px;padding:13px 15px;margin-top:10px;line-height:1.45;font-size:14.5px}",
    ".cob__aviso--si{background:#e9f7ee;color:#12603a}",
    ".cob__aviso--no{background:#fdecec;color:#8a1c1c}",
    ".cob__aviso--err{background:#fff5e5;color:#7a4a00}",
    ".cob__aviso p{margin:6px 0 0;font-size:14px}",
    ".cob__hint{font-size:13px;opacity:.85;margin-top:8px;line-height:1.4}",
    ".cob__estado{display:flex;align-items:center;gap:9px;font-size:14.5px;margin-top:10px;font-weight:600}",
    ".cob__spin{width:16px;height:16px;border:2px solid rgba(150,150,150,.35);border-top-color:#e11d2e;border-radius:50%;animation:cobGira .8s linear infinite}",
    "@keyframes cobGira{to{transform:rotate(360deg)}}",
    ".cob__wa{display:inline-block;margin-top:10px;font-weight:700;color:#128c7e;text-decoration:none}",
    ".cob__fila{display:flex;gap:8px;margin-top:6px}",
    ".cob__input{flex:1;min-width:0;border:1px solid #d5d5d5;border-radius:10px;padding:11px 12px;font:inherit;font-size:15px;background:#fff;color:#111}",
    ".cob__sug{margin-top:8px;border:1px solid #e2e2e2;border-radius:10px;overflow:hidden;background:#fff}",
    ".cob__sugitem{display:block;width:100%;text-align:left;border:0;border-bottom:1px solid #eee;background:#fff;color:#111;font:inherit;font-size:13.5px;line-height:1.35;padding:11px 12px;cursor:pointer}",
    ".cob__sugitem:last-child{border-bottom:0}"
  ].join("");
  document.head.appendChild(s);
}

/* El zoom se ajusta a lo bueno que sea el GPS. Centrar a zoom maximo
   una lectura de +-800 m deja al cliente perdido en un mapa vacio. */
function cobZoom(ac) {
  if (!ac || ac <= 30) return 18;
  if (ac <= 80) return 17;
  if (ac <= 200) return 16;
  if (ac <= 600) return 15;
  if (ac <= 2000) return 14;
  return 13;
}

/* Distancia aproximada en metros entre dos puntos cercanos. */
function cobCerca(a, b, metros) {
  if (!a || !b) return false;
  var dLat = (a[0] - b[0]) * 111320;
  var dLng = (a[1] - b[1]) * 111320 * Math.cos(a[0] * Math.PI / 180);
  return Math.sqrt(dLat * dLat + dLng * dLng) < metros;
}

function cobCargarLeaflet() {
  if (window.__cobLeaflet) return window.__cobLeaflet;
  window.__cobLeaflet = new Promise(function (resolve, reject) {
    if (window.L && window.L.map) { resolve(window.L); return; }
    var css = document.createElement("link");
    css.rel = "stylesheet";
    css.href = "https://unpkg.com/leaflet@1.9.4/dist/leaflet.css";
    css.crossOrigin = "anonymous";
    document.head.appendChild(css);
    var js = document.createElement("script");
    js.src = "https://unpkg.com/leaflet@1.9.4/dist/leaflet.js";
    js.crossOrigin = "anonymous";
    js.onload = function () { resolve(window.L); };
    js.onerror = function () { reject(new Error("mapa")); };
    document.head.appendChild(js);
  });
  return window.__cobLeaflet;
}

function CoberturaBox(props) {
  var valor = props.valor, onResult = props.onResult, onPickup = props.onPickup;

  var e = React.useState(valor && valor.pase ? "ok" : "inicio"); var estado = e[0], setEstado = e[1];
  var z = React.useState(valor ? valor.zona : null); var zona = z[0], setZona = z[1];
  var m = React.useState(null); var msg = m[0], setMsg = m[1];
  var pr = React.useState(null); var precision = pr[0], setPrecision = pr[1];
  var mm = React.useState(false); var hayMapa = mm[0], setHayMapa = mm[1];
  var qq = React.useState(""); var q = qq[0], setQ = qq[1];
  var sg = React.useState(null); var sug = sg[0], setSug = sg[1];
  var bs = React.useState(false); var buscando = bs[0], setBuscando = bs[1];

  var cajaRef = React.useRef(null);
  var mapaRef = React.useRef(null);
  var vivoRef = React.useRef(true);
  var watchRef = React.useRef(null);
  var timerRef = React.useRef(null);
  var moviendoRef = React.useRef(false);
  var debounceRef = React.useRef(null);
  var prevRef = React.useRef(null);
  var verificadoRef = React.useRef(null);
  var vigilanteRef = React.useRef(null);
  var circuloRef = React.useRef(null);

  React.useEffect(function () {
    cobEstilos();
    return function () {
      vivoRef.current = false;
      if (watchRef.current !== null && navigator.geolocation) navigator.geolocation.clearWatch(watchRef.current);
      if (timerRef.current) clearTimeout(timerRef.current);
      if (debounceRef.current) clearTimeout(debounceRef.current);
      if (vigilanteRef.current) clearInterval(vigilanteRef.current);
      circuloRef.current = null;
      if (mapaRef.current) { try { mapaRef.current.remove(); } catch (err) {} mapaRef.current = null; }
    };
  }, []);

  function consultar(lat, lng) {
    setEstado("cargando");
    fetch("/atukasa-cobertura.php", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ lat: lat, lng: lng })
    }).then(function (r) { return r.json(); }).then(function (j) {
      if (!vivoRef.current) return;
      if (j && j.ok && j.cubierto) {
        setZona(j.zona); setMsg(null); setEstado("ok");
        onResult && onResult({ cubierto: true, zona: j.zona, pase: j.pase, lat: lat, lng: lng, fee: j.delivery_fee });
      } else if (j && j.ok) {
        setZona(null); setMsg(null); setEstado("fuera");
        onResult && onResult(null);
      } else {
        setEstado("error");
        setMsg(j && j.error === "validador_no_disponible"
          ? "No pudimos verificar la zona ahora mismo. Espera un momento y toca de nuevo."
          : "No pudimos verificar esa ubicación.");
        onResult && onResult(null);
      }
    }).catch(function () {
      if (!vivoRef.current) return;
      setEstado("error");
      setMsg("No pudimos verificar la zona. Revisa tu conexión.");
      onResult && onResult(null);
    });
  }

  function quitarCirculo() {
    if (circuloRef.current && mapaRef.current) { try { mapaRef.current.removeLayer(circuloRef.current); } catch (e) {} }
    circuloRef.current = null;
  }

  /* Circulo azul = margen de error del GPS. Que el cliente VEA la duda. */
  function marcarPrecision(lat, lng, ac) {
    var mp = mapaRef.current;
    if (!mp || !window.L) return;
    if (!ac || ac < 20) { quitarCirculo(); return; }
    if (circuloRef.current) { circuloRef.current.setLatLng([lat, lng]); circuloRef.current.setRadius(ac); }
    else circuloRef.current = window.L.circle([lat, lng], { radius: ac, color: "#1e6eff", weight: 1, fillColor: "#1e6eff", fillOpacity: 0.12, interactive: false }).addTo(mp);
  }

  function buscar() {
    var t = (q || "").trim();
    if (t.length < 3) { setSug([]); return; }
    setBuscando(true);
    fetch("/atukasa-cobertura.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ buscar: t }) })
      .then(function (r) { return r.json(); })
      .then(function (j) { if (!vivoRef.current) return; setBuscando(false); setSug((j && j.resultados) ? j.resultados : []); })
      .catch(function () { if (!vivoRef.current) return; setBuscando(false); setSug([]); });
  }

  function irA(lat, lng) {
    setSug(null); setHayMapa(true); quitarCirculo();
    if (!mapaRef.current) crearMapa(lat, lng, 17); else centrar(lat, lng, 17);
    verificadoRef.current = [lat, lng];
    prevRef.current = verificadoRef.current;
    consultar(lat, lng);
  }

  function centrar(lat, lng, zoom) {
    var mp = mapaRef.current;
    if (!mp) return;
    moviendoRef.current = true;
    mp.setView([lat, lng], zoom || mp.getZoom());
    setTimeout(function () { moviendoRef.current = false; }, 450);
  }

  function crearMapa(lat, lng, zoom) {
    return cobCargarLeaflet().then(function (L) {
      if (!vivoRef.current || !cajaRef.current || mapaRef.current) return;
      var mp = L.map(cajaRef.current, {
        zoomControl: true, attributionControl: true,
        // Sin animaciones: dentro del panel deslizante no terminan y dejan
        // el zoom a medias (setView pedia 17 y el mapa se quedaba en 14).
        zoomAnimation: false, fadeAnimation: false, markerZoomAnimation: false, inertia: false
      }).setView([lat, lng], zoom || 17);
      L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", { maxZoom: 19, attribution: "© OpenStreetMap" }).addTo(mp);
      mapaRef.current = mp;
      // Verificacion automatica al mover el mapa. NO dependemos solo del
      // evento moveend de Leaflet: dentro del panel deslizante dispara
      // movestart pero nunca moveend. Vigilamos el centro cada 700 ms y,
      // cuando se queda quieto sobre un punto nuevo, se verifica solo.
      var revisar = function () {
        if (!vivoRef.current || !mapaRef.current || moviendoRef.current) return;
        var c = mapaRef.current.getCenter();
        var p = [c.lat, c.lng];
        var anterior = prevRef.current;
        prevRef.current = p;
        if (cobCerca(p, verificadoRef.current, 12)) return;  // ya lo preguntamos
        if (!cobCerca(p, anterior, 3)) return;               // todavia se mueve
        verificadoRef.current = p;
        setPrecision(null);
        quitarCirculo();
        consultar(c.lat, c.lng);
      };
      mp.on("moveend", function () {
        if (debounceRef.current) clearTimeout(debounceRef.current);
        debounceRef.current = setTimeout(revisar, 350);
      });
      vigilanteRef.current = setInterval(revisar, 700);
      setTimeout(function () { if (mapaRef.current) mapaRef.current.invalidateSize(); }, 150);
      setTimeout(function () { if (mapaRef.current) mapaRef.current.invalidateSize(); }, 600);
    });
  }

  function terminarBusqueda(lat, lng) {
    if (watchRef.current !== null && navigator.geolocation) { navigator.geolocation.clearWatch(watchRef.current); watchRef.current = null; }
    if (timerRef.current) { clearTimeout(timerRef.current); timerRef.current = null; }
    verificadoRef.current = [lat, lng];
    prevRef.current = verificadoRef.current;
    consultar(lat, lng);
  }

  function ubicar() {
    if (!navigator.geolocation) {
      setEstado("sinpermiso");
      setMsg("Este teléfono no nos deja leer la ubicación.");
      return;
    }
    setEstado("ubicando"); setPrecision(null); setHayMapa(true);

    var mejor = null;
    var arranca = function (lat, lng, ac) {
      var z = cobZoom(ac);
      if (!mapaRef.current) crearMapa(lat, lng, z).then(function () { marcarPrecision(lat, lng, ac); });
      else { centrar(lat, lng, z); marcarPrecision(lat, lng, ac); }
    };

    watchRef.current = navigator.geolocation.watchPosition(function (pos) {
      if (!vivoRef.current) return;
      var la = pos.coords.latitude, ln = pos.coords.longitude;
      var ac = pos.coords.accuracy || 999;
      if (!mejor || ac < mejor.ac) mejor = { la: la, ln: ln, ac: ac };
      setPrecision(Math.round(mejor.ac));
      arranca(mejor.la, mejor.ln, mejor.ac);
      if (mejor.ac <= 25) terminarBusqueda(mejor.la, mejor.ln);
    }, function (err) {
      if (!vivoRef.current) return;
      if (watchRef.current !== null) { navigator.geolocation.clearWatch(watchRef.current); watchRef.current = null; }
      if (timerRef.current) { clearTimeout(timerRef.current); timerRef.current = null; }
      setHayMapa(false);
      setEstado("sinpermiso");
      setMsg(err && err.code === 1
        ? "No nos diste permiso para ver tu ubicación. Actívalo en el candado de la barra de direcciones, o escríbenos por WhatsApp y lo hacemos contigo."
        : "No pudimos leer el GPS. Asegúrate de tener la ubicación encendida, o escríbenos por WhatsApp y lo hacemos contigo.");
    }, { enableHighAccuracy: true, timeout: 15000, maximumAge: 0 });

    timerRef.current = setTimeout(function () {
      if (!vivoRef.current) return;
      if (mejor) terminarBusqueda(mejor.la, mejor.ln);
      else {
        if (watchRef.current !== null) { navigator.geolocation.clearWatch(watchRef.current); watchRef.current = null; }
        setHayMapa(false); setEstado("sinpermiso");
        setMsg("El GPS está tardando demasiado. Enciende la ubicación del teléfono, o busca tu calle o sector aquí abajo.");
      }
    }, 22000);
  }

  var pinSVG = (
    <svg className="cob__pin" width="30" height="42" viewBox="0 0 30 42" fill="none">
      <path d="M15 41C15 41 28 25.5 28 15A13 13 0 1 0 2 15C2 25.5 15 41 15 41Z" fill="#e11d2e" stroke="#fff" strokeWidth="2.5"/>
      <circle cx="15" cy="15" r="4.6" fill="#fff"/>
    </svg>
  );

  return (
    <div className="cob">
      <span className="ck__label">④ Confirma tu ubicación</span>

      {estado === "inicio" && (
        <div>
          <p className="cob__hint" style={{ marginBottom: 10 }}>
            Repartimos solo en algunas zonas de San Cristóbal. Toca el botón y tu teléfono
            nos dice dónde estás — no tienes que escribir nada.
          </p>
          <button type="button" className="cob__btn" onClick={ubicar}>📍 Ubicarme automáticamente</button>
        </div>
      )}

      <div className="cob__wrap" style={{ display: hayMapa ? "block" : "none" }}>
        <div className="cob__mapa" ref={cajaRef} />
        {estado === "ubicando" && <div className="cob__pulso" />}
        {pinSVG}
      </div>

      <div className="cob__buscar">
        <div className="cob__hint">¿No encuentras tu casa en el mapa? Escribe tu calle o tu sector:</div>
        <div className="cob__fila">
          <input className="cob__input" type="text" value={q} placeholder="Ej: Quintas del Sur"
            onChange={function (ev) { setQ(ev.target.value); }}
            onKeyDown={function (ev) { if (ev.key === "Enter") { ev.preventDefault(); buscar(); } }} />
          <button type="button" className="cob__btn cob__btn--mini" style={{ marginTop: 0 }} onClick={buscar}>Buscar</button>
        </div>
        {buscando && <div className="cob__cargando">Buscando…</div>}
        {sug && sug.length > 0 && (
          <div className="cob__sug">
            {sug.map(function (it, i) {
              return (
                <button type="button" key={i} className="cob__sugitem"
                  onClick={function () { irA(it.lat, it.lng); }}>
                  📍 {String(it.nombre || "").split(",").slice(0, 3).join(",")}
                </button>
              );
            })}
          </div>
        )}
        {sug && sug.length === 0 && !buscando && (
          <div className="cob__hint">No encontramos ese lugar. Prueba con el nombre de la calle o del sector.</div>
        )}
      </div>

      {estado === "ubicando" && (
        <div className="cob__estado">
          <span className="cob__spin" />
          <span>Buscando tu ubicación{precision ? " · precisión " + precision + " m" : "…"}</span>
        </div>
      )}

      {estado === "cargando" && (
        <div className="cob__estado"><span className="cob__spin" /><span>Verificando la zona…</span></div>
      )}

      {estado === "ok" && (
        <div className="cob__aviso cob__aviso--si">
          <strong>✅ Sí llegamos hasta ahí.</strong>
          <p>Zona confirmada: {zona}.</p>
        </div>
      )}

      {estado === "fuera" && (
        <div className="cob__aviso cob__aviso--no">
          <strong>Todavía no repartimos en esa zona.</strong>
          <p>Puedes recoger tu pedido en el local, en General Cabral #90, sin costo de envío.</p>
          <button type="button" className="cob__btn cob__btn--alt" onClick={onPickup}>
            🏪 Cambiar a recoger en el local
          </button>
        </div>
      )}

      {(estado === "ok" || estado === "fuera") && hayMapa && (
        <div>
          <div className="cob__hint">
            ¿El punto rojo no está sobre tu casa? <strong>Mueve el mapa con el dedo</strong> hasta
            que quede encima. Se verifica solo.
          </div>
          <button type="button" className="cob__btn cob__btn--mini" onClick={ubicar}>
            📍 Volver a ubicarme
          </button>
        </div>
      )}

      {(estado === "sinpermiso" || estado === "error") && (
        <div className="cob__aviso cob__aviso--err">
          {msg}
          <div>
            <button type="button" className="cob__btn cob__btn--alt" onClick={ubicar}>Intentar otra vez</button>
          </div>
          {estado === "sinpermiso" && (
            <a className="cob__wa" href={COB_WHATSAPP} target="_blank" rel="noopener">Escribirnos por WhatsApp →</a>
          )}
        </div>
      )}
    </div>
  );
}
