/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * Orders & Deliveries view — embedded inside each store's detail panel.
 * Rebuilt to match the same consoleUi design system used by OrdersView and
 * DeliveriesView: gradient header, KPI strip with gradient top-bars, Pill
 * filter tabs, status chips, full paginated data table, CSV export, and an
 * order detail modal. Wired to the live Fiesta orders/getorders endpoint via
 * useFiestaAllOrders (which merges all statuses in parallel).
 */

import React, { useMemo, useState, useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';
import {
  ShoppingBag, Clock, CheckCircle2, XCircle, MapPin, Phone,
  Package, Loader2, X, Download, ChevronLeft, ChevronRight, Truck,
  UserCheck,
} from 'lucide-react';
import {
  useFiestaAllOrders,
  useFiestaDeliverySummary,
  useFiestaRiders,
  useFiestaOrderDetails,
} from '../services/fiestaQueries';
import { FIESTA_TENANT_ID, num as fnum, str as fstr, ymd, type Row } from '../services/fiestaApi';
import { shortTime } from '../services/fiestaMappers';
import {
  GradientHeader, LiveStatus, KpiStrip, Pill, StatusChip, SearchPill, FilterBar, TH_STYLE,
  ORDER_STATUS, statusColor, BRAND, BRAND_LIGHT, TEXT, TEXT_2, TEXT_3, BORDER, DIVIDER, SURFACE_ALT,
  tint, soft, edge, ring,
} from './consoleUi';

interface OrdersDeliveriesViewProps {
  searchQuery?: string;
  isCoimbatoreView?: boolean;
  locationid?: number;
  tenantId?: number;
}

type StatusKey = 'all' | 'created' | 'pending' | 'processing' | 'delivered' | 'cancelled';
const STATUS_TABS: Array<{ key: StatusKey; label: string }> = [
  { key: 'all',        label: 'All Orders'  },
  { key: 'created',    label: 'Created'     },
  { key: 'pending',    label: 'Pending'     },
  { key: 'processing', label: 'Processing'  },
  { key: 'delivered',  label: 'Delivered'   },
  { key: 'cancelled',  label: 'Cancelled'   },
];
const PAGE_SIZE = 20;

export default function OrdersDeliveriesView({
  searchQuery = '',
  locationid,
  tenantId = FIESTA_TENANT_ID,
}: OrdersDeliveriesViewProps) {
  const todayStr = ymd(new Date());

  const [fromdate, setFromdate] = useState(todayStr);
  const [todate, setTodate] = useState(todayStr);

  const [status,   setStatus]   = useState<StatusKey>('all');
  const [pageno,   setPageno]   = useState(1);
  const [localSearch, setLocalSearch] = useState('');
  const [detailOrder, setDetailOrder] = useState<Row | null>(null);

  // Search: Ctrl+K to focus, Escape to blur
  const searchRef = useRef<HTMLInputElement>(null);
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'k' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); searchRef.current?.focus(); }
      else if (e.key === 'Escape' && document.activeElement === searchRef.current) searchRef.current?.blur();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, []);

  // ── Queries ──────────────────────────────────────────────────────────────────
  const allOrdersQ = useFiestaAllOrders({ tenantid: tenantId, fromdate, todate, locationid });
  const summaryQ   = useFiestaDeliverySummary({ tenantid: tenantId, fromdate, todate, locationid });
  const ridersQ    = useFiestaRiders({ tenantid: tenantId });

  const allRows = allOrdersQ.data ?? [];
  const summary = summaryQ.data;

  // Per-status row counts (client-side from merged data)
  const statusCounts = useMemo(() => {
    const acc: Record<string, number> = {};
    for (const r of allRows) {
      const s = fstr(r.orderstatus).toLowerCase();
      acc[s] = (acc[s] ?? 0) + 1;
    }
    return acc;
  }, [allRows]);

  const countFor = (key: StatusKey) => key === 'all' ? allRows.length : (statusCounts[key] ?? 0);

  const activeFleet = (ridersQ.data ?? []).filter((r) => fstr(r.starttime)).length;

  // Filter by status + search (status='all' shows everything in the date range)
  const rows = useMemo(() => {
    const term = (localSearch || searchQuery).toLowerCase();
    return allRows.filter((r) => {
      if (locationid) {
        const rLoc = fnum(r.locationid);
        const rApp = fnum(r.applocationid);
        if (rLoc !== locationid && rApp !== locationid) return false;
      }
      if (status !== 'all' && fstr(r.orderstatus).toLowerCase() !== status) return false;
      if (!term) return true;
      return [
        r.orderid, r.orderheaderid, r.orderstatus, r.tenantname,
        r.pickupcustomer, r.pickupcontactno, r.pickupaddress, r.pickupsuburb,
        r.deliverycustomer, r.deliverycontactno, r.deliveryaddress, r.deliverysuburb,
        r.applocation, r.locationname, r.ridername,
      ].some((v) => fstr(v).toLowerCase().includes(term));
    });
  }, [allRows, status, localSearch, searchQuery, locationid]);

  // Pagination
  const pageRows = useMemo(
    () => rows.slice((pageno - 1) * PAGE_SIZE, pageno * PAGE_SIZE),
    [rows, pageno],
  );
  const hasNext = rows.length > pageno * PAGE_SIZE;

  // Totals
  const totals = useMemo(() => {
    let cod = 0, amount = 0;
    for (const r of rows) {
      cod    += fnum(r.collectionamt);
      amount += fnum(r.ordervalue) || fnum(r.orderamount) || fnum(r.deliveryamt);
    }
    return { cod, amount };
  }, [rows]);

  const total = allRows.length;
  const pct   = (n: number) => (total > 0 ? Math.round((n / total) * 100) : 0);

  const kpis = [
    { label: 'Created Orders',   value: countFor('created').toLocaleString('en-IN'),   color: '#6366f1', icon: <ShoppingBag size={20} />, badge: `${pct(countFor('created'))}% of total`   },
    { label: 'Pending Orders',   value: countFor('pending').toLocaleString('en-IN'),   color: '#f59e0b', icon: <Clock size={20} />,       badge: `${pct(countFor('pending'))}% of total`   },
    { label: 'Delivered Orders', value: countFor('delivered').toLocaleString('en-IN'), color: '#10b981', icon: <CheckCircle2 size={20} />, badge: `${pct(countFor('delivered'))}% of total` },
    { label: 'Cancelled Orders', value: countFor('cancelled').toLocaleString('en-IN'), color: '#f43f5e', icon: <XCircle size={20} />,     badge: `${pct(countFor('cancelled'))}% of total` },
  ];

  // CSV export
  const exportCsv = () => {
    const headers = ['#', 'Order ID', 'Status', 'Branch', 'Order Date', 'Pickup', 'Pickup Contact', 'Pickup Address', 'Drop', 'Drop Contact', 'Drop Address', 'Qty', 'COD', 'Amount'];
    const esc = (v: unknown) => `"${fstr(v).replace(/"/g, '""')}"`;
    const lines = rows.map((r, i) => [
      i + 1,
      fstr(r.orderid) || fstr(r.orderheaderid),
      fstr(r.orderstatus),
      fstr(r.applocation) || fstr(r.locationname),
      shortTime(r.orderdate || r.deliverydate),
      fstr(r.pickupcustomer) || fstr(r.tenantname),
      fstr(r.pickupcontactno),
      fstr(r.pickupaddress) || fstr(r.pickupsuburb),
      fstr(r.deliverycustomer),
      fstr(r.deliverycontactno),
      fstr(r.deliveryaddress) || fstr(r.deliverysuburb),
      fnum(r.quantity),
      fnum(r.collectionamt),
      fnum(r.ordervalue) || fnum(r.orderamount) || fnum(r.deliveryamt),
    ].map(esc).join(','));
    const blob = new Blob([[headers.join(','), ...lines].join('\n')], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href = url;
    a.download = `Orders_${status}_${fromdate}_to_${todate}.csv`; a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="animate-in fade-in duration-300">
      <GradientHeader
        title="Orders & Deliveries"
        subtitle="Live order board across the full lifecycle — created, pending, processing, delivered, and cancelled."
        status={
          allOrdersQ.isLoading
            ? <LiveStatus state="loading" label="Loading live orders…" />
            : allOrdersQ.isError
              ? <LiveStatus state="error"   label="Live data unavailable" />
              : <LiveStatus state="live"    label={`Live · ${total.toLocaleString('en-IN')} orders in range · ${activeFleet} riders on duty`} />
        }
        right={
          <div className="flex items-center gap-3">
            <div className="flex items-center gap-1.5">
              <input type="date" value={fromdate} max={todate} onChange={(e) => setFromdate(e.target.value)} className="rounded-full outline-none font-semibold text-xs transition-colors" style={{ padding: '6px 12px', border: `1.5px solid ${edge(BRAND)}`, background: tint(BRAND), color: BRAND }} />
              <span className="text-zinc-400 font-bold px-1 text-xs">—</span>
              <input type="date" value={todate} min={fromdate} max={todayStr} onChange={(e) => setTodate(e.target.value)} className="rounded-full outline-none font-semibold text-xs transition-colors" style={{ padding: '6px 12px', border: `1.5px solid ${edge(BRAND)}`, background: tint(BRAND), color: BRAND }} />
            </div>
            <span className="inline-flex items-center gap-1.5 rounded-full font-extrabold"
              style={{ padding: '6px 12px', fontSize: 12, background: tint(BRAND), border: `1.5px solid ${edge(BRAND)}`, color: BRAND }}>
              <MapPin size={13} /> {locationid ? `Location ${locationid}` : 'All Locations'}
            </span>
          </div>
        }
      />

      <div className="mb-4"><KpiStrip items={kpis} loading={allOrdersQ.isLoading} /></div>


      {/* Status tabs + search + CSV */}
      <FilterBar className="mb-4">
        <div className="flex flex-col lg:flex-row lg:items-center gap-3">
          <div className="flex items-center gap-2 overflow-x-auto py-0.5 flex-1 min-w-0">
            {STATUS_TABS.map((t) => (
              <React.Fragment key={t.key}>
                <Pill active={status === t.key} color={BRAND} onClick={() => { setStatus(t.key); setPageno(1); }}
                  count={allOrdersQ.isLoading ? '·' : countFor(t.key).toLocaleString('en-IN')}>
                  {t.label}
                </Pill>
              </React.Fragment>
            ))}
          </div>
          <div className="flex items-center gap-2 w-full lg:w-auto lg:shrink-0">
            <div className="w-full lg:w-64">
              <SearchPill value={localSearch} onChange={setLocalSearch} placeholder="Search orders (Ctrl+K)…" inputRef={searchRef} />
            </div>
            <button
              onClick={exportCsv}
              disabled={rows.length === 0}
              title="Export current view to CSV"
              className="inline-flex items-center gap-1.5 rounded-full font-extrabold text-white cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed whitespace-nowrap shrink-0"
              style={{ padding: '8px 14px', fontSize: 12, background: `linear-gradient(135deg, ${BRAND}, ${BRAND_LIGHT})`, boxShadow: `0 6px 18px ${ring(BRAND)}` }}
            >
              <Download size={13} /> CSV
            </button>
          </div>
        </div>
      </FilterBar>

      {/* Table */}
      <div className="bg-white border rounded-2xl overflow-hidden" style={{ borderColor: BORDER }}>
        <div className="overflow-x-auto">
          <table className="w-full" style={{ minWidth: 900 }}>
            <thead>
              <tr>
                {['#', 'Order', 'Branch', 'Pickup', 'Drop', 'Qty', 'COD', 'Amount', 'Status', ''].map((h, i) => (
                  <th key={i} className="px-3 py-2.5 text-left" style={TH_STYLE}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {allOrdersQ.isLoading ? (
                <tr><td colSpan={10} className="px-3 py-12 text-center" style={{ color: TEXT_3 }}>
                  <span className="inline-flex items-center gap-2 text-xs font-semibold">
                    <Loader2 size={15} className="animate-spin" style={{ color: BRAND }} /> Loading orders…
                  </span>
                </td></tr>
              ) : pageRows.length === 0 ? (
                <tr><td colSpan={10} className="px-3 py-12 text-center text-xs" style={{ color: TEXT_3 }}>
                  No {status} orders found for this date range or search.
                </td></tr>
              ) : (
                pageRows.map((r, i) => {
                  const st     = fstr(r.orderstatus).toLowerCase();
                  const cod    = fnum(r.collectionamt);
                  const amount = fnum(r.ordervalue) || fnum(r.orderamount) || fnum(r.deliveryamt);
                  return (
                    <tr
                      key={fstr(r.orderid) || fstr(r.orderheaderid) || i}
                      className="transition-colors align-top"
                      style={{ borderBottom: `1px solid ${DIVIDER}` }}
                      onMouseEnter={(e) => (e.currentTarget.style.background = SURFACE_ALT)}
                      onMouseLeave={(e) => (e.currentTarget.style.background = 'transparent')}
                    >
                      <td className="px-3 py-2.5 font-mono" style={{ color: TEXT_3 }}>{(pageno - 1) * PAGE_SIZE + i + 1}</td>
                      <td className="px-3 py-2.5">
                        <p className="font-extrabold font-mono text-[13px]" style={{ color: TEXT }}>{fstr(r.orderid) || `#${fstr(r.orderheaderid)}`}</p>
                        <p className="text-[10px]" style={{ color: TEXT_2 }}>{shortTime(r.orderdate || r.deliverydate)}</p>
                      </td>
                      <td className="px-3 py-2.5">
                        <span className="inline-flex items-center gap-1 font-bold text-[12px]" style={{ color: BRAND }}>
                          <MapPin size={11} /> {fstr(r.applocation) || '—'}
                        </span>
                        {fstr(r.locationname) && <p className="text-[10px] truncate max-w-[120px]" style={{ color: TEXT_2 }}>{fstr(r.locationname)}</p>}
                      </td>
                      <td className="px-3 py-2.5">
                        <p className="font-bold text-[12px] truncate max-w-[140px]" style={{ color: TEXT }}>{fstr(r.pickupcustomer) || fstr(r.tenantname) || '—'}</p>
                        <p className="text-[10px] truncate max-w-[140px]" style={{ color: TEXT_2 }}>{fstr(r.pickupsuburb) || fstr(r.pickupaddress)}</p>
                      </td>
                      <td className="px-3 py-2.5">
                        <p className="font-bold text-[12px] truncate max-w-[140px]" style={{ color: TEXT }}>{fstr(r.deliverycustomer) || '—'}</p>
                        <p className="text-[10px] truncate max-w-[140px]" style={{ color: TEXT_2 }}>{fstr(r.deliverysuburb) || fstr(r.deliveryaddress)}</p>
                      </td>
                      <td className="px-3 py-2.5 font-mono text-[12px]" style={{ color: TEXT }}>{fnum(r.quantity) || '—'}</td>
                      <td className="px-3 py-2.5 font-mono text-[12px] font-semibold" style={{ color: cod > 0 ? TEXT : TEXT_3 }}>{cod > 0 ? `₹${cod.toLocaleString('en-IN')}` : '—'}</td>
                      <td className="px-3 py-2.5 font-mono text-[12px] font-semibold" style={{ color: amount > 0 ? TEXT : TEXT_3 }}>{amount > 0 ? `₹${amount.toLocaleString('en-IN')}` : '—'}</td>
                      <td className="px-3 py-2.5"><StatusChip label={st || '—'} color={statusColor(ORDER_STATUS, st)} /></td>
                      <td className="px-3 py-2.5 text-right">
                        <button onClick={() => setDetailOrder(r)}
                          className="rounded-full font-extrabold cursor-pointer transition-colors"
                          style={{ padding: '4px 12px', fontSize: 11, color: BRAND, background: tint(BRAND), border: `1px solid ${edge(BRAND)}` }}>
                          View
                        </button>
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>

        {/* Totals footer */}
        {rows.length > 0 && (
          <div className="flex flex-wrap items-center justify-end gap-2 px-4 py-2.5 border-t" style={{ borderColor: BORDER, background: SURFACE_ALT }}>
            <span className="text-[10px] font-extrabold uppercase tracking-wider mr-auto" style={{ color: TEXT_2 }}>
              Totals · {rows.length} order{rows.length === 1 ? '' : 's'}
            </span>
            {totals.cod > 0 && <TotalChip label="COD" value={`₹${totals.cod.toLocaleString('en-IN')}`} color={TEXT_2} />}
            <TotalChip label="Amount" value={`₹${totals.amount.toLocaleString('en-IN')}`} color={BRAND} />
          </div>
        )}

        {/* Pagination */}
        <div className="flex items-center justify-between px-4 py-3 border-t" style={{ borderColor: BORDER, background: SURFACE_ALT }}>
          <span className="text-[10px] font-bold uppercase tracking-wider" style={{ color: TEXT_2 }}>
            Page {pageno} · {pageRows.length} of {rows.length} shown
          </span>
          <div className="flex items-center gap-2">
            <PagerBtn disabled={pageno === 1} onClick={() => setPageno((p) => Math.max(1, p - 1))}>
              <ChevronLeft size={13} /> Prev
            </PagerBtn>
            <PagerBtn disabled={!hasNext} onClick={() => setPageno((p) => p + 1)}>
              Next <ChevronRight size={13} />
            </PagerBtn>
          </div>
        </div>
      </div>

      {detailOrder && <OrderDetailModal order={detailOrder} onClose={() => setDetailOrder(null)} />}
    </div>
  );
}

// ── Helpers ───────────────────────────────────────────────────────────────────

function TotalChip({ label, value, color }: { label: string; value: string; color: string }) {
  return (
    <span className="inline-flex items-center gap-1.5 rounded-full font-bold"
      style={{ padding: '4px 11px', fontSize: 11.5, background: soft(color), color, border: `1px solid ${edge(color)}` }}>
      <span className="uppercase tracking-wider text-[9px] font-extrabold opacity-80">{label}</span>
      <span className="font-mono">{value}</span>
    </span>
  );
}

function PagerBtn({ children, disabled, onClick }: { children: React.ReactNode; disabled?: boolean; onClick: () => void }) {
  return (
    <button onClick={onClick} disabled={disabled}
      className="inline-flex items-center gap-1 rounded-full font-bold transition-colors cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed"
      style={{ padding: '6px 12px', fontSize: 11, border: `1px solid ${BORDER}`, background: '#fff', color: TEXT_2 }}>
      {children}
    </button>
  );
}

// ── Order details modal ────────────────────────────────────────────────────────
function OrderDetailModal({ order, onClose }: { order: Row; onClose: () => void }) {
  const orderheaderid = order.orderheaderid ?? order.orderid;
  const detailsQ = useFiestaOrderDetails(orderheaderid as number | string);
  const lines = (detailsQ.data ?? []).map((row) => {
    const quantity  = fnum(row.quantity)  || fnum(row.qty)        || fnum(row.orderqty);
    const price     = fnum(row.price)     || fnum(row.unitprice)  || fnum(row.retailprice);
    return {
      name: fstr(row.productname) || fstr(row.itemname) || 'Item',
      quantity,
      price,
      lineTotal: fnum(row.amount) || fnum(row.productsumprice) || price * quantity,
    };
  });

  const st     = fstr(order.orderstatus).toLowerCase();
  const total  = fnum(order.ordervalue) || fnum(order.orderamount) || fnum(order.deliveryamt);
  const rider  = fstr(order.ridername) || fstr(order.username);

  const STEPS = [
    { label: 'Order Placed',    field: 'orderdate'    },
    { label: 'Confirmed',       field: 'starttime'    },
    { label: 'Packed & Ready',  field: 'packtime'     },
    { label: 'Out for Delivery',field: 'pickuptime'   },
    { label: 'Delivered',       field: 'deliverytime' },
  ];

  return createPortal(
    <div
      className="fixed inset-0 z-[200] flex items-center justify-center p-4"
      style={{ background: 'rgba(15,23,42,0.4)', backdropFilter: 'blur(4px)' }}
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div
        className="bg-white max-h-[90vh] flex flex-col overflow-hidden rounded-2xl animate-in zoom-in-95 duration-200"
        style={{ width: 'min(32rem, 92vw)', border: `1px solid ${BORDER}`, boxShadow: '0 18px 50px rgba(15,23,42,0.18)' }}
      >
        {/* Brand accent bar */}
        <div style={{ height: 4, background: `linear-gradient(90deg, ${BRAND} 0%, ${BRAND_LIGHT} 100%)` }} />

        {/* Modal header */}
        <div className="p-4 border-b flex justify-between items-center shrink-0" style={{ borderColor: BORDER, background: SURFACE_ALT }}>
          <h4 className="font-extrabold flex items-center gap-2" style={{ color: TEXT }}>
            <Package size={16} style={{ color: BRAND }} />
            Order {fstr(order.orderid) || `#${fstr(order.orderheaderid)}`}
          </h4>
          <button onClick={onClose} className="p-1 rounded-full cursor-pointer" style={{ color: TEXT_3 }}><X size={16} /></button>
        </div>

        {/* Body */}
        <div className="p-4 space-y-4 overflow-y-auto flex-1">
          {/* Status + rider */}
          <div className="flex items-center justify-between flex-wrap gap-2">
            <StatusChip label={st || '—'} color={statusColor(ORDER_STATUS, st)} />
            <div className="flex items-center gap-3">
              {rider && (
                <span className="inline-flex items-center gap-1.5 text-[11px] font-medium" style={{ color: TEXT_2 }}>
                  <UserCheck size={12} style={{ color: BRAND }} /> {rider}
                </span>
              )}
              <span className="text-[11px] font-medium" style={{ color: TEXT_2 }}>{shortTime(order.orderdate || order.deliverydate)}</span>
            </div>
          </div>

          {/* Customer card */}
          <div className="p-3 rounded-xl space-y-1.5" style={{ background: SURFACE_ALT, border: `1px solid ${BORDER}` }}>
            <div className="flex items-center gap-2 font-bold" style={{ color: TEXT }}>
              {fstr(order.deliverycustomer) || 'Customer'}
            </div>
            {fstr(order.deliverycontactno) && (
              <div className="flex items-center gap-2 font-mono text-xs" style={{ color: TEXT_2 }}>
                <Phone size={12} /> {fstr(order.deliverycontactno)}
              </div>
            )}
            <div className="flex items-start gap-2 text-xs" style={{ color: TEXT_2 }}>
              <MapPin size={12} className="mt-0.5 shrink-0" />
              <span className="leading-relaxed">{fstr(order.deliveryaddress) || fstr(order.deliverysuburb) || 'Address unavailable'}</span>
            </div>
          </div>

          {/* Delivery timeline */}
          <div>
            <span className="text-[10px] font-extrabold uppercase tracking-wide block mb-2" style={{ color: TEXT_2 }}>
              Delivery Timeline
            </span>
            <div className="space-y-2.5 pl-1">
              {STEPS.map((s) => {
                const ts   = fstr(order[s.field]);
                const done = Boolean(ts);
                return (
                  <div key={s.field} className="flex items-center gap-2.5">
                    <CheckCircle2 size={13} style={{ color: done ? '#10b981' : '#cbd5e1' }} />
                    <span className="font-semibold text-xs" style={{ color: done ? TEXT : TEXT_3 }}>{s.label}</span>
                    <span className="ml-auto text-[10px] font-mono" style={{ color: TEXT_3 }}>{done ? shortTime(ts) : '—'}</span>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Line items */}
          <div>
            <span className="text-[10px] font-extrabold uppercase tracking-wide block mb-2 flex items-center gap-1.5" style={{ color: TEXT_2 }}>
              <Package size={12} /> Items
            </span>
            <div className="rounded-xl p-3" style={{ background: 'rgba(248,250,252,0.6)', border: `1px solid ${BORDER}` }}>
              {detailsQ.isLoading && (
                <div className="py-2 flex items-center gap-1.5 text-[11px] font-medium" style={{ color: TEXT_3 }}>
                  <Loader2 size={12} className="animate-spin" /> Loading line items…
                </div>
              )}
              {!detailsQ.isLoading && lines.length === 0 && (
                <div className="py-2 text-[11px] font-medium" style={{ color: TEXT_3 }}>
                  No line items returned for this order.
                </div>
              )}
              {lines.map((item, idx) => (
                <div key={idx} className="py-2 flex justify-between items-center"
                  style={{ borderTop: idx ? `1px solid ${DIVIDER}` : undefined }}>
                  <div>
                    <p className="font-bold text-xs" style={{ color: TEXT }}>{item.name}</p>
                    <p className="text-[10px]" style={{ color: TEXT_2 }}>Qty: {item.quantity} × ₹{item.price}</p>
                  </div>
                  <span className="font-extrabold font-mono text-xs" style={{ color: TEXT }}>₹{item.lineTotal.toLocaleString('en-IN')}</span>
                </div>
              ))}
              {total > 0 && (
                <div className="pt-2 mt-1 flex justify-between items-center font-extrabold text-sm"
                  style={{ color: BRAND, borderTop: `1px dashed ${BORDER}` }}>
                  <span>Order Total</span>
                  <span className="font-mono">₹{total.toLocaleString('en-IN')}</span>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="p-3 border-t flex justify-end shrink-0" style={{ borderColor: BORDER, background: SURFACE_ALT }}>
          <button onClick={onClose} className="rounded-full font-bold cursor-pointer text-white"
            style={{ padding: '8px 16px', background: `linear-gradient(135deg, ${BRAND}, ${BRAND_LIGHT})` }}>
            Close
          </button>
        </div>
      </div>
    </div>,
    document.body,
  );
}
