/* ============================================================
   YUZU YATAI — Cart drawer & Checkout
   ============================================================ */

const DELIVERY_FEE = 2490;

function modSummary(line) {
  const parts = [];
  if (line.tamano === "grande") parts.push("Grande");
  line.extras.forEach((id) => {
    const o = YY.MODIFIERS.extras.options.find((x) => x.id === id);
    if (o) parts.push(o.label);
  });
  return parts.join(" · ");
}

/* ---------- a single cart line ---------- */
function CartLine({ line, setQty, remove }) {
  const summary = modSummary(line);
  return (
    <div
      style={{
        display: "flex",
        gap: 14,
        padding: "16px 0",
        borderBottom: "1px solid var(--rice-3)",
      }}
    >
      <FoodImage
        src={line.item.img}
        label={line.item.ph}
        ratio="1 / 1"
        radius="12px 2px 12px 2px"
        style={{ width: 72, flexShrink: 0 }}
      />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div
          style={{ display: "flex", justifyContent: "space-between", gap: 10 }}
        >
          <h4
            style={{
              fontFamily: "var(--body)",
              fontWeight: 600,
              fontSize: 15.5,
              lineHeight: 1.2,
            }}
          >
            {line.item.name}
          </h4>
          <button
            onClick={remove}
            aria-label="Quitar"
            style={{ color: "rgba(30,27,24,.4)", flexShrink: 0 }}
          >
            <IcClose size={18} />
          </button>
        </div>
        {summary && (
          <p
            style={{ fontSize: 13, color: "rgba(30,27,24,.55)", marginTop: 3 }}
          >
            {summary}
          </p>
        )}
        {line.notes && (
          <p
            style={{
              fontSize: 12.5,
              color: "rgba(30,27,24,.45)",
              marginTop: 2,
              fontStyle: "italic",
            }}
          >
            “{line.notes}”
          </p>
        )}
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            marginTop: 10,
          }}
        >
          <Stepper qty={line.qty} setQty={(n) => setQty(n)} />
          <PriceTag value={line.unit * line.qty} size={16} />
        </div>
      </div>
    </div>
  );
}

/* ---------- cart drawer ---------- */
function CartDrawer({
  open,
  onClose,
  cart,
  setQty,
  remove,
  fulfillment,
  setFulfillment,
  onCheckout,
  go,
}) {
  const narrow = useNarrow();
  if (!open) return null;
  const subtotal = cart.reduce((s, l) => s + l.unit * l.qty, 0);
  const fee = fulfillment === "delivery" && cart.length ? DELIVERY_FEE : 0;
  const total = subtotal + fee;

  return (
    <Overlay onClose={onClose} side={narrow ? "bottom" : "right"}>
      <aside
        style={{
          display: "flex",
          flexDirection: "column",
          background: "var(--rice)",
          width: narrow ? "100%" : "min(440px,96vw)",
          height: narrow ? "auto" : "100vh",
          maxHeight: narrow ? "90vh" : "100vh",
          borderRadius: narrow ? "26px 26px 0 0" : 0,
        }}
      >
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            padding: "22px 24px 16px",
            borderBottom: "1px solid var(--rice-3)",
          }}
        >
          <h2
            style={{
              fontSize: 26,
              display: "flex",
              alignItems: "center",
              gap: 10,
            }}
          >
            <IcCart size={24} /> Tu pedido
          </h2>
          <button
            onClick={onClose}
            aria-label="Cerrar"
            style={{
              width: 40,
              height: 40,
              display: "grid",
              placeItems: "center",
              borderRadius: "11px 2px 11px 2px",
              background: "var(--rice-2)",
            }}
          >
            <IcClose size={22} />
          </button>
        </div>

        {cart.length === 0 ? (
          <div
            style={{
              flex: 1,
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              justifyContent: "center",
              gap: 18,
              padding: "60px 30px",
              textAlign: "center",
              minHeight: 280,
            }}
          >
            <YuzuSlice size={70} line="var(--rice-3)" seed="var(--rice-3)" />
            <p style={{ fontFamily: "var(--display)", fontSize: 24 }}>
              Tu carrito está vacío
            </p>
            <p style={{ color: "rgba(30,27,24,.55)", maxWidth: 240 }}>
              Agrega algunos platos del menú para empezar tu pedido.
            </p>
            <Button
              onClick={() => {
                onClose();
                go("menu");
              }}
            >
              Ver el menú
            </Button>
          </div>
        ) : (
          <React.Fragment>
            <div style={{ padding: "8px 24px 0", flex: 1, overflowY: "auto" }}>
              <div style={{ padding: "12px 0 4px" }}>
                <FulfillmentToggle
                  value={fulfillment}
                  onChange={setFulfillment}
                  compact
                />
              </div>
              {cart.map((l) => (
                <CartLine
                  key={l.uid}
                  line={l}
                  setQty={(n) => setQty(l.uid, n)}
                  remove={() => remove(l.uid)}
                />
              ))}
            </div>
            <div
              style={{
                borderTop: "1px solid var(--rice-3)",
                padding: "18px 24px calc(20px + env(safe-area-inset-bottom))",
                background: "var(--rice)",
              }}
            >
              <Row label="Subtotal" value={YY.CLP(subtotal)} />
              {fulfillment === "delivery" && (
                <Row
                  label="Delivery"
                  value={cart.length ? YY.CLP(fee) : "—"}
                  muted
                />
              )}
              <Row label="Total" value={YY.CLP(total)} big />
              <div style={{ marginTop: 14 }}>
                <Button full size="lg" onClick={onCheckout}>
                  Ir a pagar · {YY.CLP(total)}
                </Button>
              </div>
            </div>
          </React.Fragment>
        )}
      </aside>
    </Overlay>
  );
}

function Row({ label, value, big, muted }) {
  return (
    <div
      style={{
        display: "flex",
        justifyContent: "space-between",
        alignItems: "baseline",
        padding: big ? "10px 0 2px" : "5px 0",
      }}
    >
      <span
        style={{
          fontSize: big ? 18 : 15,
          fontWeight: big ? 700 : 500,
          fontFamily: big ? "var(--display)" : "var(--body)",
          color: muted ? "rgba(30,27,24,.55)" : "var(--ink)",
        }}
      >
        {label}
      </span>
      <span
        style={{
          fontFamily: "var(--display)",
          fontWeight: 700,
          fontSize: big ? 24 : 16,
          color: muted ? "rgba(30,27,24,.55)" : "var(--ink)",
        }}
      >
        {value}
      </span>
    </div>
  );
}

/* ---------- checkout ---------- */
const PAY_METHODS = [
  { id: "webpay", label: "Webpay", sub: "Débito / Crédito · Transbank" },
  { id: "mercadopago", label: "Mercado Pago", sub: "Saldo, tarjetas o cuotas" },
  { id: "mach", label: "MACH", sub: "Paga con tu cuenta MACH" },
];
const PICKUP_TIMES = [
  "Lo antes posible",
  "13:30",
  "14:00",
  "20:00",
  "20:30",
  "21:00",
];

function Checkout({ cart, fulfillment, setFulfillment, onClose, onConfirm }) {
  const narrow = useNarrow();
  const [pay, setPay] = React.useState("webpay");
  const [time, setTime] = React.useState(PICKUP_TIMES[0]);
  const [done, setDone] = React.useState(false);
  const [form, setForm] = React.useState({
    nombre: "",
    telefono: "",
    direccion: "",
  });
  const subtotal = cart.reduce((s, l) => s + l.unit * l.qty, 0);
  const fee = fulfillment === "delivery" ? DELIVERY_FEE : 0;
  const total = subtotal + fee;
  const order = "YY-" + Math.floor(1000 + Math.random() * 9000);

  const inp = {
    width: "100%",
    padding: "13px 15px",
    border: "1.5px solid var(--rice-3)",
    borderRadius: "var(--r-sm)",
    background: "var(--rice)",
    outline: "none",
    fontSize: 15.5,
  };

  if (done) {
    return (
      <Overlay onClose={onClose} side={narrow ? "bottom" : "center"}>
        <div
          style={{
            background: "var(--rice)",
            borderRadius: narrow ? "26px 26px 0 0" : "var(--r-lg)",
            padding: "clamp(40px,6vw,64px) clamp(28px,4vw,52px)",
            width: narrow ? "100%" : "min(480px,94vw)",
            textAlign: "center",
          }}
        >
          <div
            style={{
              width: 84,
              height: 84,
              margin: "0 auto 22px",
              borderRadius: "26px 5px 26px 5px",
              background: "var(--saffron)",
              color: "var(--rice)",
              display: "grid",
              placeItems: "center",
            }}
          >
            <IcCheck size={44} />
          </div>
          <h2 style={{ fontSize: "clamp(28px,4vw,40px)", lineHeight: 1 }}>
            ¡Pedido confirmado!
          </h2>
          <p
            style={{
              color: "rgba(30,27,24,.65)",
              margin: "14px 0 6px",
              fontSize: 16.5,
            }}
          >
            Tu orden <strong>{order}</strong> está en preparación.
          </p>
          <p style={{ color: "rgba(30,27,24,.65)", fontSize: 16.5 }}>
            {fulfillment === "retiro"
              ? `Retírala en Av. Concha y Toro 1450, Puente Alto · ${time === PICKUP_TIMES[0] ? "20–30 min" : time}`
              : "Te avisaremos cuando el delivery vaya en camino."}
          </p>
          <div
            style={{
              background: "var(--rice-2)",
              borderRadius: "var(--r-md)",
              padding: "18px 22px",
              margin: "26px 0",
              textAlign: "left",
            }}
          >
            <Row label="Total pagado" value={YY.CLP(total)} big />
            <span style={{ fontSize: 13.5, color: "rgba(30,27,24,.55)" }}>
              Pagado con {PAY_METHODS.find((p) => p.id === pay).label}
            </span>
          </div>
          <Button full size="lg" onClick={onConfirm}>
            Volver al inicio
          </Button>
        </div>
      </Overlay>
    );
  }

  return (
    <Overlay onClose={onClose} side={narrow ? "bottom" : "center"}>
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          background: "var(--rice)",
          width: narrow ? "100%" : "min(880px,95vw)",
          maxHeight: narrow ? "92vh" : "min(90vh,840px)",
          borderRadius: narrow ? "26px 26px 0 0" : "var(--r-lg)",
          overflow: "hidden",
        }}
      >
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            padding: "20px 26px",
            borderBottom: "1px solid var(--rice-3)",
            flexShrink: 0,
          }}
        >
          <h2 style={{ fontSize: 26 }}>Pagar</h2>
          <button
            onClick={onClose}
            aria-label="Cerrar"
            style={{
              width: 40,
              height: 40,
              display: "grid",
              placeItems: "center",
              borderRadius: "11px 2px 11px 2px",
              background: "var(--rice-2)",
            }}
          >
            <IcClose size={22} />
          </button>
        </div>

        <div
          style={{
            display: "grid",
            gridTemplateColumns: narrow ? "1fr" : "1.3fr 1fr",
            overflow: "hidden",
            flex: 1,
          }}
        >
          {/* form column */}
          <div
            style={{
              overflowY: "auto",
              padding: "clamp(22px,3vw,32px)",
              borderRight: narrow ? "none" : "1px solid var(--rice-3)",
            }}
          >
            <Field label="¿Cómo lo quieres?">
              <FulfillmentToggle
                value={fulfillment}
                onChange={setFulfillment}
              />
            </Field>

            {fulfillment === "delivery" ? (
              <Field
                label="Dirección de entrega"
                hint="Puente Alto y comunas cercanas"
              >
                <input
                  style={inp}
                  placeholder="Calle, número, depto"
                  value={form.direccion}
                  onChange={(e) =>
                    setForm({ ...form, direccion: e.target.value })
                  }
                />
              </Field>
            ) : (
              <Field label="Horario de retiro">
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                  {PICKUP_TIMES.map((tm) => (
                    <button
                      key={tm}
                      onClick={() => setTime(tm)}
                      style={{
                        padding: "10px 16px",
                        borderRadius: "11px 2px 11px 2px",
                        fontWeight: 600,
                        fontSize: 14,
                        border: `1.5px solid ${time === tm ? "var(--saffron)" : "var(--rice-3)"}`,
                        background:
                          time === tm ? "var(--saffron-soft)" : "var(--rice)",
                        color: time === tm ? "var(--saffron)" : "var(--ink)",
                      }}
                    >
                      {tm}
                    </button>
                  ))}
                </div>
              </Field>
            )}

            <Field label="Tus datos">
              <div style={{ display: "grid", gap: 10 }}>
                <input
                  style={inp}
                  placeholder="Nombre y apellido"
                  value={form.nombre}
                  onChange={(e) => setForm({ ...form, nombre: e.target.value })}
                />
                <input
                  style={inp}
                  placeholder="Teléfono (+56 9 …)"
                  value={form.telefono}
                  onChange={(e) =>
                    setForm({ ...form, telefono: e.target.value })
                  }
                />
              </div>
            </Field>

            <Field label="Medio de pago">
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {PAY_METHODS.map((p) => (
                  <button
                    key={p.id}
                    onClick={() => setPay(p.id)}
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 12,
                      textAlign: "left",
                      padding: "14px 16px",
                      borderRadius: "var(--r-sm)",
                      border: `1.5px solid ${pay === p.id ? "var(--saffron)" : "var(--rice-3)"}`,
                      background:
                        pay === p.id ? "var(--saffron-soft)" : "var(--rice)",
                    }}
                  >
                    <span
                      style={{
                        width: 20,
                        height: 20,
                        borderRadius: "50%",
                        border: `2px solid ${pay === p.id ? "var(--saffron)" : "var(--rice-3)"}`,
                        display: "grid",
                        placeItems: "center",
                        flexShrink: 0,
                      }}
                    >
                      {pay === p.id && (
                        <span
                          style={{
                            width: 10,
                            height: 10,
                            borderRadius: "50%",
                            background: "var(--saffron)",
                          }}
                        ></span>
                      )}
                    </span>
                    <span style={{ flex: 1 }}>
                      <span
                        style={{
                          fontWeight: 600,
                          fontSize: 15.5,
                          display: "block",
                        }}
                      >
                        {p.label}
                      </span>
                      <span
                        style={{ fontSize: 13, color: "rgba(30,27,24,.55)" }}
                      >
                        {p.sub}
                      </span>
                    </span>
                  </button>
                ))}
              </div>
            </Field>
          </div>

          {/* summary column */}
          <div
            style={{
              background: "var(--rice-2)",
              display: "flex",
              flexDirection: "column",
              overflow: "hidden",
            }}
          >
            <div
              style={{
                padding: "clamp(22px,3vw,30px) clamp(22px,3vw,30px) 8px",
                overflowY: "auto",
                flex: 1,
              }}
            >
              <div className="eyebrow" style={{ marginBottom: 14 }}>
                Resumen
              </div>
              {cart.map((l) => (
                <div
                  key={l.uid}
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    gap: 12,
                    padding: "8px 0",
                    fontSize: 14.5,
                  }}
                >
                  <span>
                    <strong style={{ fontWeight: 600 }}>{l.qty}×</strong>{" "}
                    {l.item.name}
                    {modSummary(l) ? (
                      <span
                        style={{
                          color: "rgba(30,27,24,.5)",
                          display: "block",
                          fontSize: 12.5,
                        }}
                      >
                        {modSummary(l)}
                      </span>
                    ) : null}
                  </span>
                  <span
                    style={{ fontFamily: "var(--display)", fontWeight: 700 }}
                  >
                    {YY.CLP(l.unit * l.qty)}
                  </span>
                </div>
              ))}
            </div>
            <div
              style={{
                padding:
                  "14px clamp(22px,3vw,30px) calc(20px + env(safe-area-inset-bottom))",
                borderTop: "1px solid var(--rice-3)",
              }}
            >
              <Row label="Subtotal" value={YY.CLP(subtotal)} />
              {fee > 0 && <Row label="Delivery" value={YY.CLP(fee)} muted />}
              <Row label="Total" value={YY.CLP(total)} big />
              <div style={{ marginTop: 12 }}>
                <Button full size="lg" onClick={() => setDone(true)}>
                  Pagar {YY.CLP(total)}
                </Button>
              </div>
              <p
                style={{
                  fontSize: 12,
                  color: "rgba(30,27,24,.45)",
                  textAlign: "center",
                  marginTop: 10,
                }}
              >
                Pago seguro · Precios en CLP con IVA incluido
              </p>
            </div>
          </div>
        </div>
      </div>
    </Overlay>
  );
}

function Field({ label, hint, children }) {
  return (
    <div style={{ marginBottom: 24 }}>
      <div
        style={{
          display: "flex",
          alignItems: "baseline",
          gap: 10,
          marginBottom: 10,
        }}
      >
        <h3
          style={{ fontFamily: "var(--body)", fontWeight: 700, fontSize: 16 }}
        >
          {label}
        </h3>
        {hint && (
          <span style={{ fontSize: 12.5, color: "rgba(30,27,24,.5)" }}>
            {hint}
          </span>
        )}
      </div>
      {children}
    </div>
  );
}

Object.assign(window, { CartDrawer, Checkout, DELIVERY_FEE });
