const { useState, useEffect, useMemo, useCallback } = React;

const CATEGORIES = ["Todos", "Ofertas", "Verduras", "Frutas", "Almacén"];
const fmt    = window.ElyStore.formatPrice;
const fmtQty = window.ElyStore.formatQty;

function buildWhatsappMessage(items, config) {
  let total = 0;
  const lines = items.map(({ qty, product, subtotal, offerPrice }) => {
    total += subtotal;
    const tag = offerPrice != null ? " 🔥" : "";
    return `- ${fmtQty(qty, product.unit)} ${product.name} — ${fmt(subtotal)}${tag}`;
  });
  return [
    `¡Hola ${config.storeName}! 🛒 Quiero hacer el siguiente pedido:`,
    "",
    ...lines,
    "",
    `🟢 *Total Estimado: ${fmt(total)}*`,
    "",
    "¿Me confirman si tienen todo?",
  ].join("\n");
}

function buildWhatsappUrl(items, config) {
  if (!items.length || !config.whatsappNumber) return "";
  const msg = buildWhatsappMessage(items, config);
  return `https://wa.me/${config.whatsappNumber}?text=${encodeURIComponent(msg)}`;
}

const IconSearch = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="11" cy="11" r="7" /><path d="m21 21-4.3-4.3" />
  </svg>
);
const IconCart = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="9" cy="21" r="1.5" /><circle cx="18" cy="21" r="1.5" />
    <path d="M2.5 3h3l2.7 13.2a2 2 0 0 0 2 1.6h7.6a2 2 0 0 0 2-1.5L21.5 8H6" />
  </svg>
);
const IconClose = () => (
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M18 6 6 18M6 6l12 12" />
  </svg>
);
const IconTrash = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" />
  </svg>
);
const IconWhatsapp = () => (
  <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor">
    <path d="M.057 24l1.687-6.163a11.867 11.867 0 0 1-1.587-5.946C.16 5.335 5.495 0 12.05 0a11.817 11.817 0 0 1 8.413 3.488 11.824 11.824 0 0 1 3.48 8.414c-.003 6.557-5.338 11.892-11.893 11.892a11.9 11.9 0 0 1-5.688-1.448L.057 24zm6.597-3.807c1.676.995 3.276 1.591 5.392 1.592 5.448 0 9.886-4.434 9.889-9.885.002-5.462-4.415-9.89-9.881-9.892-5.452 0-9.887 4.434-9.889 9.884a9.86 9.86 0 0 0 1.51 5.26l-.999 3.648 3.978-1.607zm11.387-5.464c-.074-.124-.272-.198-.57-.347-.297-.149-1.758-.868-2.031-.967-.272-.099-.47-.149-.669.149-.198.297-.768.967-.941 1.165-.173.198-.347.223-.644.074-.297-.149-1.255-.462-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.297-.347.446-.521.151-.172.2-.296.3-.495.099-.198.05-.372-.025-.521-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.501-.669-.51l-.57-.01c-.198 0-.52.074-.792.372s-1.04 1.016-1.04 2.479 1.065 2.876 1.213 3.074c.149.198 2.095 3.2 5.076 4.487.71.306 1.263.489 1.694.626.712.226 1.36.194 1.872.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413z"/>
  </svg>
);

function Header({ cartCount, onOpenCart, config }) {
  return (
    <header className="ely-header">
      <div className="ely-header__inner">
        <a className="ely-logo" href="/" aria-label={config.storeName}>
          <img src="assets/logo-fresh.png" alt={config.storeName} />
        </a>
        <div className="ely-header__spacer" />
        <button className="ely-cart-btn" onClick={onOpenCart} aria-label="Abrir carrito">
          <IconCart />
          {cartCount > 0 && <span className="ely-cart-btn__badge">{cartCount}</span>}
        </button>
      </div>
    </header>
  );
}

function TaglineBand({ config }) {
  const tagline = config.tagline || "Frescura todos los días";
  return (
    <div className="ely-tagline-band">
      <img
        src="uploads/eslogan.png"
        alt={tagline}
        className="ely-tagline-img"
      />
    </div>
  );
}

function Toolbar({ query, setQuery, category, setCategory }) {
  return (
    <div className="ely-toolbar">
      <div className="ely-toolbar__inner">
        <div className="ely-search">
          <IconSearch />
          <input
            type="search"
            placeholder="Buscar productos…"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
        </div>
        <div className="ely-filters">
          {CATEGORIES.map((cat) => (
            <button
              key={cat}
              className={"ely-filter" + (category === cat ? " ely-filter--active" : "")}
              onClick={() => setCategory(cat)}
            >
              {cat}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

function ProductCard({ product, qtyInCart, onAdd, onInc, onDec }) {
  return (
    <article className={"ely-card" + (product.offers && product.offers.length > 0 ? " ely-card--offer" : "")}>
      <div className={"ely-card__image" + (product.image ? "" : " ely-card__image--placeholder")}>
        {product.image ? (
          <img
            src={product.image}
            alt={product.name}
            loading="lazy"
            onError={(e) => { e.currentTarget.style.display = "none"; }}
          />
        ) : (
          <span>{product.name}</span>
        )}
        <span className="ely-badge">{product.category}</span>
        {product.offers && product.offers.length > 0 && (
          <span className="ely-card__offer-badge">🔥 Oferta</span>
        )}
      </div>
      <div className="ely-card__body">
        <div className="ely-card__name">{product.name}</div>
        <div className="ely-card__price">
          <span className="ely-card__price-amount">{fmt(product.price)}</span>
          <span className="ely-card__price-unit">/ {product.unit}</span>
        </div>
        <div style={{ marginTop: "auto", position: "relative" }}>
          <button className="ely-add-btn" onClick={onAdd}>
            Agregar
            {qtyInCart > 0 && (
              <span className="ely-add-btn__badge">{qtyInCart} {product.unit.replace("kg", "kg")}</span>
            )}
          </button>
        </div>
      </div>
    </article>
  );
}

function CartPanel({ open, onClose, items, products, onInc, onDec, onRemove, config }) {
  const detailed = useMemo(() => (
    items
      .map((it) => {
        const p = products.find((x) => x.id === it.id);
        if (!p) return null;
        return { ...it, product: p, subtotal: it.offerPrice != null ? it.offerPrice : Math.round(p.price * it.qty) };
      })
      .filter(Boolean)
  ), [items, products]);

  const total = detailed.reduce((acc, it) => acc + it.subtotal, 0);
  const waUrl = useMemo(() => buildWhatsappUrl(detailed, config), [detailed, config]);

  return (
    <>
      <div
        className={"ely-cart-overlay" + (open ? " ely-cart-overlay--open" : "")}
        onClick={onClose}
      />
      <aside
        className={"ely-cart-panel" + (open ? " ely-cart-panel--open" : "")}
        aria-hidden={!open}
      >
        <div className="ely-cart-header">
          <h2>Tu pedido</h2>
          <button className="ely-cart-close" onClick={onClose} aria-label="Cerrar carrito">
            <IconClose />
          </button>
        </div>

        <div className="ely-cart-body">
          {detailed.length === 0 ? (
            <div className="ely-cart-empty">
              <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="9" cy="21" r="1.5" /><circle cx="18" cy="21" r="1.5" />
                <path d="M2.5 3h3l2.7 13.2a2 2 0 0 0 2 1.6h7.6a2 2 0 0 0 2-1.5L21.5 8H6" />
              </svg>
              <div className="ely-cart-empty__title">Tu carrito está vacío</div>
              <div style={{ fontSize: 14 }}>
                Agregá productos del catálogo
              </div>
            </div>
          ) : (
            detailed.map(({ cartId, qty, product, subtotal, offerPrice }) => (
              <div key={cartId} className="ely-cart-item">
                <div className="ely-cart-item__img">
                  {product.image && <img src={product.image} alt={product.name} />}
                </div>
                <div className="ely-cart-item__info">
                  <div className="ely-cart-item__name">{product.name}{offerPrice != null && <span className="ely-cart-item__offer-badge">🔥</span>}</div>
                  <div className="ely-cart-item__meta">
                    {fmt(product.price)} / {product.unit}
                  </div>
                </div>
                <div>
                  <div className="ely-cart-item__subtotal">{fmt(subtotal)}</div>
                  <div className="ely-cart-item__controls">
                    <button className="ely-cart-item__qty-btn" onClick={() => onDec(cartId)} aria-label="Disminuir cantidad">−</button>
                    <span className="ely-cart-item__qty-value">{fmtQty(qty, product.unit)}</span>
                    <button className="ely-cart-item__qty-btn" onClick={() => onInc(cartId)} aria-label="Aumentar cantidad">+</button>
                    <button className="ely-cart-item__remove" onClick={() => onRemove(cartId)} aria-label="Eliminar producto">
                      <IconTrash />
                    </button>
                  </div>
                </div>
              </div>
            ))
          )}
        </div>

        <div className="ely-cart-footer">
          <div className="ely-cart-total">
            <span className="ely-cart-total__label">Total</span>
            <span className="ely-cart-total__amount">{fmt(total)}</span>
          </div>
          {detailed.length === 0 ? (
            <button className="ely-whatsapp-btn" disabled>
              <IconWhatsapp />
              Confirmar x WhatsApp
            </button>
          ) : (
            <a
              className="ely-whatsapp-btn"
              href={waUrl}
              target="_blank"
              rel="noopener noreferrer"
            >
              <IconWhatsapp />
              Confirmar x WhatsApp
            </a>
          )}
        </div>
      </aside>
    </>
  );
}

const TRUST_ITEMS = [
  {
    label: "Productos\nseleccionados",
    icon: (
      <svg viewBox="0 0 32 32"><path d="M5 11h22l-2.4 13.5a3 3 0 0 1-3 2.5H10.4a3 3 0 0 1-3-2.5L5 11z"/><path d="M10 11l2-5h8l2 5"/><path d="M13 16v6M19 16v6M16 16v6"/></svg>
    ),
  },
  {
    label: "Siempre\nfrescos",
    icon: (
      <svg viewBox="0 0 32 32"><path d="M16 27c-6 0-10-4-10-9 0-5 4-9 10-9s10 4 10 9c0 5-4 9-10 9z"/><path d="M16 27V16M16 16c-3-2-3-6 0-9M16 16c3-2 3-6 0-9"/></svg>
    ),
  },
  {
    label: "Comer sano\nhace bien",
    icon: (
      <svg viewBox="0 0 32 32"><path d="M16 27S5 20 5 12.5 11 4 16 9c5-5 11-1 11 3.5S16 27 16 27z"/><path d="M16 14c-1.5-1-3 0-3 2M16 14c1.5-1 3 0 3 2"/></svg>
    ),
  },
  {
    label: "Pedí online\ny retirá en el local",
    icon: (
      <svg viewBox="0 0 32 32" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 13v13h24V13"/><path d="M2 10l3-6h22l3 6"/><path d="M2 10h28"/><path d="M12 10v3a4 4 0 0 0 8 0v-3"/><path d="M13 26v-7h6v7"/></svg>
    ),
  },
];

function TrustBand() {
  return (
    <section className="ely-trust-band">
      <div className="ely-trust-band__inner">
        {TRUST_ITEMS.map((it, i) => (
          <div className="ely-trust-item" key={i}>
            {it.icon}
            <div className="ely-trust-item__label">
              {it.label.split("\n").map((line, j) => (
                <div key={j}>{line}</div>
              ))}
            </div>
          </div>
        ))}
        <div className="ely-trust-tagline">Elegí fresco,<br/>elegí bien</div>
      </div>
    </section>
  );
}

function Footer({ config }) {
  const waHref = `https://wa.me/${config.whatsappNumber}`;
  return (
    <footer className="ely-footer">
      <div className="ely-footer__inner">
        <div className="ely-footer__brand">
          <img src="uploads/logo-footer.png" alt={config.storeName} />
        </div>
        <div className="ely-footer__info">
          <strong>{config.storeName}</strong>
          <div className="ely-footer__row">📍 {config.address}</div>
          <div className="ely-footer__row">🕒 {config.hours}</div>
          <div className="ely-footer__row">
            💬 <a href={waHref} target="_blank" rel="noreferrer">WhatsApp: +{config.whatsappNumber}</a>
          </div>
          <div className="ely-footer__admin">
            <a href="admin.html">Acceso administrador</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

const KG_QUICK = [
  { label: "250g", value: 0.25 },
  { label: "½ kg", value: 0.5 },
  { label: "1 kg", value: 1 },
];

function AddToCartModal({ product, onConfirm, onCancel }) {
  const [qty, setQty] = useState(1);
  const [offerPrice, setOfferPrice] = useState(null);
  const isKg = product.unit === "kg";
  const offers = product.offers || [];

  const canDec = window.ElyStore.nextQty(qty, product.unit, -1) !== null;
  const canInc = window.ElyStore.nextQty(qty, product.unit, +1) !== null;

  const inc = () => {
    const next = window.ElyStore.nextQty(qty, product.unit, +1);
    if (next !== null) { setQty(next); setOfferPrice(null); }
  };
  const dec = () => {
    const next = window.ElyStore.nextQty(qty, product.unit, -1);
    if (next !== null) { setQty(next); setOfferPrice(null); }
  };

  return (
    <div className="ely-modal-overlay" onClick={onCancel}>
      <div className="ely-modal" onClick={(e) => e.stopPropagation()}>
        <h3 className="ely-modal__title">¿Cuánto llevás?</h3>
        <p className="ely-modal__subtitle">{product.name}</p>
        <div className="ely-modal__qty-box">
          <button
            className="ely-modal__stepper"
            onClick={dec}
            disabled={!canDec}
            aria-label="Disminuir"
          >−</button>
          <span className="ely-modal__qty-value">{fmtQty(qty, product.unit)}</span>
          <button
            className="ely-modal__stepper"
            onClick={inc}
            disabled={!canInc}
            aria-label="Aumentar"
          >+</button>
        </div>
        {isKg && (
          <div className="ely-modal__chips">
            {KG_QUICK.map(({ label, value }) => (
              <button
                key={label}
                className={"ely-modal__chip" + (Math.abs(qty - value) < 1e-6 && offerPrice == null ? " ely-modal__chip--active" : "")}
                onClick={() => { setQty(value); setOfferPrice(null); }}
              >
                {label}
              </button>
            ))}
          </div>
        )}
        {offers.length > 0 && (
          <div className="ely-modal__offers">
            <div className="ely-modal__offers-title">🔥 Ofertas</div>
            {offers.map((offer) => {
              const isActive = Math.abs(qty - offer.qty) < 1e-6 && offerPrice === offer.price;
              const saving = Math.round(product.price * offer.qty) - offer.price;
              return (
                <button
                  key={offer.qty}
                  className={"ely-modal__offer-chip" + (isActive ? " ely-modal__offer-chip--active" : "")}
                  onClick={() => { setQty(offer.qty); setOfferPrice(offer.price); }}
                >
                  <span>{fmtQty(offer.qty, product.unit)} por {fmt(offer.price)}</span>
                  {saving > 0 && <span className="ely-modal__offer-saving">Ahorrás {fmt(saving)}</span>}
                </button>
              );
            })}
          </div>
        )}
        <div className="ely-modal__actions">
          <button className="ely-modal__btn-cancel" onClick={onCancel}>Cancelar</button>
          <button className="ely-modal__btn-confirm" onClick={() => onConfirm(qty, offerPrice)}>Añadir</button>
        </div>
      </div>
    </div>
  );
}

function ComingSoon({ config }) {
  return (
    <div className="ely-coming-soon">
      <div className="ely-coming-soon__content">
        <h1 className="ely-coming-soon__title">¡Nos estamos preparando para vos!</h1>
        <p className="ely-coming-soon__subtitle">Muy pronto abrimos.</p>
        <img src="uploads/logo-footer.png" alt={config.storeName} className="ely-coming-soon__logo" />
        <div className="ely-coming-soon__info">
          <p>{config.address}</p>
        </div>
      </div>
    </div>
  );
}

function App() {
  const [products, setProducts] = useState([]);
  const [config, setConfig]     = useState({ ...window.ELY_CONFIG });
  const [cart, setCart]         = useState(() => window.ElyStore.loadCart());
  const [loaded, setLoaded]     = useState(false);
  const [query, setQuery]       = useState("");
  const [category, setCategory] = useState("Todos");
  const [cartOpen, setCartOpen] = useState(false);
  const [modalProduct, setModalProduct] = useState(null);

  useEffect(() => {
    const unsubP = window.ElyStore.subscribeProducts((list, err) => {
      if (err) console.error("subscribeProducts", err);
      if (list) setProducts(list);
      setLoaded(true);
    });
    const unsubC = window.ElyStore.subscribeConfig((cfg, err) => {
      if (err) console.error("subscribeConfig", err);
      if (cfg) setConfig(cfg);
    });
    return () => { unsubP(); unsubC(); };
  }, []);

  useEffect(() => {
    window.ElyStore.saveCart(cart);
  }, [cart]);

  const visibleProducts = useMemo(() => {
    const q = query.trim().toLowerCase();
    return products
      .filter((p) => p.active)
      .filter((p) => category === "Todos" || (category === "Ofertas" ? p.offers && p.offers.length > 0 : p.category === category))
      .filter((p) => !q || p.name.toLowerCase().includes(q));
  }, [products, query, category]);

  useEffect(() => {
    const validIds = new Set(products.filter((p) => p.active).map((p) => p.id));
    setCart((curr) => curr.filter((it) => validIds.has(it.id)));
  }, [products]);

  const openModal = useCallback((id) => {
    const product = products.find((p) => p.id === id);
    if (product) setModalProduct(product);
  }, [products]);

  const confirmAddToCart = useCallback((qty, offerPrice) => {
    if (!modalProduct) return;
    setCart((curr) => {
      const item = { id: modalProduct.id, qty, cartId: Date.now().toString(36) };
      if (offerPrice != null) item.offerPrice = offerPrice;
      return [...curr, item];
    });
    setModalProduct(null);
  }, [modalProduct]);

  const incItem = useCallback((cartId) => {
    setCart((curr) => {
      const item = curr.find((it) => it.cartId === cartId);
      if (!item) return curr;
      const product = products.find((p) => p.id === item.id);
      if (!product) return curr;
      const next = window.ElyStore.nextQty(item.qty, product.unit, +1);
      if (next === null) return curr;
      return curr.map((it) => it.cartId === cartId ? { ...it, qty: next, offerPrice: undefined } : it);
    });
  }, [products]);

  const decItem = useCallback((cartId) => {
    setCart((curr) => {
      const item = curr.find((it) => it.cartId === cartId);
      if (!item) return curr;
      const product = products.find((p) => p.id === item.id);
      if (!product) return curr;
      const next = window.ElyStore.nextQty(item.qty, product.unit, -1);
      if (next === null) return curr.filter((it) => it.cartId !== cartId);
      return curr.map((it) => it.cartId === cartId ? { ...it, qty: next, offerPrice: undefined } : it);
    });
  }, [products]);

  const removeItem = useCallback((cartId) => {
    setCart((curr) => curr.filter((it) => it.cartId !== cartId));
  }, []);

  const qtyOf = useCallback((id) => {
    const it = cart.find((x) => x.id === id);
    return it ? it.qty : 0;
  }, [cart]);

  const cartCount = cart.length;

  if (config.comingSoon) {
    return <ComingSoon config={config} />;
  }

  return (
    <>
      <Header cartCount={cartCount} onOpenCart={() => setCartOpen(true)} config={config} />
      <TaglineBand config={config} />
      <Toolbar
        query={query} setQuery={setQuery}
        category={category} setCategory={setCategory}
      />

      <main className="ely-grid-wrap">
        {!loaded ? (
          <div className="ely-empty">
            <div className="ely-empty__title">Cargando catálogo…</div>
          </div>
        ) : visibleProducts.length === 0 ? (
          <div className="ely-empty">
            <div className="ely-empty__title">Sin resultados</div>
            <div>Probá con otra palabra o categoría.</div>
          </div>
        ) : (
          <div className="ely-grid">
            {visibleProducts.map((p) => (
              <ProductCard
                key={p.id}
                product={p}
                qtyInCart={qtyOf(p.id)}
                onAdd={() => openModal(p.id)}
                onInc={() => incItem(p.id)}
                onDec={() => decItem(p.id)}
              />
            ))}
          </div>
        )}
      </main>

      <TrustBand />
      <Footer config={config} />

      {cartCount > 0 && !cartOpen && (
        <button className="ely-fab" onClick={() => setCartOpen(true)} aria-label="Ver carrito">
          <IconCart />
          <span className="ely-fab__badge">{cartCount}</span>
        </button>
      )}

      <CartPanel
        open={cartOpen}
        onClose={() => setCartOpen(false)}
        items={cart}
        products={products}
        onInc={incItem}
        onDec={decItem}
        onRemove={removeItem}
        config={config}
      />

      {modalProduct && (
        <AddToCartModal
          product={modalProduct}
          onConfirm={confirmAddToCart}
          onCancel={() => setModalProduct(null)}
        />
      )}
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
