/* global React, Icon, Button, Badge, ProductCard, CanVisual, ProductMedia, SwatchGrid, PresentationSelector, StockLabel, useState, useEffect, useRef */

/* ============================ HOME ============================ */
// Paleta acotada para el hero interactivo: cruza familias reales de NOGO.palette
// (azul de marca + frío + cálido + verde + neutro) — variedad sin choques de color.
const HERO_COLORS = [
  { name: "Azul Nogopaint", hex: "#0077b6" },
  { name: "Azul Noche", hex: "#283a63" },
  { name: "Terracota", hex: "#bd6a48" },
  { name: "Verde Salvia", hex: "#9aa881" },
  { name: "Gris Plomo", hex: "#73767a" },
];

function HomeScreen({ go, openProduct, startAdvisor }) {
  const NOGO = window.NOGO;
  const featured = NOGO.products.filter((p) => p.featured);
  const [heroColor, setHeroColor] = useState(HERO_COLORS[0]);
  const [heroTick, setHeroTick] = useState(0);
  const pickHeroColor = (c) => { setHeroColor(c); setHeroTick((t) => t + 1); };
  const heroKey = `${heroColor.hex}-${heroTick}`;
  const cats = [
    { id: "interior", label: "Interior", icon: "home", hex: "#a8c8e0" },
    { id: "exterior", label: "Exterior", icon: "shield", hex: "#9aa881" },
    { id: "esmaltes", label: "Esmaltes", icon: "brush", hex: "#e8a48b" },
    { id: "impermeab", label: "Impermeab.", icon: "drop", hex: "#cdbfa3" },
  ];
  return (
    <div className="ng-screen">
      {/* Hero */}
      <div className="paint-hero">
        <div className="paint-hero__copy">
          <Badge tone="primary" icon="spark">Asesoramiento experto, gratis</Badge>
          <h1>Pintá con la cantidad justa.</h1>
          <p>Nilo calcula cuántos litros necesitás según tus m². Elegí color, presentación y comprá sin desperdicio.</p>
          <div className="row gap-2">
            <Button variant="cta" onClick={() => go("catalog")}>Ver productos</Button>
            <Button variant="secondary" onClick={startAdvisor} icon="spark">Probar asesor</Button>
          </div>
          <div className="paint-hero__picker">
            <span className="paint-hero__picker-label">¿Qué color pintamos?</span>
            <div className="paint-hero__picker-row" role="group" aria-label="Elegir color para la animación de la pared">
              {HERO_COLORS.map((c) => (
                <button
                  key={c.hex}
                  type="button"
                  className={`paint-hero__pick${c.hex === heroColor.hex ? " is-active" : ""}`}
                  style={{ background: c.hex }}
                  aria-label={c.name}
                  aria-pressed={c.hex === heroColor.hex}
                  onClick={() => pickHeroColor(c)}
                >
                  <Icon name="check" size={13} stroke={3} />
                </button>
              ))}
            </div>
          </div>
        </div>
        <div className="paint-hero__visual" aria-hidden="true" style={{ "--ph-color": heroColor.hex }}>
          <div className="paint-hero__wall">
            <span key={`paint-${heroKey}`} className="paint-hero__paint" />
            <span key={`roller-${heroKey}`} className="paint-hero__roller">
              <svg viewBox="0 0 64 40" fill="none">
                <rect className="paint-hero__roller-drum" x="6" y="6" width="40" height="16" rx="8" strokeWidth="2" />
                <rect className="paint-hero__roller-cap" x="40" y="11" width="6" height="6" rx="1.5" />
                <path className="paint-hero__roller-handle" d="M46 14 L60 8 L60 2" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </span>
            <span className="paint-hero__drop"><Icon name="drop" size={14} /></span>
          </div>
          <div className="paint-hero__can"><CanVisual hex={heroColor.hex} label="Nogopaint" sub={heroColor.name} /></div>
          <div className="paint-hero__chips">
            <span className="paint-hero__chip">Interior</span>
            <span className="paint-hero__chip">20 L</span>
          </div>
          <div className="paint-hero__advisor">
            <span className="paint-hero__advisor-calc">45 m² · 2 manos → <b>10 L</b></span>
            <span className="paint-hero__advisor-tag"><Icon name="spark" size={11} stroke={2.5} />Calculado por Nilo</span>
          </div>
        </div>
      </div>

      {/* Categorías */}
      <div className="ng-pad">
        <h2 className="sec-title mb-3">Categorías</h2>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "var(--space-3)" }}>
          {cats.map((c) => (
            <button key={c.id} className="card" onClick={() => go("catalog")} style={{ display: "flex", alignItems: "center", gap: 12, padding: 14, textAlign: "left", cursor: "pointer" }}>
              <span style={{ width: 44, height: 44, borderRadius: 12, background: c.hex, display: "grid", placeItems: "center", color: "var(--text-strong)", flex: "none" }}><Icon name={c.icon} size={22} /></span>
              <span className="fw-6 strong">{c.label}</span>
            </button>
          ))}
        </div>
      </div>

      {/* Destacados */}
      <div className="ng-pad" style={{ paddingTop: 0 }}>
        <div className="row between mb-3">
          <h2 className="sec-title">Más vendidos</h2>
          <button className="link t-sm" onClick={() => go("catalog")} style={{ background: "none", border: "none" }}>Ver todo</button>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "var(--space-3)" }}>
          {featured.map((p) => <ProductCard key={p.id} product={p} onOpen={openProduct} />)}
        </div>
      </div>

      {/* Banner bot */}
      <div className="ng-pad" style={{ paddingTop: 0 }}>
        <div className="card" style={{ padding: 16, background: "var(--accent-soft)", borderColor: "var(--color-primary-200)", display: "flex", gap: 12, alignItems: "center" }}>
          <span className="bot__avatar" style={{ flex: "none" }}><Icon name="drop" size={20} /></span>
          <div style={{ flex: 1 }}>
            <div className="fw-7 strong">¿Cuánta pintura necesito?</div>
            <div className="t-xs muted">Nuestro asesor calcula los litros exactos al agregar un producto.</div>
          </div>
          <Button size="sm" onClick={startAdvisor}>Probar</Button>
        </div>
      </div>

      {/* Sucursales */}
      <div className="ng-pad" style={{ paddingTop: 0, paddingBottom: 24 }}>
        <h2 className="sec-title mb-3">Sucursales</h2>
        <div className="card">
          {NOGO.branches.map((b, i) => (
            <div key={b.city} className="row between" style={{ padding: 14, borderBottom: i < NOGO.branches.length - 1 ? "1px solid var(--border-subtle)" : "none" }}>
              <div className="row gap-3">
                <Icon name="pin" size={18} />
                <div>
                  <div className="fw-6 strong t-sm">{b.city}</div>
                  <div className="t-xs muted">{b.addr}</div>
                </div>
              </div>
              {b.free && <Badge tone="success" icon="truck">Envío gratis</Badge>}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ============================ CATÁLOGO ============================ */
function CatalogScreen({ openProduct, openFilters, filters }) {
  const NOGO = window.NOGO;
  let list = NOGO.products;
  if (filters.use) list = list.filter((p) => p.use === filters.use);
  if (filters.colorFam) list = list.filter((p) => p.colors.includes(filters.colorFam));
  const activeCount = (filters.use ? 1 : 0) + (filters.colorFam ? 1 : 0);

  return (
    <div className="ng-screen">
      <div className="filter-row">
        <button className="tag" onClick={openFilters} style={{ borderColor: activeCount ? "var(--accent)" : undefined, color: activeCount ? "var(--accent)" : undefined }}>
          <Icon name="filter" size={16} />Filtros{activeCount ? ` · ${activeCount}` : ""}
        </button>
        {[["use", "interior", "Interior"], ["use", "exterior", "Exterior"]].map(([k, v, label]) => (
          <button key={v} className={`tag ${filters[k] === v ? "tag--active" : ""}`} onClick={() => openFilters(k, v)}>{label}</button>
        ))}
      </div>
      <div className="ng-pad" style={{ paddingTop: 4 }}>
        <div className="t-sm muted mb-3">{list.length} productos</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "var(--space-3)" }}>
          {list.map((p) => <ProductCard key={p.id} product={p} onOpen={openProduct} />)}
        </div>
        {list.length === 0 && <div className="muted" style={{ textAlign: "center", padding: 40 }}>No hay productos con esos filtros.</div>}
      </div>
    </div>
  );
}

/* ============================ FICHA DE PRODUCTO ============================ */
function ProductScreen({ product, go, onAdd }) {
  const NOGO = window.NOGO;
  const families = product.colors;
  const [fam, setFam] = useState(families[0]);
  const famColors = NOGO.palette[fam];
  const [color, setColor] = useState(famColors[2] || famColors[0]);
  const [presId, setPresId] = useState(product.pres[Math.min(1, product.pres.length - 1)]);
  const pres = NOGO.presentations.filter((p) => product.pres.includes(p.id));
  const price = NOGO.priceFor(product, presId);
  const stock = NOGO.stockFor(product, presId);
  const totalColors = families.reduce((n, f) => n + NOGO.palette[f].length, 0);

  const tech = [
    { icon: "layers", label: "Rendimiento", value: `${product.rendimiento} m²/L por mano` },
    { icon: "brush", label: "Manos sugeridas", value: `${product.manos}` },
    { icon: "drop", label: "Dilución", value: product.dilucion },
    { icon: "clock", label: "Secado", value: product.secado },
    { icon: "brush", label: "Aplicación", value: product.aplicacion.join(" · ") },
  ];

  return (
    <div className="ng-screen" style={{ paddingBottom: 88 }}>
      {/* Hero con la lata del color elegido */}
      <div style={{ position: "relative", aspectRatio: "1/0.78", background: "var(--bg-surface-alt)" }}>
        <ProductMedia product={product} color={color} />
        <button className="btn--icon" onClick={() => go(-1)} aria-label="Volver"
          style={{ position: "absolute", top: 12, left: 12, width: 44, height: 44, borderRadius: 999, background: "var(--bg-surface)", boxShadow: "var(--shadow-sm)", display: "grid", placeItems: "center" }}>
          <Icon name="arrowL" />
        </button>
      </div>

      <div className="ng-pad col gap-4">
        <div>
          <div className="row between" style={{ alignItems: "flex-start" }}>
            <span className="badge badge--neutral">{product.use === "exterior" ? "Exterior" : "Interior"}</span>
            {product.featured && <Badge tone="primary" icon="star">Más vendido</Badge>}
          </div>
          <h1 className="t-2xl mt-2">{product.name}</h1>
          <p className="t-sm muted mt-1">{product.tagline}</p>
        </div>

        <div className="row between" style={{ alignItems: "flex-end" }}>
          <div>
            <div className="t-3xl disp fw-7 strong">{NOGO.fmt(price)}</div>
            <StockLabel qty={stock} />
          </div>
          <Badge tone="success" icon="truck">Envío gratis en Chivilcoy</Badge>
        </div>

        <div className="divider" />

        {/* Presentación */}
        <div className="col gap-3">
          <div className="row between">
            <span className="fw-6 strong">Presentación</span>
            <span className="t-sm muted">Precio según tamaño</span>
          </div>
          <PresentationSelector options={pres} value={presId} onChange={setPresId} />
        </div>

        {/* Color */}
        <div className="col gap-3">
          <div className="row between">
            <span className="fw-6 strong">Color · <span style={{ color: "var(--text-default)", fontWeight: 400 }}>{color.name}</span></span>
            <span className="t-sm muted">{totalColors} colores</span>
          </div>
          <div className="filter-row" style={{ padding: 0, gap: 8 }}>
            {families.map((f) => (
              <button key={f} className={`tag ${fam === f ? "tag--active" : ""}`} style={{ textTransform: "capitalize" }}
                onClick={() => { setFam(f); }}>{f}</button>
            ))}
          </div>
          <SwatchGrid colors={famColors} activeHex={color.hex} onSelect={setColor} />
        </div>

        <div className="divider" />

        {/* Datos técnicos */}
        <div className="col gap-3">
          <span className="fw-6 strong">Datos técnicos</span>
          <div className="card">
            {tech.map((t, i) => (
              <div key={t.label} className="row gap-3" style={{ padding: "12px 14px", borderBottom: i < tech.length - 1 ? "1px solid var(--border-subtle)" : "none" }}>
                <span style={{ color: "var(--text-muted)", flex: "none" }}><Icon name={t.icon} size={18} /></span>
                <span className="t-sm muted" style={{ width: 110, flex: "none" }}>{t.label}</span>
                <span className="t-sm strong fw-6" style={{ textAlign: "right", flex: 1 }}>{t.value}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* CTA fijo: dispara el bot */}
      <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, background: "var(--bg-surface)", borderTop: "1px solid var(--border-subtle)", padding: "var(--space-3) var(--space-4)", display: "flex", gap: 12, alignItems: "center", zIndex: 50 }}>
        <div style={{ flex: "none" }}>
          <div className="t-xs muted">Total</div>
          <div className="disp fw-7 strong t-lg">{NOGO.fmt(price)}</div>
        </div>
        <Button block variant="cta" disabled={stock === 0} icon="cart" onClick={() => onAdd({ product, presId, color })}>
          {stock === 0 ? "Sin stock" : "Agregar y calcular"}
        </Button>
      </div>
    </div>
  );
}

Object.assign(window, { HomeScreen, CatalogScreen, ProductScreen });
