;; Shared order components — used by both cart and orders services
;;
;; Order table (list view), order detail panels, and checkout error screens.

;; ---------------------------------------------------------------------------
;; Order table rows
;; ---------------------------------------------------------------------------

(defcomp ~shared:orders/row-desktop (&key (oid :as string) (created :as string) (desc :as string) (total :as string)
                                   (pill :as string) (status :as string) (url :as string))
  (tr :class "hidden sm:table-row border-t border-stone-100 hover:bg-stone-50/60"
    (td :class "px-3 py-2 align-top" (span :class "font-mono text-[11px] sm:text-xs" oid))
    (td :class "px-3 py-2 align-top text-stone-700 text-xs sm:text-sm" created)
    (td :class "px-3 py-2 align-top text-stone-700 text-xs sm:text-sm" desc)
    (td :class "px-3 py-2 align-top text-stone-700 text-xs sm:text-sm" total)
    (td :class "px-3 py-2 align-top" (span :class pill status))
    (td :class "px-3 py-0.5 align-top text-right"
      (a :href url :class "inline-flex items-center px-3 py-1.5 text-xs sm:text-sm rounded-full border border-stone-300 bg-white hover:bg-stone-50 transition" "View"))))

(defcomp ~shared:orders/row-mobile (&key (oid :as string) (created :as string) (total :as string)
                                  (pill :as string) (status :as string) (url :as string))
  (tr :class "sm:hidden border-t border-stone-100"
    (td :colspan "5" :class "px-3 py-3"
      (div :class "flex flex-col gap-2 text-xs"
        (div :class "flex items-center justify-between gap-2"
          (span :class "font-mono text-[11px] text-stone-700" oid)
          (span :class pill status))
        (div :class "text-[11px] text-stone-500 break-words" created)
        (div :class "flex items-center justify-between gap-2"
          (div :class "font-medium text-stone-800" total)
          (a :href url :class "inline-flex items-center px-2 py-1 text-[11px] rounded-full border border-stone-300 bg-white hover:bg-stone-50 transition shrink-0" "View"))))))

(defcomp ~shared:orders/end-row ()
  (tr (td :colspan "5" :class "px-3 py-4 text-center text-xs text-stone-400"
    (~shared:misc/end-of-results :cls "text-center text-xs text-stone-400"))))

(defcomp ~shared:orders/empty-state ()
  (div :class "max-w-full px-3 py-3 space-y-3"
    (div :class "rounded-2xl border border-dashed border-stone-300 bg-white/80 p-4 sm:p-6 text-sm text-stone-700"
      "No orders yet.")))

(defcomp ~shared:orders/table (&key rows)
  (div :class "max-w-full px-3 py-3 space-y-3"
    (div :class "overflow-x-auto rounded-2xl border border-stone-200 bg-white/80"
      (table :class "min-w-full text-xs sm:text-sm"
        (thead :class "bg-stone-50 border-b border-stone-200 text-stone-600"
          (tr
            (th :class "px-3 py-2 text-left font-medium" "Order")
            (th :class "px-3 py-2 text-left font-medium" "Created")
            (th :class "px-3 py-2 text-left font-medium" "Description")
            (th :class "px-3 py-2 text-left font-medium" "Total")
            (th :class "px-3 py-2 text-left font-medium" "Status")
            (th :class "px-3 py-2 text-left font-medium" "")))
        (tbody rows)))))

(defcomp ~shared:orders/list-header (&key search-mobile)
  (header :class "mb-6 sm:mb-8 flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4"
    (div :class "space-y-1"
      (p :class "text-xs sm:text-sm text-stone-600" "Recent orders placed via the checkout."))
    (div :class "md:hidden" search-mobile)))

;; ---------------------------------------------------------------------------
;; Order detail panels
;; ---------------------------------------------------------------------------

(defcomp ~shared:orders/item-image (&key (src :as string) (alt :as string))
  (img :src src :alt alt :class "w-full h-full object-contain object-center" :loading "lazy" :decoding "async"))

(defcomp ~shared:orders/item-no-image ()
  (div :class "w-full h-full flex items-center justify-center text-[9px] text-stone-400" "No image"))

(defcomp ~shared:orders/item-row (&key (href :as string) img (title :as string) (pid :as string)
                                (qty :as string) (price :as string))
  (li (a :class "w-full py-2 flex gap-3" :href href
    (div :class "w-12 h-12 sm:w-14 sm:h-14 rounded-md bg-stone-100 flex-shrink-0 overflow-hidden" img)
    (div :class "flex-1 flex justify-between gap-3"
      (div
        (p :class "font-medium" title)
        (p :class "text-[11px] text-stone-500" pid))
      (div :class "text-right whitespace-nowrap"
        (p qty)
        (p price))))))

(defcomp ~shared:orders/items-panel (&key items)
  (div :class "rounded-2xl border border-stone-200 bg-white/80 p-4 sm:p-6"
    (h2 :class "text-sm sm:text-base font-semibold mb-3" "Items")
    (ul :class "divide-y divide-stone-100 text-xs sm:text-sm" items)))

(defcomp ~shared:orders/calendar-entry (&key (name :as string) (pill :as string) (status :as string)
                                      (date-str :as string) (cost :as string))
  (li :class "px-4 py-3 flex items-start justify-between text-sm"
    (div (div :class "font-medium flex items-center gap-2"
      name (span :class pill status))
      (div :class "text-xs text-stone-500" date-str))
    (div :class "ml-4 font-medium" cost)))

(defcomp ~shared:orders/calendar-section (&key items)
  (section :class "mt-6 space-y-3"
    (h2 :class "text-base sm:text-lg font-semibold" "Calendar bookings in this order")
    (ul :class "divide-y divide-stone-200 rounded-2xl border border-stone-200 bg-white/80" items)))

(defcomp ~shared:orders/detail-panel (&key summary items calendar)
  (div :class "max-w-full px-3 py-3 space-y-4" summary items calendar))

(defcomp ~shared:orders/pay-btn (&key (url :as string))
  (a :href url :class "inline-flex items-center px-3 py-2 text-xs sm:text-sm rounded-full border border-emerald-600 bg-emerald-600 text-white hover:bg-emerald-700 transition"
    (i :class "fa fa-credit-card mr-2" :aria-hidden "true") "Open payment page"))

(defcomp ~shared:orders/detail-filter (&key (info :as string) (list-url :as string) (recheck-url :as string)
                                     (csrf :as string) pay)
  (header :class "mb-6 sm:mb-8 flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4"
    (div :class "space-y-1"
      (p :class "text-xs sm:text-sm text-stone-600" info))
    (div :class "flex w-full sm:w-auto justify-start sm:justify-end gap-2"
      (a :href list-url :class "inline-flex items-center px-3 py-2 text-xs sm:text-sm rounded-full border border-stone-300 bg-white hover:bg-stone-50 transition"
        (i :class "fa-solid fa-list mr-2" :aria-hidden "true") "All orders")
      (form :method "post" :action recheck-url :class "inline"
        (input :type "hidden" :name "csrf_token" :value csrf)
        (button :type "submit" :class "inline-flex items-center px-3 py-2 text-xs sm:text-sm rounded-full border border-stone-300 bg-white hover:bg-stone-50 transition"
          (i :class "fa-solid fa-rotate mr-2" :aria-hidden "true") "Re-check status"))
      pay)))

(defcomp ~shared:orders/detail-header-stack (&key auth orders order)
  (~shared:layout/header-child-sx :inner
    (<> auth (~shared:layout/header-child-sx :id "auth-header-child" :inner
      (<> orders (~shared:layout/header-child-sx :id "orders-header-child" :inner order))))))

;; ---------------------------------------------------------------------------
;; Data-driven order rows (replaces Python loop)
;; ---------------------------------------------------------------------------

(defcomp ~shared:orders/rows-from-data (&key (orders :as list?) (page :as number) (total-pages :as number)
                                      (next-url :as string?))
  (<>
    (map (lambda (o)
      (<>
        (~shared:orders/row-desktop :oid (get o "oid") :created (get o "created")
          :desc (get o "desc") :total (get o "total")
          :pill (get o "pill_desktop") :status (get o "status") :url (get o "url"))
        (~shared:orders/row-mobile :oid (get o "oid") :created (get o "created")
          :total (get o "total") :pill (get o "pill_mobile")
          :status (get o "status") :url (get o "url"))))
      (or orders (list)))
    (if next-url
      (~shared:controls/infinite-scroll :url next-url :page page :total-pages total-pages
        :id-prefix "orders" :colspan 5)
      (~shared:orders/end-row))))

;; ---------------------------------------------------------------------------
;; Data-driven order items (replaces Python loop)
;; ---------------------------------------------------------------------------

(defcomp ~shared:orders/items-from-data (&key (items :as list?))
  (~shared:orders/items-panel
    :items (<> (map (lambda (item)
      (let* ((img (if (get item "product_image")
                   (~shared:orders/item-image :src (get item "product_image") :alt (or (get item "product_title") "Product image"))
                   (~shared:orders/item-no-image))))
        (~shared:orders/item-row
          :href (get item "href") :img img
          :title (or (get item "product_title") "Unknown product")
          :pid (str "Product ID: " (get item "product_id"))
          :qty (str "Qty: " (get item "quantity"))
          :price (get item "price"))))
      (or items (list))))))

;; ---------------------------------------------------------------------------
;; Data-driven calendar entries (replaces Python loop)
;; ---------------------------------------------------------------------------

(defcomp ~shared:orders/calendar-from-data (&key (entries :as list?))
  (~shared:orders/calendar-section
    :items (<> (map (lambda (e)
      (~shared:orders/calendar-entry
        :name (get e "name") :pill (get e "pill")
        :status (get e "status") :date-str (get e "date_str")
        :cost (get e "cost")))
      (or entries (list))))))

;; ---------------------------------------------------------------------------
;; Checkout error screens
;; ---------------------------------------------------------------------------

;; ---------------------------------------------------------------------------
;; Assembled order list content — replaces Python _orders_rows_sx / _orders_main_panel_sx
;; ---------------------------------------------------------------------------

;; Status pill class mapping
(defcomp ~shared:orders/status-pill-cls (&key (status :as string?))
  (let* ((sl (lower (or status ""))))
    (cond
      ((= sl "paid") "border-emerald-300 bg-emerald-50 text-emerald-700")
      ((or (= sl "failed") (= sl "cancelled")) "border-rose-300 bg-rose-50 text-rose-700")
      (true "border-stone-300 bg-stone-50 text-stone-700"))))

;; Single order row pair (desktop + mobile) — takes serialized order data dict
(defcomp ~shared:orders/row-pair (&key (order :as dict) (detail-url-prefix :as string))
  (let* ((status (or (get order "status") "pending"))
         (pill-base (~shared:orders/status-pill-cls :status status))
         (oid (str "#" (get order "id")))
         (created (or (get order "created_at_formatted") "\u2014"))
         (desc (or (get order "description") ""))
         (total (str (or (get order "currency") "GBP") " " (or (get order "total_formatted") "0.00")))
         (url (str detail-url-prefix (get order "id") "/")))
    (<>
      (~shared:orders/row-desktop
        :oid oid :created created :desc desc :total total
        :pill (str "inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] sm:text-xs " pill-base)
        :status status :url url)
      (~shared:orders/row-mobile
        :oid oid :created created :total total
        :pill (str "inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] " pill-base)
        :status status :url url))))

;; Assembled orders list content
(defcomp ~shared:orders/list-content (&key (orders :as list) (page :as number) (total-pages :as number)
                                     (rows-url :as string) (detail-url-prefix :as string))
  (if (empty? orders)
    (~shared:orders/empty-state)
    (~shared:orders/table
      :rows (<>
        (map (lambda (order)
          (~shared:orders/row-pair :order order :detail-url-prefix detail-url-prefix))
          orders)
        (if (< page total-pages)
          (~shared:controls/infinite-scroll
            :url (str rows-url "?page=" (inc page))
            :page page :total-pages total-pages
            :id-prefix "orders" :colspan 5)
          (~shared:orders/end-row))))))

;; Assembled order detail content — replaces Python _order_main_sx
(defcomp ~shared:orders/detail-content (&key (order :as dict) (calendar-entries :as list?))
  (let* ((items (get order "items")))
    (~shared:orders/detail-panel
      :summary (~shared:cards/order-summary-card
        :order-id (get order "id")
        :created-at (get order "created_at_formatted")
        :description (get order "description")
        :status (get order "status")
        :currency (get order "currency")
        :total-amount (get order "total_formatted"))
      :items (when (not (empty? (or items (list))))
        (~shared:orders/items-panel
          :items (map (lambda (item)
            (~shared:orders/item-row
              :href (get item "product_url")
              :img (if (get item "product_image")
                     (~shared:orders/item-image :src (get item "product_image")
                                        :alt (or (get item "product_title") "Product image"))
                     (~shared:orders/item-no-image))
              :title (or (get item "product_title") "Unknown product")
              :pid (str "Product ID: " (get item "product_id"))
              :qty (str "Qty: " (get item "quantity"))
              :price (str (or (get item "currency") (get order "currency") "GBP") " " (or (get item "unit_price_formatted") "0.00"))))
            items)))
      :calendar (when (not (empty? (or calendar-entries (list))))
        (~shared:orders/calendar-section
          :items (map (lambda (e)
            (let* ((st (or (get e "state") ""))
                   (pill (cond
                     ((= st "confirmed") "bg-emerald-100 text-emerald-800")
                     ((= st "provisional") "bg-amber-100 text-amber-800")
                     ((= st "ordered") "bg-blue-100 text-blue-800")
                     (true "bg-stone-100 text-stone-700"))))
              (~shared:orders/calendar-entry
                :name (get e "name")
                :pill (str "inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium " pill)
                :status (upper (slice st 0 1))
                :date-str (get e "date_str")
                :cost (str "\u00a3" (or (get e "cost_formatted") "0.00")))))
            calendar-entries))))))

;; Assembled order detail filter — replaces Python _order_filter_sx
(defcomp ~shared:orders/detail-filter-content (&key (order :as dict) (list-url :as string) (recheck-url :as string)
                                            (pay-url :as string) (csrf :as string))
  (let* ((status (or (get order "status") "pending"))
         (created (or (get order "created_at_formatted") "\u2014")))
    (~shared:orders/detail-filter
      :info (str "Placed " created " \u00b7 Status: " status)
      :list-url list-url
      :recheck-url recheck-url
      :csrf csrf
      :pay (when (!= status "paid")
             (~shared:orders/pay-btn :url pay-url)))))

;; ---------------------------------------------------------------------------
;; Checkout return components
;; ---------------------------------------------------------------------------

(defcomp ~shared:orders/checkout-return-header (&key (status :as string))
  (header :class "mb-6 sm:mb-8"
    (h1 :class "text-xl sm:text-2xl md:text-3xl font-semibold tracking-tight" "Payment complete")
    (p :class "text-xs sm:text-sm text-stone-600"
      (str "Your checkout session is " status "."))))

(defcomp ~shared:orders/checkout-return-missing ()
  (div :class "max-w-full px-3 py-3 space-y-4"
    (p :class "text-sm text-stone-600" "Order not found.")))

(defcomp ~shared:orders/checkout-return-ticket (&key (name :as string) (pill :as string) (state :as string)
                                       (type-name :as string?) (date-str :as string) (code :as string?)
                                       (price :as string))
  (li :class "px-4 py-3 flex items-start justify-between text-sm"
    (div
      (div :class "font-medium flex items-center gap-2"
        name (span :class pill state))
      (when type-name (div :class "text-xs text-stone-500" type-name))
      (div :class "text-xs text-stone-500" date-str)
      (when code (div :class "font-mono text-xs text-stone-400" code)))
    (div :class "ml-4 font-medium" price)))

(defcomp ~shared:orders/checkout-return-tickets (&key items)
  (section :class "mt-6 space-y-3"
    (h2 :class "text-base sm:text-lg font-semibold" "Tickets")
    (ul :class "divide-y divide-stone-200 rounded-2xl border border-stone-200 bg-white/80" items)))

(defcomp ~shared:orders/checkout-return-failed (&key (order-id :as string?))
  (div :class "rounded-lg border border-rose-200 bg-rose-50 p-4 text-sm text-rose-900"
    (p :class "font-medium" "Payment failed")
    (p "Please try again or contact support."
       (when order-id (span " Order #" (str order-id))))))

(defcomp ~shared:orders/checkout-return-paid ()
  (div :class "rounded-lg border border-emerald-200 bg-emerald-50 p-4 text-sm text-emerald-900"
    (p :class "font-medium" "Payment successful!")
    (p "Your order has been confirmed.")))

(defcomp ~shared:orders/checkout-return-content (&key summary items calendar tickets status-message)
  (div :class "max-w-full px-3 py-3 space-y-4"
    status-message summary items calendar tickets))

;; ---------------------------------------------------------------------------
;; Checkout error screens
;; ---------------------------------------------------------------------------

(defcomp ~shared:orders/checkout-error-header ()
  (header :class "mb-6 sm:mb-8"
    (h1 :class "text-xl sm:text-2xl md:text-3xl font-semibold tracking-tight" "Checkout error")
    (p :class "text-xs sm:text-sm text-stone-600" "We tried to start your payment with SumUp but hit a problem.")))

(defcomp ~shared:orders/checkout-error-order-id (&key (oid :as string))
  (p :class "text-xs text-rose-800/80" "Order ID: " (span :class "font-mono" oid)))

(defcomp ~shared:orders/checkout-error-content (&key (msg :as string) order (back-url :as string))
  (div :class "max-w-full px-3 py-3 space-y-4"
    (div :class "rounded-2xl border border-rose-200 bg-rose-50/80 p-4 sm:p-6 text-sm text-rose-900 space-y-2"
      (p :class "font-medium" "Something went wrong.")
      (p msg)
      order)
    (div (a :href back-url :class "inline-flex items-center px-3 py-2 text-xs sm:text-sm rounded-full border border-stone-300 bg-white hover:bg-stone-50 transition"
      (i :class "fa fa-shopping-cart mr-2" :aria-hidden "true") "Back to cart"))))
