/* global React, ReactDOM, Icon, Button, Badge, Sheet, ToastHost,
   HomeScreen, CatalogScreen, ProductScreen, CartScreen, CheckoutScreen,
   ServicesScreen, WholesaleScreen, FilterContent, BotFlow, useState, useEffect */

function Header({ route, go, cartCount, shipBar = true }) {
  const titles = { catalog: "Catálogo", cart: "Tu carrito", checkout: "Checkout", services: "Servicios", mayorista: "Mayorista", confirm: "Compra confirmada" };
  const showBack = ["checkout"].includes(route);
  return (
    <div className="ng-header">
      {route === "home" && shipBar && (
        <div className="ng-ship-bar"><Icon name="truck" size={13} stroke={2.5} />Envío gratis en Chivilcoy · Asesoramiento sin cargo</div>
      )}
      <div className="ng-header__bar">
        {showBack ? (
          <button className="btn--icon" style={ic} onClick={() => go(-1)} aria-label="Volver"><Icon name="arrowL" /></button>
        ) : (
          <button onClick={() => go("home")} style={{ background: "none", border: "none", padding: 0, textAlign: "left" }}>
            <span className="wordmark">Nogo<b>paint</b></span>
            <span className="wordmark-note">wordmark placeholder</span>
          </button>
        )}
        {route === "home" || route === "catalog" ? (
          <div className="searchbar" onClick={() => go("catalog")}>
            <Icon name="search" size={18} />
            <input placeholder="Buscar productos o colores" readOnly={route !== "catalog"} />
          </div>
        ) : (
          <span className="fw-7 strong t-lg" style={{ flex: 1, textAlign: "center" }}>{titles[route]}</span>
        )}
        <button className="btn--icon cart-btn" style={ic} onClick={() => go("cart")} aria-label="Carrito">
          <Icon name="cart" />
          {cartCount > 0 && <span className="cart-count">{cartCount}</span>}
        </button>
      </div>
    </div>
  );
}
const ic = { width: 44, height: 44, display: "grid", placeItems: "center", borderRadius: 12 };

function TabBar({ route, go, cartCount }) {
  const tabs = [
    { id: "home", label: "Inicio", icon: "home" },
    { id: "catalog", label: "Catálogo", icon: "grid" },
    { id: "cart", label: "Carrito", icon: "cart", badge: cartCount },
    { id: "services", label: "Servicios", icon: "spark" },
    { id: "mayorista", label: "Mayorista", icon: "store" },
  ];
  return (
    <div className="tabbar">
      {tabs.map((t) => (
        <button key={t.id} className={`tabbar__item ${route === t.id ? "tabbar__item--active" : ""}`} onClick={() => go(t.id)}>
          <span style={{ position: "relative" }}>
            <Icon name={t.icon} size={22} stroke={route === t.id ? 2.4 : 2} />
            {t.badge > 0 && <span className="cart-count" style={{ top: -6, right: -10, minWidth: 16, height: 16, fontSize: 10 }}>{t.badge}</span>}
          </span>
          {t.label}
        </button>
      ))}
    </div>
  );
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#0077b6",
  "radius": "redondo",
  "display": "Schibsted Grotesk",
  "shipBar": true
}/*EDITMODE-END*/;

// Paletas de acento curadas: cada una recalcula la rampa primary por hue
const ACCENTS = {
  "#0077b6": { soft: "#e6f7ff", s200: "#99d7f4", s300: "#5fbcea", s500: "#0a87c6", s700: "#005d8f", s900: "#003f63" },
  "#1f8a5b": { soft: "#e6f4ed", s200: "#a9dcc5", s300: "#74c7a3", s500: "#23a06b", s700: "#13633f", s900: "#0d4630" },
  "#e8521e": { soft: "#fdeee7", s200: "#f9c9b3", s300: "#f4a684", s500: "#f06a36", s700: "#b53d10", s900: "#7a2c0e" },
  "#102a3a": { soft: "#e9f2f8", s200: "#c4d6e2", s300: "#93a8b6", s500: "#24414f", s700: "#16303d", s900: "#0a1c27" },
};
const RADII = {
  "recto":  { sm: "3px", md: "5px", lg: "7px", xl: "10px" },
  "medio":  { sm: "6px", md: "10px", lg: "14px", xl: "20px" },
  "redondo":{ sm: "10px", md: "16px", lg: "22px", xl: "28px" },
};

function App() {
  const NOGO = window.NOGO;
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useEffect(() => {
    const r = document.documentElement.style;
    const a = ACCENTS[t.accent] || ACCENTS["#0077b6"];
    r.setProperty("--color-primary-600", t.accent);
    r.setProperty("--color-primary-700", a.s700);
    r.setProperty("--color-primary-800", a.s700);
    r.setProperty("--color-primary-900", a.s900);
    r.setProperty("--color-primary-500", a.s500);
    r.setProperty("--color-primary-300", a.s300);
    r.setProperty("--color-primary-200", a.s200);
    r.setProperty("--color-primary-50", a.soft);
    const rad = RADII[t.radius] || RADII.medio;
    Object.entries(rad).forEach(([k, v]) => r.setProperty(`--radius-${k}`, v));
    r.setProperty("--font-display", `"${t.display}", "Helvetica Neue", Arial, sans-serif`);
  }, [t.accent, t.radius, t.display]);

  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 [filterOpen, setFilterOpen] = useState(false);
  const [bot, setBot] = useState(null);          // {product, presId, color}
  const [toasts, setToasts] = useState([]);

  const go = (to) => {
    if (to === -1) { setStack((s) => (s.length > 1 ? s.slice(0, -1) : s)); return; }
    if (to === route) return;
    setStack((s) => [...s, to]);
  };
  const openProduct = (p) => { setProduct(p); setStack((s) => [...s, "product"]); };

  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" });
    setStack((s) => (s[s.length - 1] === "product" ? s.slice(0, -1) : s));
  };

  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"]); };
  // limpiar carrito al confirmar
  useEffect(() => { if (route === "confirm") { setTimeout(() => setCart([]), 400); } }, [route]);

  const openFilters = (k, v) => {
    if (k) { setFilters((f) => ({ ...f, [k]: f[k] === v ? null : v })); }
    else setFilterOpen(true);
  };

  const showChrome = !["product", "checkout", "confirm"].includes(route) || route === "checkout";
  const showTabs = ["home", "catalog", "cart", "services", "mayorista"].includes(route);

  return (
    <div className="ng-app">
      {route !== "product" && route !== "confirm" && <Header route={route} go={go} cartCount={cartCount} shipBar={t.shipBar} />}

      {route === "home" && <HomeScreen go={go} openProduct={openProduct} startAdvisor={startAdvisor} />}
      {route === "catalog" && <CatalogScreen openProduct={openProduct} openFilters={openFilters} filters={filters} />}
      {route === "product" && product && <ProductScreen product={product} go={go} onAdd={onAdd} />}
      {route === "cart" && <CartScreen cart={cart} setQty={setQty} removeItem={removeItem} go={go} />}
      {route === "checkout" && <CheckoutScreen cart={cart} go={go} onPlace={onPlace} />}
      {route === "services" && <ServicesScreen />}
      {route === "mayorista" && <WholesaleScreen />}
      {route === "confirm" && <ConfirmScreen go={go} />}

      {showTabs && <TabBar route={route} go={go} cartCount={cartCount} />}

      {filterOpen && (
        <Sheet title="Filtros" onClose={() => setFilterOpen(false)}
          footer={<div className="row gap-3"><Button variant="ghost" onClick={() => setFilters({ use: null, colorFam: null })}>Limpiar</Button><Button block onClick={() => setFilterOpen(false)}>Ver resultados</Button></div>}>
          <FilterContent filters={filters} setFilters={setFilters} onClose={() => setFilterOpen(false)} />
        </Sheet>
      )}

      {bot && (
        <>
          <div className="overlay" onClick={() => setBot(null)} />
          <div className="sheet" style={{ height: "92%" }}>
            <BotFlow product={bot.product} presId={bot.presId} color={bot.color} onConfirm={onBotConfirm} onClose={() => setBot(null)} />
          </div>
        </>
      )}

      {toasts.length > 0 && <ToastHost toasts={toasts} />}

      {!window.NOGO_DEPLOY_MODE && window.TweaksPanel && ReactDOM.createPortal(
        <TweaksPanel title="Tweaks">
          <TweakSection label="Dirección visual" />
          <TweakColor label="Color primario" value={t.accent}
            options={["#0077b6", "#1f8a5b", "#e8521e", "#102a3a"]}
            onChange={(v) => setTweak("accent", v)} />
          <TweakRadio label="Esquinas" value={t.radius}
            options={["recto", "medio", "redondo"]}
            onChange={(v) => setTweak("radius", v)} />
          <TweakSelect label="Tipografía titulares" value={t.display}
            options={["Schibsted Grotesk", "Hanken Grotesk", "Space Grotesk", "Archivo"]}
            onChange={(v) => setTweak("display", v)} />
          <TweakSection label="Contenido" />
          <TweakToggle label="Barra de envío gratis" value={t.shipBar}
            onChange={(v) => setTweak("shipBar", v)} />
        </TweaksPanel>,
        document.body
      )}
    </div>
  );
}

function ConfirmScreen({ go }) {
  return (
    <div className="ng-screen" style={{ display: "grid", placeItems: "center", background: "var(--bg-surface)" }}>
      <div className="col gap-3" style={{ alignItems: "center", textAlign: "center", padding: 32 }}>
        <span style={{ width: 76, height: 76, borderRadius: 999, background: "var(--color-success-50)", color: "var(--color-success-600)", display: "grid", placeItems: "center", animation: "pop .4s" }}><Icon name="check" size={40} stroke={3} /></span>
        <h1 className="t-2xl">¡Gracias por tu compra!</h1>
        <p className="t-sm muted" style={{ maxWidth: 260 }}>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" }}>
          <div className="row between t-sm"><span className="muted">N° de pedido</span><span className="strong fw-7">#NGP-{Math.floor(1000 + Math.random() * 9000)}</span></div>
        </div>
        <Button block onClick={() => go("home")}>Volver al inicio</Button>
      </div>
    </div>
  );
}

Object.assign(window, { MobileApp: App });

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