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

/* ============================ CARRITO ============================ */
function DtCart({ 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="dt-wrap" style={{ padding: "100px 0", display: "grid", placeItems: "center", textAlign: "center" }}>
        <div className="col gap-4" style={{ alignItems: "center" }}>
          <span style={{ width: 80, height: 80, borderRadius: 999, background: "var(--bg-surface-alt)", display: "grid", placeItems: "center", color: "var(--text-muted)" }}><Icon name="cart" size={34} /></span>
          <h2 className="t-2xl">Tu carrito está vacío</h2>
          <p className="t-lg muted" style={{ maxWidth: 360 }}>Sumá productos y te ayudamos a calcular la cantidad justa para tu proyecto.</p>
          <Button size="lg" variant="cta" onClick={() => go("catalog")}>Ver productos</Button>
        </div>
      </div>
    );
  }
  return (
    <div className="dt-wrap">
      <h1 className="dt-h1" style={{ fontSize: "var(--text-4xl)", padding: "40px 0 8px" }}>Tu carrito</h1>
      <div className="dt-twocol" style={{ paddingTop: 16 }}>
        <div className="col gap-3">
          {cart.map((it, idx) => (
            <div key={idx} className="dt-cart-row">
              <span className="dt-cart-row__sw" style={{ background: it.color ? it.color.hex : "var(--bg-surface-alt)" }}>{!it.color && <Icon name="brush" size={28} />}</span>
              <div style={{ flex: 1 }}>
                <div className="row between">
                  <div>
                    <div className="fw-7 strong t-lg">{it.name}</div>
                    <div className="t-sm muted mt-1">{it.presLabel}{it.color ? ` · ${it.color.name}` : ""}</div>
                  </div>
                  <button className="dt-iconbtn" style={{ width: 36, height: 36 }} onClick={() => removeItem(idx)} aria-label="Eliminar"><Icon name="x" size={18} /></button>
                </div>
                <div className="row between" style={{ marginTop: 16 }}>
                  <QtyStepper value={it.qty} onChange={(q) => setQty(idx, q)} />
                  <span className="disp fw-7 strong t-xl">{NOGO.fmt(it.price * it.qty)}</span>
                </div>
              </div>
            </div>
          ))}
          {hasPaint && (
            <div className="card" style={{ padding: 16, background: "var(--accent-soft)", borderColor: "var(--color-primary-200)", display: "flex", gap: 10, alignItems: "center" }}>
              <Icon name="info" size={20} /><span className="t-sm strong">Las cantidades fueron calculadas por nuestro asesor según los m² de tu proyecto.</span>
            </div>
          )}
        </div>

        <div className="dt-summary">
          <h3 className="t-lg">Resumen</h3>
          <div className="row between"><span className="muted">Subtotal ({cart.reduce((n, i) => n + i.qty, 0)} ítems)</span><span className="strong fw-6">{NOGO.fmt(subtotal)}</span></div>
          <div className="row between"><span className="muted">Envío</span><span className="stock-ok fw-6">A calcular</span></div>
          <div className="divider" />
          <div className="row between"><span className="fw-7 strong t-lg">Total</span><span className="disp fw-7 strong t-2xl">{NOGO.fmt(subtotal)}</span></div>
          <Button size="lg" block iconRight="chevR" onClick={() => go("checkout")}>Continuar compra</Button>
          <div className="row gap-2 muted" style={{ justifyContent: "center" }}><Icon name="shield" size={16} />Compra protegida</div>
        </div>
      </div>
    </div>
  );
}

/* ============================ CHECKOUT ============================ */
function DtCheckout({ 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 = ({ value, cur, set, title, desc, right, icon }) => (
    <button onClick={() => set(value)} className="card" style={{ display: "flex", gap: 14, alignItems: "center", padding: 18, 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={22} /></span>}
      <span style={{ flex: 1 }}><span className="fw-6 strong" style={{ display: "block" }}>{title}</span>{desc && <span className="t-sm 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="dt-wrap">
      <div className="dt-breadcrumb"><button onClick={() => go("cart")}>Carrito</button><Icon name="chevR" size={14} /><span className="strong">Checkout</span></div>
      <h1 className="dt-h1" style={{ fontSize: "var(--text-4xl)", padding: "8px 0" }}>Finalizar compra</h1>
      <div className="dt-twocol" style={{ paddingTop: 16 }}>
        <div className="col gap-6">
          <section className="col gap-3">
            <h3 className="t-lg">Datos de contacto</h3>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
              <Field label="Nombre y apellido"><input className="input" placeholder="Tu nombre" /></Field>
              <Field label="Email"><input className="input" inputMode="email" placeholder="vos@correo.com" /></Field>
              <Field label="Teléfono"><input className="input" inputMode="tel" placeholder="11 5555 5555" /></Field>
              <Field label="DNI"><input className="input" inputMode="numeric" placeholder="00.000.000" /></Field>
            </div>
          </section>

          <section className="col gap-3">
            <h3 className="t-lg">Entrega</h3>
            <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="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 de envío"><select className="select" value={branch} onChange={(e) => setBranch(e.target.value)}>{NOGO.branches.map((b) => <option key={b.city}>{b.city}</option>)}</select></Field>
            ) : (
              <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>
            )}
            {delivery === "envio" && branch === "Chivilcoy" && <div className="badge badge--success" style={{ alignSelf: "flex-start" }}><Icon name="truck" size={12} />¡Envío gratis en Chivilcoy!</div>}
          </section>

          <section className="col gap-3">
            <h3 className="t-lg">Pago</h3>
            <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 el pedido" />
          </section>
        </div>

        <div className="dt-summary">
          <h3 className="t-lg">Tu pedido</h3>
          <div className="col gap-2" style={{ maxHeight: 180, overflowY: "auto" }}>
            {cart.map((it, i) => (
              <div key={i} className="row gap-2" style={{ alignItems: "center" }}>
                <span style={{ width: 36, height: 36, borderRadius: 8, background: it.color ? it.color.hex : "var(--bg-surface-alt)", flex: "none", border: "1px solid rgba(18,21,27,.1)" }} />
                <span className="t-sm" style={{ flex: 1, lineHeight: 1.25 }}>{it.qty}× {it.name}<br /><span className="muted t-xs">{it.presLabel}</span></span>
                <span className="t-sm fw-6 strong">{NOGO.fmt(it.price * it.qty)}</span>
              </div>
            ))}
          </div>
          <div className="divider" />
          <div className="row between t-sm"><span className="muted">Subtotal</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>
          <div className="divider" />
          <div className="row between"><span className="fw-7 strong t-lg">Total</span><span className="disp fw-7 strong t-2xl">{NOGO.fmt(total)}</span></div>
          <Button size="lg" block variant="cta" onClick={onPlace}>Pagar {NOGO.fmt(total)}</Button>
        </div>
      </div>
    </div>
  );
}

/* ============================ SERVICIOS ============================ */
function DtServices() {
  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 calcular cantidades.", price: "Gratis" },
    { id: "obra", title: "Mano de obra", icon: "brush", desc: "Pintores matriculados de confianza. Presupuesto detallado sin compromiso.", price: "A presupuestar" },
  ];
  return (
    <div className="dt-screen">
      <div className="dt-services-hero">
        <div className="dt-wrap" style={{ padding: "56px 0" }}>
          <h1 className="dt-h1" style={{ fontSize: "var(--text-4xl)" }}>Servicios</h1>
          <p className="t-lg muted mt-2" style={{ maxWidth: 560 }}>Te acompañamos antes, durante y después de pintar. Elegí el servicio y dejanos tus datos.</p>
        </div>
      </div>
      <div className="dt-wrap">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24, padding: "40px 0" }}>
          {services.map((s) => (
            <button key={s.id} className="card" onClick={() => setTab(s.id)} style={{ padding: 28, textAlign: "left", cursor: "pointer", display: "flex", gap: 18, alignItems: "flex-start", borderColor: tab === s.id ? "var(--accent)" : "var(--border-subtle)", borderWidth: tab === s.id ? 2 : 1, background: tab === s.id ? "var(--accent-soft)" : "var(--bg-surface)" }}>
              <span style={{ width: 56, height: 56, borderRadius: 14, background: "var(--bg-surface)", color: "var(--accent)", display: "grid", placeItems: "center", flex: "none", boxShadow: "var(--shadow-xs)" }}><Icon name={s.icon} size={26} /></span>
              <span style={{ flex: 1 }}><span className="row between"><span className="fw-7 strong t-lg">{s.title}</span><Badge tone={s.price === "Gratis" ? "success" : "neutral"}>{s.price}</Badge></span><span className="t-sm muted" style={{ display: "block", marginTop: 6 }}>{s.desc}</span></span>
            </button>
          ))}
        </div>

        <div style={{ maxWidth: 640, margin: "0 auto", paddingBottom: 40 }}>
          <div className="dt-form-card">
            <h3 className="t-2xl">Solicitar {tab === "asesoria" ? "asesoramiento" : "presupuesto"}</h3>
            {sent ? (
              <div className="col gap-3" style={{ alignItems: "center", padding: 24, textAlign: "center" }}>
                <span style={{ width: 64, height: 64, borderRadius: 999, background: "var(--color-success-50)", color: "var(--color-success-600)", display: "grid", placeItems: "center" }}><Icon name="check" size={32} stroke={3} /></span>
                <div className="fw-7 strong t-lg">¡Solicitud enviada!</div>
                <div className="muted">Te contactamos dentro de las 24 h hábiles.</div>
                <Button variant="secondary" onClick={() => setSent(false)}>Enviar otra</Button>
              </div>
            ) : (
              <>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                  <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>
                </div>
                <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 size="lg" block onClick={() => setSent(true)}>Enviar solicitud</Button>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================ MAYORISTA ============================ */
function DtWholesale() {
  const [sent, setSent] = useState(false);
  return (
    <div className="dt-screen">
      <div style={{ background: "linear-gradient(135deg, var(--color-neutral-800), var(--color-neutral-900))", color: "#fff" }}>
        <div className="dt-wrap" style={{ padding: "64px 0", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 40, alignItems: "center" }}>
          <div>
            <span className="badge" style={{ background: "rgba(255,255,255,.16)", color: "#fff" }}><Icon name="store" size={13} />B2B</span>
            <h1 className="dt-h1" style={{ color: "#fff", fontSize: "var(--text-4xl)", marginTop: 14 }}>Cuenta mayorista</h1>
            <p className="t-lg" style={{ opacity: .9, marginTop: 10, maxWidth: 440 }}>Precios especiales para pintores, corralones, estudios y empresas constructoras. Atención comercial dedicada.</p>
          </div>
          <div className="col gap-3">
            {[["card", "Lista de precios mayorista"], ["truck", "Logística para grandes volúmenes"], ["user", "Asesor comercial asignado"]].map(([ic, txt]) => (
              <div key={txt} className="row gap-3" style={{ background: "rgba(255,255,255,0.06)", padding: 16, borderRadius: "var(--radius-md)" }}><span style={{ flex: "none" }}><Icon name={ic} size={22} /></span><span className="fw-6">{txt}</span></div>
            ))}
          </div>
        </div>
      </div>
      <div className="dt-wrap">
        <div style={{ maxWidth: 640, margin: "0 auto", padding: "40px 0" }}>
          <div className="dt-form-card">
            {sent ? (
              <div className="col gap-3" style={{ alignItems: "center", padding: 24, textAlign: "center" }}>
                <span style={{ width: 64, height: 64, borderRadius: 999, background: "var(--color-success-50)", color: "var(--color-success-600)", display: "grid", placeItems: "center" }}><Icon name="check" size={32} stroke={3} /></span>
                <div className="fw-7 strong t-lg">¡Recibimos tu solicitud!</div>
                <div className="muted">Un asesor comercial te contactará a la brevedad.</div>
              </div>
            ) : (
              <>
                <h3 className="t-2xl">Solicitá tu cuenta</h3>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                  <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>
                </div>
                <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 size="lg" 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>
    </div>
  );
}

Object.assign(window, { DtCart, DtCheckout, DtServices, DtWholesale });
