/* global React, Icon, Button, Badge, Field, QtyStepper, useState */

/* ============================ CARRITO ============================ */
function CartScreen({ cart, setQty, removeItem, go }) {
  const NOGO = window.NOGO;
  const subtotal = cart.reduce((s, i) => s + i.price * i.qty, 0);
  const hasPaint = cart.some((i) => i.color !== null);
  if (cart.length === 0) {
    return (
      <div className="ng-screen" style={{ display: "grid", placeItems: "center", textAlign: "center" }}>
        <div className="col gap-3" style={{ alignItems: "center", padding: 40 }}>
          <span style={{ width: 64, height: 64, borderRadius: 999, background: "var(--bg-surface-alt)", display: "grid", placeItems: "center", color: "var(--text-muted)" }}><Icon name="cart" size={28} /></span>
          <div className="fw-7 strong t-lg">Tu carrito está vacío</div>
          <div className="t-sm muted" style={{ maxWidth: 220 }}>Sumá productos y te ayudamos a calcular la cantidad justa.</div>
          <Button variant="cta" onClick={() => go("catalog")}>Ver productos</Button>
        </div>
      </div>
    );
  }
  return (
    <div className="ng-screen" style={{ paddingBottom: 96 }}>
      <div className="ng-pad col gap-3">
        {cart.map((it, idx) => (
          <div key={idx} className="card" style={{ display: "flex", gap: 12, padding: 12 }}>
            <span style={{ width: 56, height: 56, borderRadius: 10, background: it.color ? it.color.hex : "var(--bg-surface-alt)", flex: "none", border: "1px solid rgba(18,21,27,.12)", display: "grid", placeItems: "center", color: "var(--text-muted)" }}>
              {!it.color && <Icon name="brush" size={22} />}
            </span>
            <div style={{ flex: 1 }}>
              <div className="row between">
                <span className="fw-6 strong t-sm" style={{ lineHeight: 1.25 }}>{it.name}</span>
                <button className="btn--icon" onClick={() => removeItem(idx)} aria-label="Eliminar" style={{ width: 28, height: 28, display: "grid", placeItems: "center", color: "var(--text-muted)" }}><Icon name="x" size={16} /></button>
              </div>
              <div className="t-xs muted">{it.presLabel}{it.color ? ` · ${it.color.name}` : ""}</div>
              <div className="row between mt-2">
                <QtyStepper value={it.qty} onChange={(q) => setQty(idx, q)} />
                <span className="disp fw-7 strong">{NOGO.fmt(it.price * it.qty)}</span>
              </div>
            </div>
          </div>
        ))}
        {hasPaint && (
          <div className="card" style={{ padding: 12, background: "var(--accent-soft)", borderColor: "var(--color-primary-200)", display: "flex", gap: 10, alignItems: "center" }}>
            <Icon name="info" size={18} /><span className="t-xs strong">Cantidades calculadas por nuestro asesor según tus m².</span>
          </div>
        )}
      </div>
      <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, background: "var(--bg-surface)", borderTop: "1px solid var(--border-subtle)", padding: "var(--space-4)" }}>
        <div className="row between mb-3">
          <span className="muted">Subtotal</span>
          <span className="disp fw-7 strong t-lg">{NOGO.fmt(subtotal)}</span>
        </div>
        <Button block size="lg" iconRight="chevR" onClick={() => go("checkout")}>Continuar compra</Button>
      </div>
    </div>
  );
}

/* ============================ CHECKOUT ============================ */
function CheckoutScreen({ cart, go, onPlace }) {
  const NOGO = window.NOGO;
  const subtotal = cart.reduce((s, i) => s + i.price * i.qty, 0);
  const [delivery, setDelivery] = useState("envio");
  const [branch, setBranch] = useState("Chivilcoy");
  const [pay, setPay] = useState("mp");
  const freeShip = delivery === "retiro" || branch === "Chivilcoy";
  const shipCost = delivery === "envio" && !freeShip ? 4500 : 0;
  const total = subtotal + shipCost;

  const Radio = ({ name, value, cur, set, title, desc, right, icon }) => (
    <button onClick={() => set(value)} className="card" style={{ display: "flex", gap: 12, alignItems: "center", padding: 14, textAlign: "left", cursor: "pointer", borderColor: cur === value ? "var(--accent)" : "var(--border-subtle)", background: cur === value ? "var(--accent-soft)" : "var(--bg-surface)", width: "100%" }}>
      {icon && <span style={{ color: "var(--text-default)", flex: "none" }}><Icon name={icon} size={20} /></span>}
      <span style={{ flex: 1 }}>
        <span className="fw-6 strong t-sm" style={{ display: "block" }}>{title}</span>
        {desc && <span className="t-xs muted">{desc}</span>}
      </span>
      {right}
      <span style={{ width: 22, height: 22, borderRadius: 999, border: "1.5px solid", borderColor: cur === value ? "var(--accent)" : "var(--border-strong)", display: "grid", placeItems: "center", flex: "none" }}>
        {cur === value && <span style={{ width: 10, height: 10, borderRadius: 999, background: "var(--accent)" }} />}
      </span>
    </button>
  );

  return (
    <div className="ng-screen" style={{ paddingBottom: 120 }}>
      <div className="ng-pad col gap-5">
        <section className="col gap-3">
          <h2 className="fw-7 strong">Entrega</h2>
          <Radio value="envio" cur={delivery} set={setDelivery} icon="truck" title="Envío a domicilio" desc="24–72 h hábiles"
            right={freeShip ? <Badge tone="success">Gratis</Badge> : <span className="t-sm fw-6">{NOGO.fmt(4500)}</span>} />
          <Radio value="retiro" cur={delivery} set={setDelivery} icon="store" title="Retiro en sucursal" desc="Listo en 2 h · sin cargo" />
          {delivery === "envio" && (
            <Field label="Localidad">
              <select className="select" value={branch} onChange={(e) => setBranch(e.target.value)}>
                {NOGO.branches.map((b) => <option key={b.city}>{b.city}</option>)}
              </select>
            </Field>
          )}
          {delivery === "envio" && branch === "Chivilcoy" && (
            <div className="badge badge--success" style={{ alignSelf: "flex-start" }}><Icon name="truck" size={12} />¡Envío gratis en Chivilcoy!</div>
          )}
          {delivery === "retiro" && (
            <Field label="Sucursal de retiro">
              <select className="select" value={branch} onChange={(e) => setBranch(e.target.value)}>
                {NOGO.branches.map((b) => <option key={b.city}>{b.city} — {b.addr}</option>)}
              </select>
            </Field>
          )}
        </section>

        <section className="col gap-3">
          <h2 className="fw-7 strong">Pago</h2>
          <Radio value="mp" cur={pay} set={setPay} icon="card" title="Mercado Pago" desc="Tarjeta, débito o dinero en cuenta" />
          <Radio value="transfer" cur={pay} set={setPay} icon="card" title="Transferencia bancaria" desc="5% de descuento" />
          <Radio value="local" cur={pay} set={setPay} icon="store" title="Pago en sucursal" desc="Al retirar" />
        </section>

        <section className="col gap-2">
          <h2 className="fw-7 strong mb-2">Resumen</h2>
          <div className="row between t-sm"><span className="muted">Subtotal ({cart.length} ítems)</span><span className="strong fw-6">{NOGO.fmt(subtotal)}</span></div>
          <div className="row between t-sm"><span className="muted">Envío</span><span className="strong fw-6">{shipCost === 0 ? "Gratis" : NOGO.fmt(shipCost)}</span></div>
        </section>
      </div>

      <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, background: "var(--bg-surface)", borderTop: "1px solid var(--border-subtle)", padding: "var(--space-4)" }}>
        <div className="row between mb-3"><span className="fw-6 strong">Total</span><span className="disp fw-7 strong t-2xl">{NOGO.fmt(total)}</span></div>
        <Button block size="lg" variant="cta" onClick={onPlace}>Pagar {NOGO.fmt(total)}</Button>
      </div>
    </div>
  );
}

/* ============================ SERVICIOS ============================ */
function ServicesScreen() {
  const [tab, setTab] = useState("asesoria");
  const [sent, setSent] = useState(false);
  const services = [
    { id: "asesoria", title: "Asesoramiento sin cargo", icon: "spark", desc: "A domicilio o virtual. Un experto te ayuda a elegir productos, colores y cantidades.", price: "Gratis" },
    { id: "obra", title: "Mano de obra", icon: "brush", desc: "Pintores matriculados de confianza. Presupuesto sin compromiso.", price: "A presupuestar" },
  ];
  return (
    <div className="ng-screen">
      <div style={{ padding: "var(--space-5) var(--space-4)", background: "var(--bg-surface)", borderBottom: "1px solid var(--border-subtle)" }}>
        <h1 className="t-2xl">Servicios</h1>
        <p className="t-sm muted mt-1">Te acompañamos antes, durante y después de pintar.</p>
      </div>
      <div className="ng-pad col gap-3">
        {services.map((s) => (
          <button key={s.id} className="card" onClick={() => setTab(s.id)} style={{ padding: 16, textAlign: "left", cursor: "pointer", display: "flex", gap: 14, alignItems: "flex-start", borderColor: tab === s.id ? "var(--accent)" : "var(--border-subtle)" }}>
            <span style={{ width: 44, height: 44, borderRadius: 12, background: "var(--accent-soft)", color: "var(--accent)", display: "grid", placeItems: "center", flex: "none" }}><Icon name={s.icon} /></span>
            <span style={{ flex: 1 }}>
              <span className="row between"><span className="fw-7 strong">{s.title}</span><Badge tone={s.price === "Gratis" ? "success" : "neutral"}>{s.price}</Badge></span>
              <span className="t-sm muted" style={{ display: "block", marginTop: 4 }}>{s.desc}</span>
            </span>
          </button>
        ))}

        <div className="card ng-pad col gap-3" style={{ marginTop: 8 }}>
          <h3 className="t-lg">Solicitar {tab === "asesoria" ? "asesoramiento" : "presupuesto"}</h3>
          {sent ? (
            <div className="col gap-2" style={{ alignItems: "center", padding: 16, textAlign: "center" }}>
              <span style={{ width: 52, height: 52, borderRadius: 999, background: "var(--color-success-50)", color: "var(--color-success-600)", display: "grid", placeItems: "center" }}><Icon name="check" size={26} stroke={3} /></span>
              <div className="fw-7 strong">¡Solicitud enviada!</div>
              <div className="t-sm muted">Te contactamos dentro de las 24 h hábiles.</div>
              <Button variant="secondary" onClick={() => setSent(false)}>Enviar otra</Button>
            </div>
          ) : (
            <>
              <Field label="Nombre y apellido"><input className="input" placeholder="Tu nombre" /></Field>
              <Field label="Teléfono / WhatsApp"><input className="input" inputMode="tel" placeholder="11 5555 5555" /></Field>
              <Field label={tab === "asesoria" ? "Modalidad" : "Tipo de trabajo"}>
                <select className="select">
                  {tab === "asesoria" ? <><option>Virtual (videollamada)</option><option>A domicilio</option></> : <><option>Interior</option><option>Exterior / frente</option><option>Impermeabilización</option></>}
                </select>
              </Field>
              <Field label="Contanos tu proyecto" hint="Superficie aproximada, ambientes, plazos…">
                <textarea className="textarea" placeholder="Ej: living y dos dormitorios, ~60 m²…" />
              </Field>
              <Button block onClick={() => setSent(true)}>Enviar solicitud</Button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

/* ============================ CONTACTO MAYORISTA ============================ */
function WholesaleScreen() {
  const [sent, setSent] = useState(false);
  return (
    <div className="ng-screen">
      <div style={{ padding: "var(--space-5) var(--space-4)", background: "linear-gradient(160deg, var(--color-neutral-800), var(--color-neutral-900))", color: "#fff" }}>
        <span className="badge" style={{ background: "rgba(255,255,255,.16)", color: "#fff" }}><Icon name="store" size={12} />B2B</span>
        <h1 className="t-2xl" style={{ color: "#fff", marginTop: 10 }}>Cuenta mayorista</h1>
        <p className="t-sm" style={{ opacity: .9, marginTop: 6 }}>Precios especiales para pintores, corralones y empresas constructoras.</p>
      </div>
      <div className="ng-pad">
        <div className="card ng-pad col gap-3">
          {sent ? (
            <div className="col gap-2" style={{ alignItems: "center", padding: 16, textAlign: "center" }}>
              <span style={{ width: 52, height: 52, borderRadius: 999, background: "var(--color-success-50)", color: "var(--color-success-600)", display: "grid", placeItems: "center" }}><Icon name="check" size={26} stroke={3} /></span>
              <div className="fw-7 strong">¡Recibimos tu solicitud!</div>
              <div className="t-sm muted">Un asesor comercial te contactará a la brevedad.</div>
            </div>
          ) : (
            <>
              <Field label="Razón social / Nombre"><input className="input" placeholder="Empresa o profesional" /></Field>
              <Field label="CUIT"><input className="input" inputMode="numeric" placeholder="30-00000000-0" /></Field>
              <Field label="Rubro">
                <select className="select"><option>Pintor profesional</option><option>Corralón</option><option>Constructora</option><option>Arquitectura / Estudio</option><option>Otro</option></select>
              </Field>
              <Field label="Email"><input className="input" inputMode="email" placeholder="empresa@correo.com" /></Field>
              <Field label="Volumen estimado mensual" hint="Nos ayuda a armar tu lista de precios">
                <select className="select"><option>Hasta 100 L</option><option>100 – 500 L</option><option>500 – 2000 L</option><option>Más de 2000 L</option></select>
              </Field>
              <Button block onClick={() => setSent(true)}>Solicitar cuenta mayorista</Button>
              <p className="t-xs muted" style={{ textAlign: "center" }}>Respondemos en 24–48 h hábiles.</p>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

/* ============================ FILTROS (sheet) ============================ */
function FilterContent({ filters, setFilters, onClose }) {
  const NOGO = window.NOGO;
  const fams = Object.keys(NOGO.palette);
  return (
    <div className="col gap-5">
      <div className="col gap-3">
        <span className="fw-6 strong">Uso</span>
        <div className="segmented">
          {[["", "Todos"], ["interior", "Interior"], ["exterior", "Exterior"]].map(([v, l]) => (
            <button key={v} className={`pill ${(filters.use || "") === v ? "pill--active" : ""}`} style={{ flex: 1, minWidth: 0 }} onClick={() => setFilters({ ...filters, use: v || null })}><span>{l}</span></button>
          ))}
        </div>
      </div>
      <div className="col gap-3">
        <span className="fw-6 strong">Familia de color</span>
        <div className="row gap-2" style={{ flexWrap: "wrap" }}>
          <button className={`tag ${!filters.colorFam ? "tag--active" : ""}`} onClick={() => setFilters({ ...filters, colorFam: null })}>Todos</button>
          {fams.map((f) => (
            <button key={f} className={`tag ${filters.colorFam === f ? "tag--active" : ""}`} style={{ textTransform: "capitalize" }} onClick={() => setFilters({ ...filters, colorFam: f })}>
              <span style={{ display: "flex", gap: 2 }}>{NOGO.palette[f].slice(0, 3).map((c) => <span key={c.hex} style={{ width: 12, height: 12, borderRadius: 3, background: c.hex }} />)}</span>{f}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CartScreen, CheckoutScreen, ServicesScreen, WholesaleScreen, FilterContent });
