/* ============================================================
   YUZU YATAI — Menú / Pedir en línea
   MenuCard (3 variants) · MenuPage · ItemModal · CartDrawer · Checkout
   ============================================================ */

/* ---------- MENU CARD (3 variants) ---------- */
function AddBtn({ onClick, label = "Agregar", compact }) {
  const [h, setH] = React.useState(false);
  if (compact)
    return (
      <button
        onClick={onClick}
        aria-label="Agregar"
        onMouseEnter={() => setH(true)}
        onMouseLeave={() => setH(false)}
        style={{
          width: 42,
          height: 42,
          display: "grid",
          placeItems: "center",
          borderRadius: "13px 3px 13px 3px",
          background: h ? "var(--saffron-deep)" : "var(--saffron)",
          color: "var(--rice)",
          flexShrink: 0,
          boxShadow: "0 10px 22px -12px rgba(160,46,46,.8)",
          transition: "background .2s, transform .2s",
          transform: h ? "translateY(-2px)" : "none",
        }}
      >
        <IcPlus size={22} />
      </button>
    );
  return (
    <Button size="sm" onClick={onClick}>
      <IcPlus size={16} /> {label}
    </Button>
  );
}

function PriceTag({ value, size = 19 }) {
  return (
    <span
      style={{
        fontFamily: "var(--display)",
        fontWeight: 700,
        fontSize: size,
        letterSpacing: "-.01em",
      }}
    >
      {YY.CLP(value)}
    </span>
  );
}

function MenuCard({ item, onAdd, variant = "stacked" }) {
  const [h, setH] = React.useState(false);
  const lift = {
    transform: h ? "translateY(-4px)" : "none",
    transition: "transform .3s cubic-bezier(.2,.7,.2,1), box-shadow .3s",
  };

  if (variant === "overlay") {
    return (
      <article
        onMouseEnter={() => setH(true)}
        onMouseLeave={() => setH(false)}
        className="grain"
        style={{
          position: "relative",
          overflow: "hidden",
          borderRadius: "var(--r-md)",
          aspectRatio: "3 / 4",
          background: "var(--ink)",
          boxShadow: h ? "var(--shadow-card)" : "var(--shadow-soft)",
          ...lift,
        }}
      >
        <FoodImage
          src={item.img}
          label={item.ph}
          ratio="3 / 4"
          radius="0"
          style={{ position: "absolute", inset: 0 }}
        />
        <div
          style={{
            position: "absolute",
            inset: 0,
            background:
              "linear-gradient(180deg,rgba(30,27,24,0) 35%,rgba(30,27,24,.4) 60%,rgba(30,27,24,.92) 100%)",
          }}
        ></div>
        {item.tags[0] && (
          <div style={{ position: "absolute", top: 14, left: 14 }}>
            <TagChip tag={item.tags[0]} small />
          </div>
        )}
        <div
          style={{
            position: "absolute",
            left: 0,
            right: 0,
            bottom: 0,
            padding: 18,
            color: "var(--rice)",
          }}
        >
          <h3 style={{ color: "var(--rice)", fontSize: 22, lineHeight: 1.05 }}>
            {item.name}
          </h3>
          <p
            style={{
              color: "rgba(244,239,231,.72)",
              fontSize: 13.5,
              margin: "7px 0 14px",
              display: "-webkit-box",
              WebkitLineClamp: 2,
              WebkitBoxOrient: "vertical",
              overflow: "hidden",
            }}
          >
            {item.desc}
          </p>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
            }}
          >
            <span style={{ color: "var(--rice)" }}>
              <PriceTag value={item.price} size={20} />
            </span>
            <AddBtn onClick={onAdd} compact />
          </div>
        </div>
      </article>
    );
  }

  if (variant === "editorial") {
    return (
      <article
        onMouseEnter={() => setH(true)}
        onMouseLeave={() => setH(false)}
        style={{
          display: "flex",
          gap: 16,
          alignItems: "center",
          background: "var(--rice)",
          borderRadius: "var(--r-md)",
          padding: 12,
          boxShadow: h ? "var(--shadow-card)" : "var(--shadow-soft)",
          ...lift,
        }}
      >
        <FoodImage
          src={item.img}
          label={item.ph}
          ratio="1 / 1"
          radius="var(--r-sm)"
          style={{ width: 112, flexShrink: 0 }}
        />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div
            style={{
              display: "flex",
              gap: 8,
              marginBottom: 6,
              flexWrap: "wrap",
            }}
          >
            {item.tags.map((t) => (
              <TagChip key={t} tag={t} xs />
            ))}
          </div>
          <h3 style={{ fontSize: 19, lineHeight: 1.1 }}>{item.name}</h3>
          <p
            style={{
              color: "rgba(30,27,24,.62)",
              fontSize: 13.5,
              margin: "5px 0 10px",
              display: "-webkit-box",
              WebkitLineClamp: 2,
              WebkitBoxOrient: "vertical",
              overflow: "hidden",
            }}
          >
            {item.desc}
          </p>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
            }}
          >
            <PriceTag value={item.price} />
            <AddBtn onClick={onAdd} compact />
          </div>
        </div>
      </article>
    );
  }

  // stacked (default)
  return (
    <article
      onMouseEnter={() => setH(true)}
      onMouseLeave={() => setH(false)}
      style={{
        display: "flex",
        flexDirection: "column",
        background: "var(--rice)",
        borderRadius: "var(--r-md)",
        overflow: "hidden",
        boxShadow: h ? "var(--shadow-card)" : "var(--shadow-soft)",
        ...lift,
      }}
    >
      <div style={{ position: "relative" }}>
        <FoodImage src={item.img} label={item.ph} ratio="4 / 3" radius="0" />
        {item.tags[0] && (
          <div style={{ position: "absolute", top: 12, left: 12 }}>
            <TagChip tag={item.tags[0]} small />
          </div>
        )}
      </div>
      <div
        style={{
          padding: "18px 18px 20px",
          display: "flex",
          flexDirection: "column",
          flex: 1,
        }}
      >
        <h3 style={{ fontSize: 21, lineHeight: 1.08 }}>{item.name}</h3>
        <p
          style={{
            color: "rgba(30,27,24,.64)",
            fontSize: 14,
            margin: "8px 0 16px",
            flex: 1,
          }}
        >
          {item.desc}
        </p>
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            gap: 10,
          }}
        >
          <PriceTag value={item.price} size={21} />
          <AddBtn onClick={onAdd} />
        </div>
      </div>
    </article>
  );
}

/* ---------- MENU PAGE ---------- */
function FulfillmentToggle({ value, onChange, compact }) {
  return (
    <div
      style={{
        display: "inline-flex",
        background: "var(--rice-2)",
        borderRadius: "14px 3px 14px 3px",
        padding: 4,
        gap: 4,
      }}
    >
      {[
        { id: "retiro", label: "Retiro", I: IcStore },
        { id: "delivery", label: "Delivery", I: IcBike },
      ].map((o) => (
        <button
          key={o.id}
          onClick={() => onChange(o.id)}
          style={{
            display: "inline-flex",
            alignItems: "center",
            gap: 8,
            padding: compact ? "8px 14px" : "10px 18px",
            borderRadius: "11px 2px 11px 2px",
            fontWeight: 600,
            fontSize: 14.5,
            background: value === o.id ? "var(--ink)" : "transparent",
            color: value === o.id ? "var(--rice)" : "var(--ink)",
            transition: "background .2s,color .2s",
          }}
        >
          <o.I size={18} /> {o.label}
        </button>
      ))}
    </div>
  );
}

function MenuPage({
  openItem,
  cartCount,
  cartTotal,
  onCart,
  fulfillment,
  setFulfillment,
  cardVariant,
}) {
  const [cat, setCat] = React.useState("todos");
  const tabs = [{ id: "todos", label: "Todo" }, ...YY.CATS];
  const items =
    cat === "todos" ? YY.MENU : YY.MENU.filter((m) => m.cat === cat);
  const tabRef = React.useRef(null);

  // Layout: list is the default everywhere (easier to scan); the user can
  // switch to the gallery grid via the toggle.
  const [view, setView] = React.useState(null);
  const effectiveView = view ?? "list";
  const variant = effectiveView === "list" ? "editorial" : cardVariant;
  // min(100%, …) keeps the track from exceeding the container on very narrow
  // phones, so a single column always fits instead of overflowing horizontally.
  const gridCols =
    effectiveView === "list"
      ? "repeat(auto-fill,minmax(min(100%,320px),1fr))"
      : "repeat(auto-fill,minmax(min(100%,260px),1fr))";

  return (
    <main>
      {/* header */}
      <section
        style={{ background: "var(--ink)", color: "var(--rice)" }}
        className="grain on-ink"
      >
        <div
          className="wrap"
          style={{
            padding:
              "clamp(40px,6vw,72px) clamp(20px,5vw,56px) clamp(30px,4vw,44px)",
          }}
        >
          <Eyebrow tone="cream">Menú · Pedir en línea</Eyebrow>
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "flex-end",
              gap: 24,
              flexWrap: "wrap",
              marginTop: 12,
            }}
          >
            <h1
              className="font-display"
              style={{
                color: "var(--rice)",
                fontSize: "clamp(36px,5.5vw,72px)",
                lineHeight: 0.98,
              }}
            >
              Arma tu pedido
            </h1>
            <div
              style={{
                display: "flex",
                flexDirection: "column",
                gap: 8,
                alignItems: "flex-start",
              }}
            >
              <FulfillmentToggle
                value={fulfillment}
                onChange={setFulfillment}
              />
              <span
                style={{
                  fontSize: 13,
                  color: "rgba(244,239,231,.6)",
                  display: "inline-flex",
                  alignItems: "center",
                  gap: 6,
                }}
              >
                <IcClock size={14} />{" "}
                {fulfillment === "retiro"
                  ? "Listo en 20–30 min"
                  : "Delivery 35–50 min · Puente Alto y alrededores"}
              </span>
            </div>
          </div>
        </div>
      </section>

      {/* sticky category tabs */}
      <div
        style={{
          position: "sticky",
          top: 76,
          zIndex: 30,
          background: "rgba(244,239,231,.92)",
          backdropFilter: "blur(12px)",
          borderBottom: "1px solid var(--rice-3)",
        }}
      >
        <div
          className="wrap"
          style={{
            padding: "0 clamp(20px,5vw,56px)",
            display: "flex",
            alignItems: "center",
            gap: 12,
          }}
        >
          <div
            ref={tabRef}
            style={{
              display: "flex",
              gap: 8,
              overflowX: "auto",
              padding: "14px 0",
              scrollbarWidth: "none",
              flex: 1,
            }}
          >
            {tabs.map((tb) => (
              <button
                key={tb.id}
                onClick={() => setCat(tb.id)}
                style={{
                  whiteSpace: "nowrap",
                  padding: "9px 18px",
                  borderRadius: "12px 3px 12px 3px",
                  fontWeight: 600,
                  fontSize: 14.5,
                  background: cat === tb.id ? "var(--saffron)" : "var(--rice)",
                  color: cat === tb.id ? "var(--rice)" : "var(--ink)",
                  border:
                    cat === tb.id
                      ? "1px solid var(--saffron)"
                      : "1px solid var(--rice-3)",
                  transition: "all .2s",
                }}
              >
                {tb.label}
              </button>
            ))}
          </div>

          {/* layout toggle */}
          <div
            role="radiogroup"
            aria-label="Diseño de tarjetas"
            style={{
              display: "inline-flex",
              flexShrink: 0,
              background: "var(--rice-2)",
              borderRadius: "12px 3px 12px 3px",
              padding: 4,
              gap: 4,
            }}
          >
            {[
              { id: "grid", I: IcGrid, label: "Grilla" },
              { id: "list", I: IcRows, label: "Lista" },
            ].map((o) => {
              const on = effectiveView === o.id;
              return (
                <button
                  key={o.id}
                  onClick={() => setView(o.id)}
                  role="radio"
                  aria-checked={on}
                  aria-label={o.label}
                  title={o.label}
                  style={{
                    display: "grid",
                    placeItems: "center",
                    width: 36,
                    height: 34,
                    borderRadius: "9px 2px 9px 2px",
                    background: on ? "var(--ink)" : "transparent",
                    color: on ? "var(--rice)" : "var(--ink)",
                    transition: "background .2s, color .2s",
                  }}
                >
                  <o.I size={18} />
                </button>
              );
            })}
          </div>
        </div>
      </div>

      {/* grid */}
      <section
        className="wrap"
        style={{ padding: "clamp(28px,4vw,48px) clamp(20px,5vw,56px) 120px" }}
      >
        {cat === "todos" ? (
          YY.CATS.map((c) => {
            const list = YY.MENU.filter((m) => m.cat === c.id);
            return (
              <div key={c.id} style={{ marginBottom: 56 }}>
                <h2
                  style={{
                    fontSize: "clamp(24px,3vw,36px)",
                    marginBottom: 22,
                    display: "flex",
                    alignItems: "baseline",
                    gap: 12,
                  }}
                >
                  {c.label}
                  <span
                    style={{
                      fontSize: 14,
                      fontFamily: "var(--body)",
                      fontWeight: 500,
                      color: "rgba(30,27,24,.45)",
                    }}
                  >
                    {list.length} platos
                  </span>
                </h2>
                <div
                  style={{
                    display: "grid",
                    gridTemplateColumns: gridCols,
                    gap: "clamp(16px,2vw,24px)",
                  }}
                >
                  {list.map((m) => (
                    <MenuCard
                      key={m.id}
                      item={m}
                      onAdd={() => openItem(m)}
                      variant={variant}
                    />
                  ))}
                </div>
              </div>
            );
          })
        ) : (
          <div
            style={{
              display: "grid",
              gridTemplateColumns: gridCols,
              gap: "clamp(16px,2vw,24px)",
            }}
          >
            {items.map((m) => (
              <MenuCard
                key={m.id}
                item={m}
                onAdd={() => openItem(m)}
                variant={variant}
              />
            ))}
          </div>
        )}
      </section>
    </main>
  );
}

/* ---------- ITEM MODAL (modifiers) ---------- */
function Stepper({ qty, setQty, big }) {
  const btn = {
    width: big ? 46 : 38,
    height: big ? 46 : 38,
    display: "grid",
    placeItems: "center",
    borderRadius: "11px 2px 11px 2px",
    background: "var(--rice-2)",
    color: "var(--ink)",
  };
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 12 }}>
      <button
        onClick={() => setQty(Math.max(1, qty - 1))}
        style={btn}
        aria-label="Menos"
      >
        <IcMinus size={18} />
      </button>
      <span
        style={{
          fontFamily: "var(--display)",
          fontWeight: 700,
          fontSize: big ? 24 : 20,
          minWidth: 26,
          textAlign: "center",
        }}
      >
        {qty}
      </span>
      <button onClick={() => setQty(qty + 1)} style={btn} aria-label="Más">
        <IcPlus size={18} />
      </button>
    </div>
  );
}

function ItemModal({ item, onClose, onAdd }) {
  const [qty, setQty] = React.useState(1);
  const [tamano, setTamano] = React.useState("normal");
  const [extras, setExtras] = React.useState([]);
  const [notes, setNotes] = React.useState("");
  const narrow = useNarrow();
  const M = YY.MODIFIERS;

  const tamPrice = M.tamano.options.find((o) => o.id === tamano).price;
  const extraPrice = extras.reduce(
    (s, id) => s + M.extras.options.find((o) => o.id === id).price,
    0,
  );
  const unit = item.price + tamPrice + extraPrice;
  const total = unit * qty;

  const toggleExtra = (id) =>
    setExtras((x) => (x.includes(id) ? x.filter((e) => e !== id) : [...x, id]));

  const add = () => {
    onAdd({
      uid:
        item.id +
        ":" +
        tamano +
        ":" +
        extras.slice().sort().join("-") +
        ":" +
        Date.now(),
      item,
      qty,
      tamano,
      extras: extras.slice(),
      notes,
      unit,
    });
    onClose();
  };

  return (
    <Overlay onClose={onClose} side={narrow ? "bottom" : "center"}>
      <div
        style={{
          position: "relative",
          display: "flex",
          flexDirection: "column",
          maxHeight: narrow ? "90vh" : "min(90vh,660px)",
          width: narrow ? "100%" : "min(900px,95vw)",
          background: "var(--rice)",
          borderRadius: narrow ? "26px 26px 0 0" : "var(--r-lg)",
          overflow: "hidden",
        }}
      >
        {/* close — floats over the top-right corner */}
        <button
          onClick={onClose}
          aria-label="Cerrar"
          style={{
            position: "absolute",
            top: 14,
            right: 14,
            zIndex: 5,
            width: 42,
            height: 42,
            borderRadius: "50%",
            background: "rgba(244,239,231,.92)",
            boxShadow: "0 2px 10px rgba(30,27,24,.18)",
            display: "grid",
            placeItems: "center",
            color: "var(--ink)",
          }}
        >
          <IcClose size={22} />
        </button>

        {/* two columns on desktop, stacked on mobile */}
        <div
          style={{
            display: "flex",
            flexDirection: narrow ? "column" : "row",
            flex: 1,
            minHeight: 0,
          }}
        >
          {/* image column */}
          <div
            style={{
              position: "relative",
              flexShrink: 0,
              background: "var(--ink)",
              width: narrow ? "auto" : "42%",
            }}
          >
            <FoodImage
              src={item.img}
              label={item.ph}
              ratio={narrow ? "16 / 9" : "auto"}
              radius="0"
              style={narrow ? undefined : { height: "100%" }}
            />
            {item.tags[0] && (
              <div
                style={{
                  position: "absolute",
                  bottom: 14,
                  left: 14,
                  display: "flex",
                  gap: 8,
                }}
              >
                {item.tags.map((t) => (
                  <TagChip key={t} tag={t} />
                ))}
              </div>
            )}
          </div>

          {/* options column (scrolls) */}
          <div
            style={{
              flex: 1,
              minWidth: 0,
              padding: "28px clamp(20px,3vw,34px)",
              overflowY: "auto",
            }}
          >
            <h2
              style={{
                fontSize: "clamp(26px,3.4vw,34px)",
                lineHeight: 1.02,
                paddingRight: 44,
              }}
            >
              {item.name}
            </h2>
            <p
              style={{
                color: "rgba(30,27,24,.66)",
                marginTop: 10,
                fontSize: 16,
              }}
            >
              {item.desc}
            </p>
            <div style={{ marginTop: 10 }}>
              <PriceTag value={item.price} size={22} />
            </div>

            {/* tamaño */}
            <ModGroup label="Tamaño" required>
              {M.tamano.options.map((o) => (
                <OptRow
                  key={o.id}
                  type="radio"
                  active={tamano === o.id}
                  onClick={() => setTamano(o.id)}
                  label={o.label}
                  price={o.price}
                />
              ))}
            </ModGroup>
            {/* extras */}
            <ModGroup label="Extras" hint="Opcional">
              {M.extras.options.map((o) => (
                <OptRow
                  key={o.id}
                  type="check"
                  active={extras.includes(o.id)}
                  onClick={() => toggleExtra(o.id)}
                  label={o.label}
                  price={o.price}
                />
              ))}
            </ModGroup>
            {/* notas */}
            <ModGroup label="Notas para la cocina" hint="Opcional">
              <textarea
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                rows={2}
                placeholder="Ej: sin cilantro, salsa aparte…"
                style={{
                  width: "100%",
                  resize: "vertical",
                  border: "1.5px solid var(--rice-3)",
                  borderRadius: "var(--r-sm)",
                  padding: "12px 14px",
                  background: "var(--rice)",
                  outline: "none",
                  fontSize: 15,
                }}
              />
            </ModGroup>
          </div>
        </div>

        {/* footer — spans the full width under both columns */}
        <div
          style={{
            flexShrink: 0,
            borderTop: "1px solid var(--rice-3)",
            padding:
              "14px clamp(20px,4vw,30px) calc(16px + env(safe-area-inset-bottom))",
            display: "flex",
            alignItems: "center",
            gap: 16,
            background: "var(--rice)",
          }}
        >
          <Stepper qty={qty} setQty={setQty} big />
          <div style={{ flex: 1 }}>
            <Button full size="lg" onClick={add}>
              Agregar · {YY.CLP(total)}
            </Button>
          </div>
        </div>
      </div>
    </Overlay>
  );
}

function ModGroup({ label, hint, required, children }) {
  return (
    <div style={{ marginTop: 24 }}>
      <div
        style={{
          display: "flex",
          alignItems: "baseline",
          gap: 10,
          marginBottom: 12,
        }}
      >
        <h3
          style={{ fontSize: 17, fontFamily: "var(--body)", fontWeight: 700 }}
        >
          {label}
        </h3>
        {required && (
          <span
            style={{
              fontSize: 11,
              fontWeight: 600,
              letterSpacing: ".08em",
              textTransform: "uppercase",
              color: "var(--saffron)",
            }}
          >
            Requerido
          </span>
        )}
        {hint && (
          <span style={{ fontSize: 13, color: "rgba(30,27,24,.45)" }}>
            {hint}
          </span>
        )}
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {children}
      </div>
    </div>
  );
}

function OptRow({ type, active, onClick, label, price }) {
  return (
    <button
      onClick={onClick}
      style={{
        display: "flex",
        alignItems: "center",
        gap: 12,
        width: "100%",
        textAlign: "left",
        padding: "12px 14px",
        borderRadius: "var(--r-sm)",
        background: active ? "var(--saffron-soft)" : "var(--rice-2)",
        border: `1.5px solid ${active ? "var(--saffron)" : "transparent"}`,
        transition: "all .18s",
      }}
    >
      <span
        style={{
          width: 22,
          height: 22,
          flexShrink: 0,
          borderRadius: type === "radio" ? "50%" : "6px",
          border: `2px solid ${active ? "var(--saffron)" : "var(--rice-3)"}`,
          background: active ? "var(--saffron)" : "transparent",
          display: "grid",
          placeItems: "center",
          color: "var(--rice)",
        }}
      >
        {active && <IcCheck size={14} />}
      </span>
      <span style={{ flex: 1, fontWeight: 500, fontSize: 15.5 }}>{label}</span>
      {price > 0 && (
        <span style={{ color: "rgba(30,27,24,.6)", fontSize: 14.5 }}>
          +{YY.CLP(price)}
        </span>
      )}
    </button>
  );
}

/* ---------- generic overlay ---------- */
function Overlay({ children, onClose, side = "center" }) {
  React.useEffect(() => {
    const k = (e) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", k);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", k);
      document.body.style.overflow = "";
    };
  }, []);
  const pos =
    side === "bottom"
      ? { alignItems: "flex-end", justifyContent: "center" }
      : side === "right"
        ? { alignItems: "stretch", justifyContent: "flex-end" }
        : { alignItems: "center", justifyContent: "center", padding: 20 };
  return (
    <div
      style={{
        position: "fixed",
        inset: 0,
        zIndex: 100,
        display: "flex",
        ...pos,
      }}
    >
      <div
        onClick={onClose}
        style={{
          position: "absolute",
          inset: 0,
          background: "rgba(30,27,24,.55)",
          animation: "fadeIn .25s both",
          backdropFilter: "blur(2px)",
        }}
      ></div>
      <div
        style={{
          position: "relative",
          zIndex: 2,
          animation:
            side === "center"
              ? "scaleIn .3s cubic-bezier(.2,.7,.2,1) both"
              : "slideUp .35s cubic-bezier(.2,.7,.2,1) both",
          maxWidth: "100%",
        }}
      >
        {children}
      </div>
    </div>
  );
}

Object.assign(window, {
  MenuCard,
  MenuPage,
  ItemModal,
  Overlay,
  FulfillmentToggle,
  Stepper,
  AddBtn,
  PriceTag,
});
