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

/* ============================ 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 DtHome({ go, openProduct, startAdvisor }) {
  const NOGO = window.NOGO;
  const featured = NOGO.products.filter((p) => p.featured).concat(NOGO.products.filter((p) => !p.featured)).slice(0, 4);
  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", desc: "Látex y esmaltes lavables", icon: "home", hex: "#a8c8e0" },
    { id: "exterior", label: "Exterior", desc: "Resistentes a la intemperie", icon: "shield", hex: "#9aa881" },
    { id: "esmaltes", label: "Esmaltes", desc: "Madera y metal", icon: "brush", hex: "#e8a48b" },
    { id: "impermeab", label: "Impermeabilizantes", desc: "Techos y terrazas", icon: "drop", hex: "#cdbfa3" },
  ];
  return (
    <div className="dt-screen">
      <div className="dt-wrap">
        {/* Hero */}
        <div className="paint-hero">
          <div className="paint-hero__copy">
            <Badge tone="primary" icon="spark">Asesoramiento experto, sin cargo</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-3">
              <Button size="lg" variant="cta" onClick={() => go("catalog")}>Ver productos</Button>
              <Button size="lg" 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={18} /></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">Exterior</span>
              <span className="paint-hero__chip">20 L</span>
              <span className="paint-hero__chip">+30 colores</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={12} stroke={2.5} />Calculado por Nilo</span>
            </div>
          </div>
        </div>

        {/* Categorías */}
        <section className="dt-section">
          <div className="dt-section-head"><h2>Categorías</h2></div>
          <div className="dt-cats">
            {cats.map((c) => (
              <button key={c.id} className="dt-cat" onClick={() => go("catalog")}>
                <span className="dt-cat__icon" style={{ background: c.hex }}><Icon name={c.icon} size={26} /></span>
                <span><span className="fw-7 strong t-lg" style={{ display: "block" }}>{c.label}</span><span className="t-sm muted">{c.desc}</span></span>
              </button>
            ))}
          </div>
        </section>

        {/* Destacados */}
        <section className="dt-section" style={{ paddingTop: 0 }}>
          <div className="dt-section-head">
            <h2>Más vendidos</h2>
            <button className="link" onClick={() => go("catalog")} style={{ background: "none", border: "none", cursor: "pointer" }}>Ver catálogo completo →</button>
          </div>
          <div className="dt-pgrid">
            {featured.map((p) => <ProductCard key={p.id} product={p} onOpen={openProduct} />)}
          </div>
        </section>

        {/* Banner servicios */}
        <section className="dt-section" style={{ paddingTop: 0 }}>
          <div className="card" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 0, overflow: "hidden", borderColor: "var(--color-primary-200)" }}>
            <div style={{ padding: 40, background: "var(--accent-soft)", display: "flex", flexDirection: "column", gap: 12, justifyContent: "center" }}>
              <span className="bot__avatar" style={{ width: 48, height: 48 }}><Icon name="drop" size={24} /></span>
              <h3 className="t-2xl">¿Cuánta pintura necesito?</h3>
              <p className="t-sm muted" style={{ maxWidth: 380 }}>Al agregar un producto, nuestro asesor Nilo calcula los litros exactos y te recomienda los baldes y complementos.</p>
              <Button onClick={startAdvisor} style={{ alignSelf: "flex-start" }} icon="spark">Probar el asesor</Button>
            </div>
            <div style={{ padding: 40, display: "flex", flexDirection: "column", gap: 16, justifyContent: "center" }}>
              {[["spark", "Asesoramiento a domicilio o virtual, sin cargo"], ["brush", "Mano de obra con pintores matriculados"], ["truck", "Envío gratis en Chivilcoy"]].map(([ic, txt]) => (
                <div key={txt} className="row gap-3"><span style={{ color: "var(--accent)", flex: "none" }}><Icon name={ic} size={22} /></span><span className="strong fw-6">{txt}</span></div>
              ))}
            </div>
          </div>
        </section>
      </div>
    </div>
  );
}

/* ============================ CATÁLOGO ============================ */
function DtCatalog({ openProduct, filters, setFilters }) {
  const NOGO = window.NOGO;
  const fams = Object.keys(NOGO.palette);
  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 Check = ({ on, onClick, children }) => (
    <label className="choice" onClick={onClick} style={{ minHeight: 40 }}>
      <input type="checkbox" checked={on} readOnly />
      <span className="choice__box choice__box--check"><Icon name="check" size={14} stroke={3} /></span>
      <span className="t-sm strong">{children}</span>
    </label>
  );

  return (
    <div className="dt-wrap">
      <div className="dt-breadcrumb"><button>Inicio</button><Icon name="chevR" size={14} /><span className="strong">Catálogo</span></div>
      <div className="dt-catalog">
        <aside className="dt-sidebar">
          <div className="dt-filter-group">
            <h4>Uso</h4>
            <div className="dt-check-list">
              <Check on={!filters.use} onClick={() => setFilters({ ...filters, use: null })}>Todos</Check>
              <Check on={filters.use === "interior"} onClick={() => setFilters({ ...filters, use: "interior" })}>Interior</Check>
              <Check on={filters.use === "exterior"} onClick={() => setFilters({ ...filters, use: "exterior" })}>Exterior</Check>
            </div>
          </div>
          <div className="divider" />
          <div className="dt-filter-group">
            <h4>Familia de color</h4>
            <div className="dt-check-list">
              <Check on={!filters.colorFam} onClick={() => setFilters({ ...filters, colorFam: null })}>Todas</Check>
              {fams.map((f) => (
                <label key={f} className="choice" onClick={() => setFilters({ ...filters, colorFam: f })} style={{ minHeight: 40, textTransform: "capitalize" }}>
                  <input type="checkbox" checked={filters.colorFam === f} readOnly />
                  <span className="choice__box choice__box--check"><Icon name="check" size={14} stroke={3} /></span>
                  <span style={{ display: "flex", gap: 3, marginRight: 2 }}>{NOGO.palette[f].slice(0, 4).map((c) => <span key={c.hex} style={{ width: 14, height: 14, borderRadius: 4, background: c.hex }} />)}</span>
                  <span className="t-sm strong">{f}</span>
                </label>
              ))}
            </div>
          </div>
          <div className="divider" />
          <div className="card" style={{ padding: 16, background: "var(--accent-soft)", borderColor: "var(--color-primary-200)" }}>
            <div className="fw-7 strong mb-2">¿Dudas con el color?</div>
            <div className="t-sm muted mb-3">Pedí asesoramiento sin cargo.</div>
            <Button size="sm" variant="secondary" block>Contactar</Button>
          </div>
        </aside>

        <div>
          <div className="dt-section-head" style={{ marginBottom: 20 }}>
            <h2 className="t-2xl">{filters.use ? (filters.use === "interior" ? "Interior" : "Exterior") : "Todos los productos"}</h2>
            <span className="muted">{list.length} productos</span>
          </div>
          <div className="dt-pgrid dt-pgrid--3">
            {list.map((p) => <ProductCard key={p.id} product={p} onOpen={openProduct} />)}
          </div>
          {list.length === 0 && <div className="muted" style={{ textAlign: "center", padding: 60 }}>No hay productos con esos filtros.</div>}
        </div>
      </div>
    </div>
  );
}

/* ============================ FICHA ============================ */
function DtProduct({ 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(" · ") },
    { icon: "shield", label: "Uso", value: product.use === "exterior" ? "Exterior" : "Interior" },
  ];

  return (
    <div className="dt-wrap">
      <div className="dt-breadcrumb">
        <button onClick={() => go("home")}>Inicio</button><Icon name="chevR" size={14} />
        <button onClick={() => go("catalog")}>Catálogo</button><Icon name="chevR" size={14} />
        <span className="strong">{product.name}</span>
      </div>

      <div className="dt-pdp">
        <div className="dt-pdp__media"><ProductMedia product={product} color={color} /></div>

        <div className="dt-pdp__col">
          <div>
            <div className="row gap-2 mb-2">
              <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-4xl">{product.name}</h1>
            <p className="t-lg muted mt-2">{product.tagline}</p>
          </div>

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

          <div className="divider" />

          <div className="col gap-3">
            <span className="fw-6 strong t-lg">Presentación</span>
            <PresentationSelector options={pres} value={presId} onChange={setPresId} />
          </div>

          <div className="col gap-3">
            <div className="row between">
              <span className="fw-6 strong t-lg">Color · <span style={{ color: "var(--text-default)", fontWeight: 400 }}>{color.name}</span></span>
              <span className="t-sm muted">{totalColors} colores disponibles</span>
            </div>
            <div className="row gap-2" style={{ flexWrap: "wrap" }}>
              {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="row gap-3" style={{ marginTop: 8 }}>
            <Button size="lg" block variant="cta" icon="cart" disabled={stock === 0} onClick={() => onAdd({ product, presId, color })}>
              {stock === 0 ? "Sin stock" : "Agregar y calcular cantidad"}
            </Button>
          </div>
          <div className="row gap-2" style={{ color: "var(--text-muted)" }}><Icon name="info" size={16} /><span className="t-sm">Al agregar, el asesor calcula cuántos litros necesitás.</span></div>

          <div className="divider" />

          <div className="col gap-3">
            <span className="fw-6 strong t-lg">Datos técnicos</span>
            <div className="dt-tech-grid">
              {tech.map((t) => (
                <div key={t.label} className="dt-tech-cell">
                  <div className="row gap-2 muted t-sm mb-2"><Icon name={t.icon} size={16} />{t.label}</div>
                  <div className="strong fw-6">{t.value}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DtHome, DtCatalog, DtProduct });
