/* global React, ReactDOM, Icon, Button, Badge, ToastHost, BotFlow,
   DtHome, DtCatalog, DtProduct, DtCart, DtCheckout, DtServices, DtWholesale,
   ChromeWindow, useState, useEffect */

function DtHeader({ route, go, cartCount }) {
  const nav = [["catalog", "Productos"], ["services", "Servicios"], ["mayorista", "Mayorista"]];
  return (
    <header className="dt-header">
      <div className="dt-shipbar"><Icon name="truck" size={15} stroke={2.5} />Envío gratis en Chivilcoy · Asesoramiento experto sin cargo · Retiro en sucursal</div>
      <div className="dt-wrap">
        <div className="dt-headbar">
          <button onClick={() => go("home")} style={{ background: "none", border: "none", cursor: "pointer", textAlign: "left", padding: 0 }}>
            <span className="wordmark" style={{ fontSize: "var(--text-2xl)" }}>Nogo<b>paint</b></span>
            <span className="wordmark-note">wordmark placeholder</span>
          </button>
          <nav className="dt-nav">
            {nav.map(([id, label]) => (
              <button key={id} className={["catalog", "product"].includes(route) && id === "catalog" ? "active" : route === id ? "active" : ""} onClick={() => go(id)}>{label}</button>
            ))}
          </nav>
          <div className="dt-search" onClick={() => go("catalog")}>
            <Icon name="search" size={20} />
            <input placeholder="Buscar productos o colores…" readOnly />
          </div>
          <div className="dt-headicons">
            <button className="dt-iconbtn" aria-label="Mi cuenta"><Icon name="user" /></button>
            <button className="dt-iconbtn" aria-label="Carrito" onClick={() => go("cart")}>
              <Icon name="cart" />
              {cartCount > 0 && <span className="cart-count" style={{ top: 6, right: 6 }}>{cartCount}</span>}
            </button>
          </div>
        </div>
      </div>
    </header>
  );
}

function DtFooter({ go }) {
  const NOGO = window.NOGO;
  return (
    <footer className="dt-footer">
      <div className="dt-wrap">
        <div className="dt-footer-grid">
          <div>
            <span className="wordmark" style={{ color: "#fff", fontSize: "var(--text-2xl)" }}>Nogo<b style={{ color: "var(--color-primary-400)" }}>paint</b></span>
            <p style={{ marginTop: 14, maxWidth: 280 }}>Pinturería monomarca con asesoramiento experto. Sucursales en Buenos Aires, Entre Ríos y La Pampa.</p>
          </div>
          <div>
            <h4>Productos</h4>
            <a onClick={() => go("catalog")} style={{ cursor: "pointer" }}>Interior</a>
            <a onClick={() => go("catalog")} style={{ cursor: "pointer" }}>Exterior</a>
            <a onClick={() => go("catalog")} style={{ cursor: "pointer" }}>Esmaltes</a>
            <a onClick={() => go("catalog")} style={{ cursor: "pointer" }}>Impermeabilizantes</a>
          </div>
          <div>
            <h4>Servicios</h4>
            <a onClick={() => go("services")} style={{ cursor: "pointer" }}>Asesoramiento</a>
            <a onClick={() => go("services")} style={{ cursor: "pointer" }}>Mano de obra</a>
            <a onClick={() => go("mayorista")} style={{ cursor: "pointer" }}>Cuenta mayorista</a>
          </div>
          <div>
            <h4>Sucursales</h4>
            {NOGO.branches.slice(0, 4).map((b) => <p key={b.city}>{b.city}</p>)}
          </div>
        </div>
        <div className="dt-footer-bottom">
          <span>© 2026 Nogopaint. Todos los derechos reservados.</span>
          <span>Medios de pago: Mercado Pago · Transferencia · Efectivo en sucursal</span>
        </div>
      </div>
    </footer>
  );
}

function DtApp({ scale = 1 }) {
  const NOGO = window.NOGO;
  const [stack, setStack] = useState(["home"]);
  const route = stack[stack.length - 1];
  const [product, setProduct] = useState(null);
  const [cart, setCart] = useState([]);
  const [filters, setFilters] = useState({ use: null, colorFam: null });
  const [bot, setBot] = useState(null);
  const [toasts, setToasts] = useState([]);
  const scrollRef = React.useRef(null);

  const go = (to) => {
    if (to === route && to !== "catalog") return;
    setStack((s) => [...s, to]);
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
  };
  const openProduct = (p) => { setProduct(p); setStack((s) => [...s, "product"]); if (scrollRef.current) scrollRef.current.scrollTop = 0; };

  const addToast = (msg, opts = {}) => {
    const id = Date.now() + Math.random();
    setToasts((t) => [...t, { id, msg, ...opts }]);
    setTimeout(() => setToasts((t) => t.filter((x) => x.id !== id)), 2600);
  };
  const cartCount = cart.reduce((n, i) => n + i.qty, 0);
  const onAdd = ({ product, presId, color }) => setBot({ product, presId, color });
  const startAdvisor = () => {
    const product = NOGO.products.find((p) => p.featured) || NOGO.products[0];
    const presId = product.pres[Math.min(1, product.pres.length - 1)];
    const fam = product.colors[0];
    const color = NOGO.palette[fam][2] || NOGO.palette[fam][0];
    setBot({ product, presId, color });
  };

  useEffect(() => {
    if (window.NOGO_DEPLOY_MODE && window.location.hash === "#asesor") {
      startAdvisor();
    }
  }, []);

  const onBotConfirm = (items) => {
    setCart((prev) => {
      const next = [...prev];
      items.forEach((it) => {
        const k = next.findIndex((x) => x.productId === it.productId && x.presId === it.presId && (x.color?.hex || null) === (it.color?.hex || null));
        if (k >= 0) next[k] = { ...next[k], qty: next[k].qty + it.qty };
        else next.push(it);
      });
      return next;
    });
    setBot(null);
    addToast("Agregado al carrito", { tone: "success", icon: "check" });
  };

  const setQty = (idx, q) => setCart((c) => c.map((it, i) => (i === idx ? { ...it, qty: q } : it)));
  const removeItem = (idx) => setCart((c) => c.filter((_, i) => i !== idx));
  const onPlace = () => { setStack((s) => [...s, "confirm"]); setTimeout(() => setCart([]), 400); };

  return (
    <div className="dt-root" ref={scrollRef} style={{ height: "100%", overflowY: "auto" }}>
      <DtHeader route={route} go={go} cartCount={cartCount} />

      {route === "home" && <DtHome go={go} openProduct={openProduct} startAdvisor={startAdvisor} />}
      {route === "catalog" && <DtCatalog openProduct={openProduct} filters={filters} setFilters={setFilters} />}
      {route === "product" && product && <DtProduct product={product} go={go} onAdd={onAdd} />}
      {route === "cart" && <DtCart cart={cart} setQty={setQty} removeItem={removeItem} go={go} />}
      {route === "checkout" && <DtCheckout cart={cart} go={go} onPlace={onPlace} />}
      {route === "services" && <DtServices />}
      {route === "mayorista" && <DtWholesale />}
      {route === "confirm" && <DtConfirm go={go} />}

      <DtFooter go={go} />

      {bot && ReactDOM.createPortal(
        <div className="dt-modal-overlay" onClick={(e) => { if (e.target.classList.contains("dt-modal-overlay")) setBot(null); }}>
          <div className="dt-modal" style={{ transform: `scale(${scale})` }}>
            <BotFlow product={bot.product} presId={bot.presId} color={bot.color} onConfirm={onBotConfirm} onClose={() => setBot(null)} />
          </div>
        </div>,
        document.body
      )}

      {toasts.length > 0 && ReactDOM.createPortal(
        <div style={{ position: "fixed", bottom: 24, left: "50%", transform: "translateX(-50%)", zIndex: 1450, display: "flex", flexDirection: "column", gap: 8 }}>
          {toasts.map((t) => <div key={t.id} className={`toast ${t.tone ? "toast--" + t.tone : ""}`}><Icon name={t.icon || "check"} size={18} stroke={2.5} />{t.msg}</div>)}
        </div>,
        document.body
      )}
    </div>
  );
}

function DtConfirm({ go }) {
  return (
    <div className="dt-wrap" style={{ padding: "100px 0", display: "grid", placeItems: "center", textAlign: "center" }}>
      <div className="col gap-4" style={{ alignItems: "center", maxWidth: 440 }}>
        <span style={{ width: 88, height: 88, borderRadius: 999, background: "var(--color-success-50)", color: "var(--color-success-600)", display: "grid", placeItems: "center" }}><Icon name="check" size={44} stroke={3} /></span>
        <h1 className="dt-h1" style={{ fontSize: "var(--text-4xl)" }}>¡Gracias por tu compra!</h1>
        <p className="t-lg muted">Te enviamos el comprobante por email. Podés seguir tu pedido desde Mi cuenta.</p>
        <div className="card ng-pad" style={{ width: "100%", textAlign: "left", padding: 24 }}>
          <div className="row between"><span className="muted">N° de pedido</span><span className="strong fw-7 t-lg">#NGP-{Math.floor(1000 + Math.random() * 9000)}</span></div>
        </div>
        <Button size="lg" onClick={() => go("home")}>Volver al inicio</Button>
      </div>
    </div>
  );
}

/* Montaje con escalado dentro del marco de navegador */
function Root() {
  const [scale, setScale] = useState(1);
  const W = 1280, H = 820;
  useEffect(() => {
    const fit = () => setScale(Math.min(1, (window.innerWidth - 48) / W, (window.innerHeight - 48) / H));
    fit(); window.addEventListener("resize", fit); return () => window.removeEventListener("resize", fit);
  }, []);
  return (
    <div style={{ transform: `scale(${scale})`, transformOrigin: "center center" }}>
      <ChromeWindow width={W} height={H} url="nogopaint.com.ar" tabs={[{ title: "Nogopaint — Pinturería online" }]}>
        <DtApp scale={scale} />
      </ChromeWindow>
    </div>
  );
}

Object.assign(window, { DtApp, DtHeader, DtFooter });

if (!window.NOGO_SKIP_AUTOMOUNT) {
  ReactDOM.createRoot(document.getElementById("root")).render(<Root />);
}
