// TruckOrderSummary.jsx — finalized order detail view.
//
// Lines are regrouped by VENDOR (not storage area) since this is the view
// you'll actually send to suppliers. Each vendor section has a "Download PDF"
// button that opens a print-styled view in a new window.
//
// Also used to view past orders from the log.

const { useMemo: useMemoOS } = React;

const OrderSummaryView = ({ order, onBack, onDelete }) => {
  const allItems   = window.SAMPLE_INVENTORY_ITEMS  || [];
  const allVendors = window.SAMPLE_VENDORS          || [];

  const itemById   = useMemoOS(() => Object.fromEntries(allItems.map(i => [i.id, i])), [allItems]);
  const vendorById = useMemoOS(() => Object.fromEntries(allVendors.map(v => [v.id, v])), [allVendors]);

  // Regroup by vendor; only lines with final > 0 actually need to be ordered.
  const vendorGroups = useMemoOS(() => {
    const buckets = {};
    order.lines.forEach(line => {
      if ((line.final || 0) <= 0) return;
      const item = itemById[line.itemId];
      const vendorId = item?.vendorId || '__none';
      if (!buckets[vendorId]) {
        buckets[vendorId] = {
          vendor: vendorById[vendorId] || { id: vendorId, name: 'No vendor' },
          lines: [],
        };
      }
      buckets[vendorId].lines.push({ ...line, item });
    });
    return Object.values(buckets).sort((a, b) => a.vendor.name.localeCompare(b.vendor.name));
  }, [order.lines, itemById, vendorById]);

  // Lines that were counted but NOT ordered (informational).
  const noOrderLines = useMemoOS(() => {
    return order.lines
      .filter(l => (l.final || 0) <= 0)
      .map(l => ({ ...l, item: itemById[l.itemId] }))
      .filter(l => l.item);
  }, [order.lines, itemById]);

  const finalizer = window.SAMPLE_STAFF.find(s => s.id === order.finalizedByStaffId);
  const creator   = window.SAMPLE_STAFF.find(s => s.id === order.createdByStaffId);

  const totalLines = order.lines.length;
  const totalOrdered = order.lines.reduce((sum, l) => sum + (l.final > 0 ? 1 : 0), 0);
  const totalOverrides = order.lines.filter(l => l.overridden).length;

  return (
    <div className="portal-page-wide" style={{ maxWidth: 1180 }}>
      {/* Back link */}
      <button onClick={onBack} style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        padding: '6px 10px 6px 6px',
        background: 'transparent', border: 'none',
        cursor: 'pointer',
        color: 'var(--fg-2)',
        fontSize: 13,
        marginBottom: 16,
        marginLeft: -10,
      }}>
        <PIcon name="chevronL" size={15} />
        Back to orders
      </button>

      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 24, flexWrap: 'wrap', marginBottom: 24 }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 6 }}>
            Truck order · finalized
          </div>
          <h1 style={{ fontSize: 28, fontWeight: 600, letterSpacing: '-0.02em', margin: 0 }}>{toFmtDate(order.finalizedAt)}</h1>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 10, flexWrap: 'wrap', fontSize: 12.5, color: 'var(--fg-2)' }}>
            {creator && (
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                <span style={{ color: 'var(--fg-3)' }}>Started by</span>
                <PAvatar staff={creator} size={20} />
                <span style={{ fontWeight: 500, color: 'var(--fg-1)' }}>{creator.name}</span>
              </div>
            )}
            {finalizer && (
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                <span style={{ color: 'var(--fg-3)' }}>Finalized by</span>
                <PAvatar staff={finalizer} size={20} />
                <span style={{ fontWeight: 500, color: 'var(--fg-1)' }}>{finalizer.name}</span>
                <span style={{ color: 'var(--fg-3)' }}>· {toFmtTime(order.finalizedAt)}</span>
              </div>
            )}
          </div>
          {order.note && (
            <div style={{
              marginTop: 14, padding: '10px 14px',
              background: '#FBFAF8',
              border: '1px solid var(--border-2)',
              borderLeft: '3px solid var(--fg-2)',
              borderRadius: 6,
              fontSize: 13, color: 'var(--fg-2)',
              maxWidth: 600,
            }}>
              {order.note}
            </div>
          )}
        </div>
        {onDelete && (
          <PBtn variant="ghost" onClick={onDelete} style={{ color: 'var(--danger)' }}>
            <PIcon name="trash" size={13} />
            Delete
          </PBtn>
        )}
      </div>

      {/* Stat strip */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(4, 1fr)',
        gap: 1,
        background: 'var(--border-2)',
        border: '1px solid var(--border-2)',
        borderRadius: 10,
        overflow: 'hidden',
        marginBottom: 28,
      }}>
        <SummaryStat label="Items counted"     value={totalLines} />
        <SummaryStat label="Lines to order"    value={totalOrdered} />
        <SummaryStat label="Vendors"           value={vendorGroups.length} />
        <SummaryStat label="Manual overrides"  value={totalOverrides} warn={totalOverrides > 0} />
      </div>

      {/* Vendor sections */}
      {vendorGroups.length === 0 ? (
        <div className="portal-empty">
          <div style={{ fontSize: 14, color: 'var(--fg-2)' }}>Nothing to order in this count.</div>
        </div>
      ) : vendorGroups.map(group => (
        <VendorSection key={group.vendor.id} group={group} order={order} />
      ))}

      {/* No-order lines (informational) */}
      {noOrderLines.length > 0 && (
        <details style={{
          marginTop: 28,
          padding: '12px 16px',
          background: '#FBFAF8',
          border: '1px solid var(--border-2)',
          borderRadius: 10,
        }}>
          <summary style={{ cursor: 'pointer', fontSize: 13, fontWeight: 600, color: 'var(--fg-2)' }}>
            {noOrderLines.length} item{noOrderLines.length === 1 ? '' : 's'} counted but not ordered
          </summary>
          <div style={{ marginTop: 12, display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 6 }}>
            {noOrderLines.map(l => (
              <div key={l.itemId} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--fg-2)' }}>
                <PIcon name="check" size={11} color="var(--fg-3)" />
                <span>{l.item.name}</span>
                <span style={{ color: 'var(--fg-3)', fontFamily: 'var(--font-num)' }}>
                  · {toFmtQty(window.truckOnHandDisplay(l.item, l.countStorage, l.countPurchase))}{' '}
                  {window.truckIsStorageLarger(l.item) ? l.item.storageUnit : l.item.purchaseUnit} on hand
                </span>
              </div>
            ))}
          </div>
        </details>
      )}
    </div>
  );
};

// ------------------------------------------------------------------
// Per-vendor section
// ------------------------------------------------------------------
const VendorSection = ({ group, order }) => {
  const { vendor, lines } = group;
  const totalUnits = lines.reduce((s, l) => s + (l.final || 0), 0);

  return (
    <div style={{
      background: '#FFFFFF',
      border: '1px solid var(--border-2)',
      borderRadius: 10,
      overflow: 'hidden',
      marginBottom: 16,
    }}>
      <div style={{
        padding: '14px 18px',
        background: '#FAFAF9',
        borderBottom: '1px solid var(--border-2)',
        display: 'flex', alignItems: 'center', gap: 14,
      }}>
        <span style={{
          width: 36, height: 36, borderRadius: 8,
          background: '#FFFFFF',
          border: '1px solid var(--border-2)',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 14, fontWeight: 700, color: 'var(--fg-1)',
          letterSpacing: '-0.01em',
        }}>{vendor.name.slice(0, 2).toUpperCase()}</span>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--fg-1)', letterSpacing: '-0.005em' }}>{vendor.name}</div>
          <div style={{ fontSize: 11.5, color: 'var(--fg-3)', marginTop: 2 }}>
            {lines.length} item{lines.length === 1 ? '' : 's'} · {totalUnits} unit{totalUnits === 1 ? '' : 's'} to order
          </div>
        </div>
        <PBtn variant="secondary" onClick={() => printVendorOrder(group, order)}>
          <PIcon name="download" size={13} />
          PDF
        </PBtn>
        <PBtn variant="ghost" onClick={() => copyVendorOrder(group)} title="Copy as plain text">
          <PIcon name="copy" size={13} />
        </PBtn>
      </div>

      <table style={{ borderCollapse: 'collapse', width: '100%' }}>
        <thead>
          <tr style={{ borderBottom: '1px solid var(--border-2)' }}>
            <th style={{ ...thStyle, width: 130 }}>SKU</th>
            <th style={thStyle}>Item</th>
            <th style={{ ...thStyle, width: 110, textAlign: 'right' }}>On hand</th>
            <th style={{ ...thStyle, width: 140, textAlign: 'right' }}>Order</th>
          </tr>
        </thead>
        <tbody>
          {lines.map(line => {
            const item = line.item;
            const onHand = window.truckOnHand(item, line.countStorage, line.countPurchase);
            return (
              <tr key={line.itemId} style={{ borderBottom: '1px solid var(--border-2)' }}>
                <td style={{ padding: '12px 18px', fontFamily: 'var(--font-num)', fontSize: 12, color: 'var(--fg-2)', whiteSpace: 'nowrap' }}>
                  {item.vendorSku || '—'}
                </td>
                <td style={{ padding: '12px 18px' }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--fg-1)' }}>{item.name}</div>
                  {(item.vendorAliases || []).length > 0 && (
                    <div style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 2 }}>
                      {(item.vendorAliases || []).join(' · ')}
                    </div>
                  )}
                </td>
                <td style={{ padding: '12px 18px', textAlign: 'right' }}>
                  <div style={{ fontFamily: 'var(--font-num)', fontSize: 13.5, fontWeight: 600, color: 'var(--fg-1)', letterSpacing: '-0.005em' }}>
                    {toFmtQty(window.truckOnHandDisplay(item, line.countStorage, line.countPurchase))}
                  </div>
                  <div style={{ fontSize: 10.5, color: 'var(--fg-3)', marginTop: 2 }}>
                    {window.truckIsStorageLarger(item) ? item.storageUnit : item.purchaseUnit}
                  </div>
                </td>
                <td style={{ padding: '12px 18px', textAlign: 'right' }}>
                  <div style={{
                    fontSize: 18, fontWeight: 700,
                    color: line.overridden ? '#92400E' : '#2D6A2A',
                    fontFamily: 'var(--font-num)', letterSpacing: '-0.01em', lineHeight: 1.1,
                  }}>{line.final}</div>
                  <div style={{ fontSize: 10.5, color: 'var(--fg-3)', marginTop: 2 }}>{item.purchaseUnit}</div>
                  {line.overridden && (
                    <div style={{ marginTop: 4, display: 'inline-block' }}>
                      <OverrideMark>auto was {line.suggested}</OverrideMark>
                    </div>
                  )}
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
};

const thStyle = {
  textAlign: 'left',
  padding: '10px 18px',
  fontSize: 10.5, fontWeight: 700,
  color: 'var(--fg-3)',
  textTransform: 'uppercase', letterSpacing: '0.06em',
};

const SummaryStat = ({ label, value, warn }) => (
  <div style={{ background: '#FFFFFF', padding: '16px 18px' }}>
    <div style={{
      fontSize: 24, fontWeight: 700, letterSpacing: '-0.02em',
      fontFamily: 'var(--font-num)',
      color: warn ? '#92400E' : 'var(--fg-1)',
    }}>{value}</div>
    <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginTop: 4 }}>
      {label}
    </div>
  </div>
);

// ------------------------------------------------------------------
// PDF generation — opens a new window with a print-styled HTML page
// using Noto Sans SC (so Chinese glyphs render correctly) and auto-
// triggers the system print dialog. From there the user chooses
// "Save as PDF" — the resulting file opens cleanly in Apple Preview.
//
// We tried html2pdf.js but in some browser+sandbox combos html2canvas
// produced blank captures. The native print path is bulletproof.
// ------------------------------------------------------------------
const printVendorOrder = (group, order) => {
  const { vendor, lines } = group;
  const finalizer = window.SAMPLE_STAFF.find(s => s.id === order.finalizedByStaffId);
  const dateStr = toFmtDate(order.finalizedAt);
  const timeStr = toFmtTime(order.finalizedAt);
  const totalUnits = lines.reduce((s, l) => s + (l.final || 0), 0);

  const rows = lines.map((line) => {
    const item = line.item;
    const aliases = (item.vendorAliases || []).join(' · ');
    return `
      <tr>
        <td class="mono sku">${escapeHtml(item.vendorSku || '—')}</td>
        <td class="item-cell">
          <div class="item-name">${escapeHtml(item.name)}</div>
          ${aliases ? `<div class="item-aliases">${escapeHtml(aliases)}</div>` : ''}
        </td>
        <td class="num order">
          <div class="order-qty">${line.final}</div>
          <div class="order-unit">${escapeHtml(item.purchaseUnit)}</div>
        </td>
      </tr>`;
  }).join('');

  const safeVendor = vendor.name.replace(/[^a-z0-9\u4e00-\u9fff]+/gi, '_');
  const safeDate = (order.finalizedAt || '').slice(0, 10);
  // Browser uses document.title as the default Save-as-PDF filename.
  const docTitle = `truck-order_${safeVendor}_${safeDate}`;

  const html = `<!doctype html>
<html lang="en"><head>
<meta charset="utf-8" />
<title>${escapeHtml(docTitle)}</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Noto+Sans+SC:wght@400;500;600;700&display=swap">
<style>
  @page { size: letter; margin: 0.6in; }
  * { box-sizing: border-box; }
  html, body {
    margin: 0; padding: 0;
    color: #111;
    -webkit-print-color-adjust: exact; print-color-adjust: exact;
    -webkit-font-smoothing: antialiased;
  }
  body {
    font-family: "Inter", "Noto Sans SC", -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
    padding: 0;
  }
  .topbar {
    position: fixed; top: 0; left: 0; right: 0;
    padding: 12px 16px;
    background: #FAF8F2;
    border-bottom: 1px solid #E8E2D4;
    display: flex; gap: 10px; align-items: center; justify-content: space-between;
    font-size: 13px; color: #444;
    z-index: 100;
  }
  .topbar button {
    font: inherit; cursor: pointer;
    padding: 6px 14px; border-radius: 6px;
    border: 1px solid #111; background: #111; color: #fff;
    font-weight: 600;
  }
  .topbar button.secondary { background: transparent; color: #111; }
  .topbar .hint { color: #666; font-size: 12px; }
  .sheet { padding: 64px 24px 24px; max-width: 7.5in; margin: 0 auto; }

  @media print {
    .topbar { display: none !important; }
    .sheet { padding: 0; max-width: none; margin: 0; }
  }

  .header { display: flex; justify-content: space-between; align-items: flex-end; padding-bottom: 16px; border-bottom: 2px solid #111; margin-bottom: 24px; }
  .brand { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.1em; color: #666; }
  .title { font-size: 24px; font-weight: 700; margin-top: 4px; letter-spacing: -0.01em; }
  .meta { text-align: right; font-size: 12px; color: #444; line-height: 1.5; }
  .meta b { color: #111; }
  table { width: 100%; border-collapse: collapse; font-size: 12px; table-layout: fixed; }
  th { text-align: left; padding: 8px 6px; border-bottom: 1.5px solid #111; font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em; color: #444; font-weight: 700; }
  td { padding: 10px 6px; border-bottom: 1px solid #ddd; vertical-align: top; }
  td.num { text-align: right; font-variant-numeric: tabular-nums; font-weight: 500; white-space: nowrap; }
  td.mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11px; color: #555; }
  td.sku { white-space: nowrap; }
  td.order { font-weight: 700; font-size: 14px; }
  .order-qty { font-size: 18px; font-weight: 700; font-variant-numeric: tabular-nums; letter-spacing: -0.01em; line-height: 1.1; }
  .order-unit { font-size: 10px; color: #666; font-weight: 500; margin-top: 2px; }
  .item-cell { min-width: 0; }
  .item-name { font-weight: 600; font-size: 13px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .item-aliases { font-size: 11px; color: #666; margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .note { margin-top: 20px; padding: 12px 14px; background: #FAF8F2; border-left: 3px solid #888; font-size: 12px; color: #444; }
  .total-row td { font-weight: 700; font-size: 14px; padding-top: 14px; border-bottom: 2px solid #111; }
</style>
</head>
<body>
  <div class="topbar">
    <span class="hint">Print dialog will open automatically. Choose <b>Save as PDF</b> as the destination.</span>
    <div style="display:flex; gap:8px;">
      <button class="secondary" onclick="window.close()">Close</button>
      <button onclick="window.print()">Open print dialog</button>
    </div>
  </div>
  <div class="sheet">
    <div class="header">
      <div>
        <div class="brand">Truck Order</div>
        <div class="title">${escapeHtml(vendor.name)}</div>
      </div>
      <div class="meta">
        <div><b>${dateStr}</b> · ${timeStr}</div>
        ${finalizer ? `<div>Finalized by <b>${escapeHtml(finalizer.name)}</b></div>` : ''}
        <div>Ref: ${escapeHtml(order.id)}</div>
      </div>
    </div>

    <table>
      <thead>
        <tr>
          <th style="width: 110px;">SKU</th>
          <th>Item</th>
          <th style="width: 110px; text-align: right;">Order</th>
        </tr>
      </thead>
      <tbody>
        ${rows}
        <tr class="total-row">
          <td colspan="2" style="text-align: right;">Total</td>
          <td class="num">${totalUnits} units</td>
        </tr>
      </tbody>
    </table>

    ${order.note ? `<div class="note"><b>Note:</b> ${escapeHtml(order.note)}</div>` : ''}
  </div>

  <script>
    // Wait for the CJK web font to actually load, then auto-open the print dialog.
    (async () => {
      try {
        if (document.fonts && document.fonts.ready) {
          await document.fonts.ready;
          await Promise.all([
            document.fonts.load('600 13px "Noto Sans SC"'),
            document.fonts.load('500 13px "Inter"'),
          ]);
        }
        await new Promise(r => setTimeout(r, 250));
        window.print();
      } catch (e) {
        console.error(e);
      }
    })();
  </script>
</body></html>`;

  const w = window.open('', '_blank', 'width=900,height=1100');
  if (!w) {
    alert('Pop-up blocked. Please allow pop-ups for this site so the PDF can open.');
    return;
  }
  w.document.open();
  w.document.write(html);
  w.document.close();
};

const copyVendorOrder = (group) => {
  const { vendor, lines } = group;
  const txt = [
    `${vendor.name} — Truck Order`,
    '',
    ...lines.map(l => {
      const item = l.item;
      const sku = item.vendorSku ? ` (SKU ${item.vendorSku})` : '';
      return `${l.final} ${item.purchaseUnit} — ${item.name}${sku}`;
    }),
  ].join('\n');
  navigator.clipboard?.writeText(txt);
};

const escapeHtml = (s) => String(s ?? '').replace(/[&<>"']/g, c => ({
  '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;',
})[c]);

Object.assign(window, { OrderSummaryView });
