"use client";

import { useEffect, useState, useMemo, useCallback } from "react";
import { useRouter } from "next/navigation";
import { Search, ShoppingCart, Plus, Minus, X, Truck, Package, LayoutGrid, List as ListIcon } from "lucide-react";
import Swal from "sweetalert2";

interface Item {
  OBJID: string;
  ITEM_CODE: string;
  ITEM_NAME: string;
  ITEM_DETAIL: string;
  MAKER_NAME: string;
  UNIT: string;
  UNIT_PRICE: number;
  IS_TAX_FREE: string;
  IMAGE_URL: string;
  STOCK_QTY: number;
  MAX_ORDER_QTY: number | null;
  IS_HIDDEN: string;
  REQUIRES_DELIVERY: string;
}
interface CartLine { item: Item; qty: number }
interface ExtraLine { id: string; kind: "DELIVERY" | "CHARTER"; unitPrice: number; qty: number; label: string }

const DEFAULT_CHARTER_PRICE = 5000;
const DEFAULT_DELIVERY_PRICE = 4000;

const fmt = (n: number) => Number(n || 0).toLocaleString("ko-KR");
const newKey = () => Math.random().toString(36).slice(2, 10) + Date.now().toString(36);

export default function ItemsBrowse() {
  const router = useRouter();
  const [items, setItems] = useState<Item[]>([]);
  const [keyword, setKeyword] = useState("");
  const [taxFilter, setTaxFilter] = useState<"" | "Y" | "N">("");
  const [stockFilter, setStockFilter] = useState<"AVAILABLE" | "ALL">("AVAILABLE");
  const [loading, setLoading] = useState(false);
  const [cart, setCart] = useState<CartLine[]>([]);
  const [extras, setExtras] = useState<ExtraLine[]>([]);
  const [cartOpen, setCartOpen] = useState(false);
  const [viewMode, setViewMode] = useState<"card" | "list">("card");
  // 현재 사용자의 발주 한도 우회 권한 (관리자 또는 unlimited_qty='Y' 거래처)
  const [unlimitedQty, setUnlimitedQty] = useState(false);

  useEffect(() => {
    fetch("/api/auth/me").then((r) => r.json()).then((d) => {
      if (d?.user) {
        const isAdmin = d.user.role === "ADMIN" || d.user.isAdmin === true || d.user.userType === "A";
        setUnlimitedQty(isAdmin || !!d.user.unlimitedQty);
      }
    }).catch(() => {});
  }, []);

  const fetchItems = useCallback(async () => {
    setLoading(true);
    const res = await fetch("/api/m/items/list", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        keyword,
        isTaxFree: taxFilter || undefined,
        onlyAvailable: stockFilter === "AVAILABLE",
      }),
    });
    const j = await res.json();
    setItems(j.RESULTLIST ?? []);
    setLoading(false);
  }, [keyword, taxFilter, stockFilter]);

  // 검색조건 변경 시 즉시 자동 조회 (디바운스 250ms)
  useEffect(() => {
    const t = setTimeout(() => { fetchItems(); }, 250);
    return () => clearTimeout(t);
  }, [fetchItems]);

  // 카트에 택배전용 품목이 있는지
  const cartNeedsDelivery = useMemo(
    () => cart.some((c) => c.item.REQUIRES_DELIVERY === "Y"),
    [cart]
  );
  const hasDeliveryLine = extras.some((e) => e.kind === "DELIVERY");

  // 택배전용 품목이 카트에 들어왔는데 택배 라인이 없으면 자동 한 줄 추가
  useEffect(() => {
    if (cartNeedsDelivery && !hasDeliveryLine) {
      setExtras((prev) => [
        { id: newKey(), kind: "DELIVERY", unitPrice: DEFAULT_DELIVERY_PRICE, qty: 1, label: "택배비" },
        ...prev,
      ]);
    }
  }, [cartNeedsDelivery, hasDeliveryLine]);

  const addToCart = (item: Item) => addManyToCart(item, 1);

  const addManyToCart = (item: Item, qty: number) => {
    const stock = Number(item.STOCK_QTY);
    const maxQ = Number(item.MAX_ORDER_QTY ?? 0);
    const limit = unlimitedQty || maxQ <= 0 ? stock : Math.min(stock, maxQ);
    let toastTitle = "";
    let warned = false;
    setCart((c) => {
      const found = c.find((x) => x.item.OBJID === item.OBJID);
      const newQty = (found?.qty ?? 0) + qty;
      if (newQty > limit) {
        warned = true;
        return c;
      }
      toastTitle = found
        ? `수량 +${qty} → ${newQty}개`
        : `장바구니에 추가됨: ${item.ITEM_NAME} (${qty}개)`;
      if (found) return c.map((x) => x.item.OBJID === item.OBJID ? { ...x, qty: newQty } : x);
      return [...c, { item, qty }];
    });
    if (warned) {
      Swal.fire({
        icon: "warning",
        title: maxQ > 0 && stock > maxQ ? "1회 발주 한도 초과" : "재고 부족",
        text: `최대 ${fmt(limit)}개까지 담을 수 있습니다.`,
      });
      return;
    }
    Swal.fire({
      toast: true, position: "top-end", icon: "success",
      title: toastTitle,
      showConfirmButton: false, timer: 1000, timerProgressBar: true,
    });
  };

  const updateQty = (objid: string, delta: number) => {
    setCart((c) =>
      c.map((x) => {
        if (x.item.OBJID !== objid) return x;
        const newQty = x.qty + delta;
        if (newQty <= 0) return x;
        const stock = Number(x.item.STOCK_QTY);
        const maxQ = Number(x.item.MAX_ORDER_QTY ?? 0);
        const limit = unlimitedQty || maxQ <= 0 ? stock : Math.min(stock, maxQ);
        if (newQty > limit) return x;
        return { ...x, qty: newQty };
      })
    );
  };

  const setQty = (objid: string, value: number) => {
    setCart((c) =>
      c.map((x) => {
        if (x.item.OBJID !== objid) return x;
        const stock = Number(x.item.STOCK_QTY);
        const maxQ = Number(x.item.MAX_ORDER_QTY ?? 0);
        const limit = unlimitedQty || maxQ <= 0 ? stock : Math.min(stock, maxQ);
        const clamped = Math.max(1, Math.min(limit, Math.floor(value || 0)));
        return { ...x, qty: clamped };
      })
    );
  };

  const removeLine = (objid: string) => setCart((c) => c.filter((x) => x.item.OBJID !== objid));

  const addExtra = (kind: "DELIVERY" | "CHARTER") => {
    // 같은 종류 라인이 이미 있으면 새로 만들지 않고 수량 +1
    setExtras((p) => {
      const existing = p.find((e) => e.kind === kind);
      if (existing) {
        return p.map((e) => e.id === existing.id ? { ...e, qty: e.qty + 1 } : e);
      }
      const defaultPrice = kind === "DELIVERY" ? DEFAULT_DELIVERY_PRICE : DEFAULT_CHARTER_PRICE;
      return [...p, {
        id: newKey(), kind,
        unitPrice: defaultPrice, qty: 1,
        label: kind === "DELIVERY" ? "택배비" : "용차비",
      }];
    });
  };
  const updateExtra = (id: string, field: keyof ExtraLine, value: string | number) => {
    setExtras((p) => p.map((e) => (e.id === id ? { ...e, [field]: value } as ExtraLine : e)));
  };
  const removeExtra = (id: string) => {
    const target = extras.find((e) => e.id === id);
    if (target?.kind === "DELIVERY" && cartNeedsDelivery) {
      Swal.fire({ icon: "warning", title: "택배 전용 품목이 있어 택배 라인을 제거할 수 없습니다." });
      return;
    }
    setExtras((p) => p.filter((e) => e.id !== id));
  };

  const totals = useMemo(() => {
    let supply = 0, vat = 0, total = 0, taxFree = 0, taxable = 0, delivery = 0, charter = 0;
    for (const ln of cart) {
      const lineTotal = Math.round(Number(ln.item.UNIT_PRICE) * ln.qty);
      total += lineTotal;
      if (ln.item.IS_TAX_FREE === "Y") {
        supply += lineTotal;
        taxFree += lineTotal;
      } else {
        const s = Math.round(lineTotal / 1.1);
        supply += s;
        vat += lineTotal - s;
        taxable += s;
      }
    }
    for (const ex of extras) {
      const lineTotal = Math.round((Number(ex.unitPrice) || 0) * (Number(ex.qty) || 0));
      total += lineTotal;
      const s = Math.round(lineTotal / 1.1);
      supply += s;
      vat += lineTotal - s;
      taxable += s;
      if (ex.kind === "DELIVERY") delivery += lineTotal;
      if (ex.kind === "CHARTER")  charter  += lineTotal;
    }
    return { supply, vat, total, taxFree, taxable, delivery, charter };
  }, [cart, extras]);

  const submitOrder = async () => {
    if (cart.length === 0) {
      Swal.fire({ icon: "warning", title: "발주 품목을 추가하세요." });
      return;
    }
    if (cartNeedsDelivery && !hasDeliveryLine) {
      Swal.fire({ icon: "warning", title: "택배 전용 품목이 포함되어 택배 라인이 필요합니다." });
      return;
    }
    if (extras.some((e) => Number(e.unitPrice) <= 0 || Number(e.qty) <= 0)) {
      Swal.fire({ icon: "warning", title: "택배/용차 단가/수량을 입력하세요." });
      return;
    }
    const ok = await Swal.fire({
      icon: "question",
      title: "발주를 요청하시겠습니까?",
      text: `합계 ₩${fmt(totals.total)} (품목 ${cart.length}, 부가 ${extras.length})`,
      showCancelButton: true, confirmButtonText: "발주", cancelButtonText: "취소",
      confirmButtonColor: "#0f766e",
    });
    if (!ok.isConfirmed) return;

    const res = await fetch("/api/m/orders/save", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        lines: cart.map((c) => ({ itemObjid: c.item.OBJID, qty: c.qty })),
        extras: extras.map((e) => ({
          kind: e.kind,
          unitPrice: Number(e.unitPrice),
          qty: Number(e.qty),
          label: e.label,
        })),
      }),
    });
    const j = await res.json();
    if (j.success) {
      await Swal.fire({ icon: "success", title: "발주 요청 완료", text: `발주번호: ${j.orderNo}` });
      setCart([]); setExtras([]);
      router.push("/m/orders");
    } else {
      Swal.fire({ icon: "error", title: "오류", text: j.message });
    }
  };

  return (
    <div className="flex flex-col h-full overflow-hidden">
      {/* ===== 상단 sticky 카트 바 ===== */}
      <div className="sticky top-0 z-20 bg-white border-2 border-emerald-300 rounded-xl shadow-lg mb-3 overflow-hidden">
        <button
          onClick={() => setCartOpen((v) => !v)}
          className="w-full flex items-center justify-between gap-2 px-3 sm:px-4 py-2.5 hover:bg-emerald-50/40 transition"
        >
          <div className="flex items-center gap-2 font-bold text-slate-800 text-sm sm:text-base min-w-0">
            <ShoppingCart size={16} className="text-emerald-700 shrink-0" />
            <span className="truncate">발주 장바구니</span>
            <span className="shrink-0 px-2 py-0.5 rounded-full bg-emerald-100 text-emerald-700 text-[11px] font-bold tabular-nums">
              {cart.length + extras.length}
            </span>
          </div>
          <div className="flex items-center gap-2 shrink-0">
            <span className="hidden md:inline text-xs text-violet-700 tabular-nums">면세 ₩{fmt(totals.taxFree)}</span>
            <span className="hidden md:inline text-xs text-rose-700 tabular-nums">과세 ₩{fmt(totals.taxable)}</span>
            <span className="text-sm sm:text-base font-bold text-emerald-700 tabular-nums">₩{fmt(totals.total)}</span>
            <button
              onClick={(e) => { e.stopPropagation(); submitOrder(); }}
              disabled={cart.length === 0}
              className="h-8 sm:h-9 px-3 sm:px-4 rounded-lg bg-emerald-700 text-white text-xs sm:text-sm font-bold hover:bg-emerald-800 disabled:bg-slate-200 disabled:text-slate-400 disabled:cursor-not-allowed"
            >
              발주 요청
            </button>
            <span className={`text-slate-400 text-xs transition-transform ${cartOpen ? "rotate-180" : ""}`}>▼</span>
          </div>
        </button>

        {cartOpen && (
          <div className="border-t border-emerald-100 px-3 sm:px-4 py-3 max-h-[55vh] overflow-y-auto bg-slate-50/50 space-y-3">
            {/* 택배/용차 추가 버튼 */}
            <div className="flex flex-wrap gap-2 items-center justify-between">
              <div className="flex gap-2 flex-wrap">
                <button
                  type="button"
                  onClick={() => addExtra("DELIVERY")}
                  className="inline-flex items-center gap-1 h-8 px-3 rounded-md bg-orange-100 text-orange-700 text-xs font-bold hover:bg-orange-200"
                >
                  <Truck size={13} /> + 택배 추가
                </button>
                <button
                  type="button"
                  onClick={() => addExtra("CHARTER")}
                  className="inline-flex items-center gap-1 h-8 px-3 rounded-md bg-sky-100 text-sky-700 text-xs font-bold hover:bg-sky-200"
                >
                  <Package size={13} /> + 용차 추가
                </button>
              </div>
              {(cart.length > 0 || extras.length > 0) && (
                <button
                  onClick={() => { setCart([]); setExtras([]); }}
                  className="text-xs text-slate-400 hover:text-rose-500"
                >
                  전체 삭제
                </button>
              )}
            </div>

            {/* 택배/용차 라인 */}
            {extras.length > 0 && (
              <div className="space-y-1.5">
                {extras.map((ex) => {
                  const lineTotal = Math.round((Number(ex.unitPrice) || 0) * (Number(ex.qty) || 0));
                  return (
                    <div
                      key={ex.id}
                      className={`flex flex-wrap items-center gap-2 p-2 rounded-lg border ${ex.kind === "DELIVERY" ? "bg-orange-50/60 border-orange-200" : "bg-sky-50/60 border-sky-200"}`}
                    >
                      <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded shrink-0 ${ex.kind === "DELIVERY" ? "bg-orange-200 text-orange-800" : "bg-sky-200 text-sky-800"}`}>
                        {ex.kind === "DELIVERY" ? "택배" : "용차"}
                      </span>
                      <input
                        value={ex.label}
                        onChange={(e) => updateExtra(ex.id, "label", e.target.value)}
                        placeholder="담당자/메모"
                        className="flex-1 min-w-[120px] h-8 px-2 rounded border border-slate-200 text-xs bg-white"
                      />
                      <div className="flex items-center gap-1 shrink-0">
                        <input
                          type="number"
                          min={0}
                          value={ex.unitPrice || ""}
                          onChange={(e) => updateExtra(ex.id, "unitPrice", Number(e.target.value))}
                          placeholder="단가"
                          className="w-20 sm:w-24 h-8 px-2 rounded border border-slate-200 text-xs text-right tabular-nums bg-white"
                        />
                        <span className="text-slate-400 text-xs">×</span>
                        <input
                          type="number"
                          min={1}
                          value={ex.qty || ""}
                          onChange={(e) => updateExtra(ex.id, "qty", Number(e.target.value))}
                          placeholder="수량"
                          className="w-14 sm:w-16 h-8 px-2 rounded border border-slate-200 text-xs text-right tabular-nums bg-white"
                        />
                        <span className="text-slate-400 text-xs">=</span>
                        <span className="w-20 sm:w-24 h-8 px-2 inline-flex items-center justify-end text-xs font-bold tabular-nums bg-white border border-slate-100 rounded">
                          ₩{fmt(lineTotal)}
                        </span>
                      </div>
                      <button
                        onClick={() => removeExtra(ex.id)}
                        className="text-slate-300 hover:text-rose-500 shrink-0"
                        title="삭제"
                      >
                        <X size={14} />
                      </button>
                    </div>
                  );
                })}
              </div>
            )}

            {/* 품목 라인 */}
            {cart.length === 0 && extras.length === 0 ? (
              <div className="text-slate-400 text-sm text-center py-6">
                아래 품목 카드의 <span className="font-bold text-emerald-700">+ 담기</span> 버튼으로 추가하세요.
              </div>
            ) : cart.length > 0 && (
              <div className="grid sm:grid-cols-2 gap-2">
                {cart.map((ln) => {
                  const lineTotal = Math.round(Number(ln.item.UNIT_PRICE) * ln.qty);
                  return (
                    <div key={ln.item.OBJID} className="bg-white border border-slate-100 rounded-lg p-2.5">
                      <div className="flex items-start justify-between gap-2 mb-2">
                        <div className="text-sm font-semibold leading-tight min-w-0">
                          <div className="truncate">{ln.item.ITEM_NAME}</div>
                          {ln.item.REQUIRES_DELIVERY === "Y" && (
                            <span className="inline-block mt-0.5 text-[9px] px-1.5 py-0.5 rounded bg-orange-100 text-orange-700 font-bold">택배전용</span>
                          )}
                        </div>
                        <button onClick={() => removeLine(ln.item.OBJID)} className="text-slate-300 hover:text-rose-500 shrink-0">
                          <X size={14} />
                        </button>
                      </div>
                      <div className="flex items-center justify-between gap-2">
                        <div className="flex items-center gap-1">
                          <button onClick={() => updateQty(ln.item.OBJID, -1)} className="w-7 h-7 rounded-md bg-slate-100 hover:bg-slate-200 flex items-center justify-center">
                            <Minus size={12} />
                          </button>
                          <input
                            type="number"
                            min={1}
                            value={ln.qty}
                            onChange={(e) => setQty(ln.item.OBJID, Number(e.target.value))}
                            className="w-12 h-7 text-center text-sm font-bold tabular-nums border border-slate-200 rounded"
                          />
                          <button onClick={() => updateQty(ln.item.OBJID, 1)} className="w-7 h-7 rounded-md bg-slate-100 hover:bg-slate-200 flex items-center justify-center">
                            <Plus size={12} />
                          </button>
                        </div>
                        <div className="text-sm font-bold tabular-nums">₩{fmt(lineTotal)}</div>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}

            <div className="border-t border-slate-200 pt-2 grid grid-cols-2 sm:grid-cols-4 gap-2 text-xs">
              <Row label="면세 합계" value={`₩${fmt(totals.taxFree)}`} color="violet" />
              <Row label="과세 공급가" value={`₩${fmt(totals.taxable)}`} color="rose" />
              <Row label="세액" value={`₩${fmt(totals.vat)}`} />
              <Row label="총 합계" value={`₩${fmt(totals.total)}`} />
              {totals.delivery > 0 && <Row label="택배비" value={`₩${fmt(totals.delivery)}`} color="orange" />}
              {totals.charter > 0 && <Row label="용차비" value={`₩${fmt(totals.charter)}`} color="sky" />}
            </div>
          </div>
        )}
      </div>

      <div className="flex-1 space-y-4 overflow-y-auto pr-1">
        <div>
          <h1 className="text-xl sm:text-2xl font-bold text-slate-900">출고 요청</h1>
          <p className="text-slate-500 text-xs sm:text-sm mt-1">현재 재고가 있는 품목을 선택해 상단 장바구니에 담고 [발주 요청] 버튼으로 전송하세요.</p>
        </div>

        <div className="flex gap-2 items-center flex-wrap">
          <div className="relative flex-1 min-w-[160px]">
            <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
            <input
              value={keyword}
              onChange={(e) => setKeyword(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && fetchItems()}
              placeholder="품목명 또는 품목코드"
              className="w-full h-10 pl-9 pr-3 rounded-lg border border-slate-200 text-sm focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500/15 outline-none"
            />
          </div>
          <select value={taxFilter} onChange={(e) => setTaxFilter(e.target.value as "" | "Y" | "N")} className="h-10 px-2 sm:px-3 rounded-lg border border-slate-200 text-sm">
            <option value="">전체</option>
            <option value="Y">면세</option>
            <option value="N">과세</option>
          </select>
          <select value={stockFilter} onChange={(e) => setStockFilter(e.target.value as "AVAILABLE" | "ALL")} className="h-10 px-2 sm:px-3 rounded-lg border border-slate-200 text-sm">
            <option value="AVAILABLE">재고있는 품목만</option>
            <option value="ALL">전체 품목</option>
          </select>
          {/* 보기 모드 토글 */}
          <div className="flex items-center bg-slate-100 rounded-lg p-0.5 ml-auto">
            <button
              onClick={() => setViewMode("card")}
              title="카드 보기"
              className={`h-9 px-2.5 rounded-md text-xs font-bold inline-flex items-center gap-1 ${viewMode === "card" ? "bg-white text-emerald-700 shadow" : "text-slate-500"}`}
            >
              <LayoutGrid size={14} /> 카드
            </button>
            <button
              onClick={() => setViewMode("list")}
              title="리스트 보기"
              className={`h-9 px-2.5 rounded-md text-xs font-bold inline-flex items-center gap-1 ${viewMode === "list" ? "bg-white text-emerald-700 shadow" : "text-slate-500"}`}
            >
              <ListIcon size={14} /> 리스트
            </button>
          </div>
        </div>

        {loading ? (
          <div className="text-slate-400 text-center py-12">불러오는 중...</div>
        ) : items.length === 0 ? (
          <div className="text-slate-400 text-center py-12 bg-white rounded-xl border border-slate-100">검색 결과가 없습니다.</div>
        ) : viewMode === "list" ? (
          <ListView
            items={items}
            cart={cart}
            unlimitedQty={unlimitedQty}
            onAdd={addManyToCart}
            onPlus={(o) => updateQty(o, 1)}
            onMinus={(o) => updateQty(o, -1)}
            onSetQty={setQty}
            onRemove={removeLine}
          />
        ) : (
          <div className="grid grid-cols-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-2">
            {items.map((it) => {
              const cartLine = cart.find((x) => x.item.OBJID === it.OBJID);
              const inCart = cartLine?.qty ?? 0;
              const stock = Number(it.STOCK_QTY);
              const maxQ = Number(it.MAX_ORDER_QTY ?? 0);
              const limit = unlimitedQty || maxQ <= 0 ? stock : Math.min(stock, maxQ);
              const soldOut = stock === 0;
              return (
                <div key={it.OBJID} className={`bg-white border rounded-lg p-2 transition ${inCart > 0 ? "border-emerald-400 ring-2 ring-emerald-100" : "border-slate-200 hover:shadow-md"}`}>
                  <div className="aspect-square bg-slate-50 rounded mb-1.5 overflow-hidden flex items-center justify-center relative">
                    {it.IMAGE_URL ? (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img src={it.IMAGE_URL} alt={it.ITEM_NAME} className="w-full h-full object-cover" />
                    ) : (
                      <div className="text-slate-300 text-[10px]">이미지 없음</div>
                    )}
                    {inCart > 0 && (
                      <span className="absolute top-0.5 right-0.5 bg-emerald-600 text-white text-[9px] font-bold px-1 py-0.5 rounded-full">
                        {inCart}
                      </span>
                    )}
                    <div className="absolute top-0.5 left-0.5 flex flex-col gap-0.5">
                      {it.IS_TAX_FREE === "Y" && (
                        <span className="px-1 py-0.5 rounded bg-violet-500/90 text-white text-[9px] font-bold">면세</span>
                      )}
                      {it.REQUIRES_DELIVERY === "Y" && (
                        <span className="px-1 py-0.5 rounded bg-orange-500/90 text-white text-[9px] font-bold">택배</span>
                      )}
                    </div>
                  </div>
                  <div className="font-bold text-[11px] sm:text-xs text-slate-900 leading-tight mb-0.5 line-clamp-2 min-h-[2em]">{it.ITEM_NAME}</div>
                  <div className="flex items-baseline justify-between mb-1 gap-1">
                    <div className="font-bold text-slate-900 tabular-nums text-xs sm:text-sm">₩{fmt(it.UNIT_PRICE)}</div>
                    <div className={`text-[10px] font-semibold tabular-nums shrink-0 ${stock > 0 ? "text-emerald-700" : "text-rose-500"}`}>
                      {fmt(stock)}{it.UNIT}
                    </div>
                  </div>
                  {maxQ > 0 && !unlimitedQty && (
                    <div className="text-[9px] text-sky-700 mb-0.5">한도 ≤ {fmt(maxQ)}</div>
                  )}

                  {/* 수량 컨트롤 — 카드 안에서 바로 조절 */}
                  {soldOut ? (
                    <div className="w-full mt-1 h-7 rounded bg-slate-100 text-slate-400 text-[11px] font-bold flex items-center justify-center">
                      품절
                    </div>
                  ) : inCart === 0 ? (
                    <div className="flex gap-1 mt-1">
                      <input
                        type="number"
                        min={1}
                        max={limit}
                        defaultValue={1}
                        onClick={(e) => (e.target as HTMLInputElement).select()}
                        onKeyDown={(e) => {
                          if (e.key === "Enter") {
                            const val = Number((e.target as HTMLInputElement).value) || 1;
                            const q = Math.max(1, Math.min(limit, val));
                            addManyToCart(it, q);
                            (e.target as HTMLInputElement).value = "1";
                          }
                        }}
                        id={`qty-${it.OBJID}`}
                        className="w-9 h-7 px-1 rounded border border-slate-200 text-center text-[11px] tabular-nums focus:border-emerald-500 outline-none"
                      />
                      <button
                        onClick={() => {
                          const el = document.getElementById(`qty-${it.OBJID}`) as HTMLInputElement | null;
                          const val = el ? Number(el.value) || 1 : 1;
                          const q = Math.max(1, Math.min(limit, val));
                          addManyToCart(it, q);
                          if (el) el.value = "1";
                        }}
                        className="flex-1 h-7 rounded bg-emerald-700 text-white text-[11px] font-bold hover:bg-emerald-800 flex items-center justify-center gap-0.5"
                      >
                        <Plus size={11} /> 담기
                      </button>
                    </div>
                  ) : (
                    <div className="flex items-center gap-0.5 mt-1 bg-emerald-50 border border-emerald-200 rounded p-0.5">
                      <button onClick={() => updateQty(it.OBJID, -1)}
                        className="w-6 h-6 rounded bg-white border border-emerald-200 hover:bg-emerald-100 flex items-center justify-center shrink-0">
                        <Minus size={11} />
                      </button>
                      <input
                        type="number"
                        min={1}
                        max={limit}
                        value={inCart}
                        onChange={(e) => setQty(it.OBJID, Number(e.target.value))}
                        className="w-full min-w-0 h-6 text-center font-bold text-[11px] tabular-nums bg-white border border-emerald-200 rounded"
                      />
                      <button onClick={() => updateQty(it.OBJID, 1)}
                        className="w-6 h-6 rounded bg-white border border-emerald-200 hover:bg-emerald-100 flex items-center justify-center shrink-0">
                        <Plus size={11} />
                      </button>
                      <button onClick={() => removeLine(it.OBJID)}
                        title="빼기"
                        className="w-6 h-6 rounded bg-white border border-rose-200 hover:bg-rose-100 text-rose-500 flex items-center justify-center shrink-0">
                        <X size={11} />
                      </button>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

function Row({ label, value, color }: { label: string; value: string; color?: "violet" | "rose" | "orange" | "sky" }) {
  const cls = color === "violet" ? "text-violet-700"
            : color === "rose"   ? "text-rose-700"
            : color === "orange" ? "text-orange-700"
            : color === "sky"    ? "text-sky-700"
            : "text-slate-700";
  return (
    <div className="flex justify-between">
      <span className={cls}>{label}</span>
      <span className="tabular-nums">{value}</span>
    </div>
  );
}

function ListView({ items, cart, unlimitedQty, onAdd, onPlus, onMinus, onSetQty, onRemove }: {
  items: Item[]; cart: CartLine[]; unlimitedQty: boolean;
  onAdd: (it: Item, qty: number) => void;
  onPlus: (o: string) => void;
  onMinus: (o: string) => void;
  onSetQty: (o: string, v: number) => void;
  onRemove: (o: string) => void;
}) {
  return (
    <div className="bg-white border border-slate-200 rounded-xl overflow-hidden">
      <div className="overflow-x-hidden">
        <table className="w-full text-[12px] table-fixed">
          <thead className="bg-slate-50 text-slate-600 text-[10px]">
            <tr>
              <th className="text-left px-2 py-2">품목</th>
              <th className="text-center px-1 py-2 w-10">구분</th>
              <th className="text-right px-1 py-2 w-[68px]">단가</th>
              <th className="text-right px-1 py-2 w-12">재고</th>
              <th className="text-center px-1 py-2 w-[112px]">수량</th>
            </tr>
          </thead>
          <tbody>
            {items.map((it) => {
              const cartLine = cart.find((x) => x.item.OBJID === it.OBJID);
              const inCart = cartLine?.qty ?? 0;
              const stock = Number(it.STOCK_QTY);
              const maxQ = Number(it.MAX_ORDER_QTY ?? 0);
              const limit = unlimitedQty || maxQ <= 0 ? stock : Math.min(stock, maxQ);
              const soldOut = stock === 0;
              return (
                <tr key={it.OBJID} className={`border-t border-slate-100 ${inCart > 0 ? "bg-emerald-50/40" : "hover:bg-slate-50"}`}>
                  <td className="px-2 py-2 overflow-hidden">
                    <div className="font-semibold truncate text-[12px]">
                      {it.ITEM_NAME}
                      {it.REQUIRES_DELIVERY === "Y" && <span className="ml-1 px-1 py-0.5 rounded bg-orange-100 text-orange-700 text-[9px] font-bold">택배</span>}
                    </div>
                    {inCart > 0 && <div className="text-[10px] text-emerald-700 font-bold">담은 {inCart}</div>}
                  </td>
                  <td className="px-1 py-2 text-center">
                    <span className={`text-[9px] px-1 py-0.5 rounded font-bold ${it.IS_TAX_FREE === "Y" ? "bg-violet-100 text-violet-700" : "bg-rose-100 text-rose-700"}`}>
                      {it.IS_TAX_FREE === "Y" ? "면세" : "과세"}
                    </span>
                  </td>
                  <td className="px-1 py-2 text-right tabular-nums font-bold text-[11px]">₩{Number(it.UNIT_PRICE).toLocaleString("ko-KR")}</td>
                  <td className={`px-1 py-2 text-right tabular-nums text-[11px] ${stock <= 0 ? "text-rose-500 font-bold" : "text-slate-700"}`}>{Number(stock).toLocaleString("ko-KR")}</td>
                  <td className="px-1 py-2">
                    {soldOut ? (
                      <div className="text-center text-[10px] text-slate-400">품절</div>
                    ) : inCart === 0 ? (
                      <div className="flex gap-0.5 justify-end">
                        <input
                          type="number"
                          min={1}
                          max={limit}
                          defaultValue={1}
                          onClick={(e) => (e.target as HTMLInputElement).select()}
                          onKeyDown={(e) => {
                            if (e.key === "Enter") {
                              const v = Number((e.target as HTMLInputElement).value) || 1;
                              onAdd(it, Math.max(1, Math.min(limit, v)));
                              (e.target as HTMLInputElement).value = "1";
                            }
                          }}
                          id={`lqty-${it.OBJID}`}
                          className="w-12 h-7 px-1 rounded border border-slate-200 text-center text-[11px] tabular-nums"
                        />
                        <button onClick={() => {
                          const el = document.getElementById(`lqty-${it.OBJID}`) as HTMLInputElement | null;
                          const v = el ? Number(el.value) || 1 : 1;
                          onAdd(it, Math.max(1, Math.min(limit, v)));
                          if (el) el.value = "1";
                        }} className="h-7 w-9 rounded bg-emerald-700 text-white font-bold hover:bg-emerald-800 inline-flex items-center justify-center" title="담기">
                          <Plus size={14} />
                        </button>
                      </div>
                    ) : (
                      <div className="flex items-center gap-0.5 justify-end">
                        <button onClick={() => onMinus(it.OBJID)} className="w-7 h-7 rounded bg-white border border-emerald-200 hover:bg-emerald-100 flex items-center justify-center"><Minus size={11} /></button>
                        <input type="number" min={1} max={limit} value={inCart}
                          onChange={(e) => onSetQty(it.OBJID, Number(e.target.value))}
                          className="w-10 h-7 text-center font-bold text-[11px] tabular-nums border border-emerald-200 rounded" />
                        <button onClick={() => onPlus(it.OBJID)} className="w-7 h-7 rounded bg-white border border-emerald-200 hover:bg-emerald-100 flex items-center justify-center"><Plus size={11} /></button>
                        <button onClick={() => onRemove(it.OBJID)} title="빼기" className="w-7 h-7 rounded bg-white border border-rose-200 hover:bg-rose-100 text-rose-500 flex items-center justify-center"><X size={11} /></button>
                      </div>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}
