// TruckOrderSummary.jsx — finalized order view on iPad.
//
// Layout:
//   - Back link
//   - Header (date, who started/finalized, optional note)
//   - Vendor sections (one per vendor) with PDF export button
//
// PDF strategy (PWA-friendly):
//   1. Try iframe inside the app — no new window, stays in PWA. Works
//      on most Safari/iPad versions; user prints from the iframe overlay.
//   2. Fall back to window.open() if the iframe approach fails or the
//      user explicitly requests "Open in new tab".
//
// Either way, the print sheet links Noto Sans SC so Chinese aliases render.

const { useMemo: useMemoOs, useState: useOs, useEffect: useEffectOs, useRef: useRefOs } = React;

const TruckOrderSummaryView = ({ 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.
  const vendorGroups = useMemoOs(() => {
    const buckets = {};
    order.lines.forEach(line => {
      if ((line.final || 0) <= 0) return;
      const item = itemById[line.itemId];
      const vid = item?.vendorId || '__none';
      if (!buckets[vid]) {
        buckets[vid] = { vendor: vendorById[vid] || { id: vid, name: 'No vendor' }, lines: [] };
      }
      buckets[vid].lines.push({ ...line, item });
    });
    return Object.values(buckets).sort((a, b) => a.vendor.name.localeCompare(b.vendor.name));
  }, [order.lines, itemById, vendorById]);

  const noOrderLines = useMemoOs(() => 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 totalOrdered = order.lines.reduce((s, l) => s + (l.final > 0 ? 1 : 0), 0);
  const overrides    = order.lines.filter(l => l.overridden).length;

  // PDF iframe state — when set, renders a fullscreen overlay with the
  // print-styled HTML inside an iframe and the system print dialog auto-opens.
  const [pdfOpenFor, setPdfOpenFor] = useOs(null);

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* Header */}
      <div style={{
        flexShrink: 0,
        padding: '14px 22px 12px',
        background: 'var(--bg-surface)',
        borderBottom: '1px solid var(--border-1)',
      }}>
        <button onClick={onBack} style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '6px 10px 6px 6px', marginLeft: -10,
          background: 'transparent', border: 'none', cursor: 'pointer',
          color: 'var(--fg-2)', fontSize: 13,
        }}>
          <Icon name="chevronL" size={16} />
          Back
        </button>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 14, marginTop: 4 }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>
              Truck order · finalized
            </div>
            <div style={{ fontSize: 24, fontWeight: 600, letterSpacing: '-0.02em', marginTop: 2 }}>
              {toFmtDateTo(order.finalizedAt)}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 6, fontSize: 12, color: 'var(--fg-2)', flexWrap: 'wrap' }}>
              {creator && (
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                  <span style={{ color: 'var(--fg-3)' }}>Started by</span>
                  <Avatar staff={creator} size={18} />
                  <b style={{ color: 'var(--fg-1)' }}>{creator.name}</b>
                </span>
              )}
              {finalizer && (
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                  <span style={{ color: 'var(--fg-3)' }}>Finalized</span>
                  <Avatar staff={finalizer} size={18} />
                  <b style={{ color: 'var(--fg-1)' }}>{finalizer.name}</b>
                  <span style={{ color: 'var(--fg-3)' }}>· {toFmtTimeTo(order.finalizedAt)}</span>
                </span>
              )}
            </div>
          </div>
          {onDelete && (
            <button onClick={onDelete} style={{
              padding: '6px 12px', borderRadius: 8,
              background: 'transparent', border: 'none', cursor: 'pointer',
              color: 'var(--danger)', fontSize: 12.5, fontWeight: 500,
              display: 'inline-flex', alignItems: 'center', gap: 5,
            }}>
              <Icon name="x" size={14} strokeWidth={2} /> Delete
            </button>
          )}
        </div>
      </div>

      {/* Body */}
      <div className="scroll-soft" style={{ flex: 1, overflowY: 'auto', padding: '16px 22px 40px' }}>
        {order.note && (
          <div style={{
            marginBottom: 14, padding: '10px 14px',
            background: '#FBFAF8', borderLeft: '3px solid var(--fg-2)',
            borderRadius: 8, fontSize: 13, color: 'var(--fg-2)',
          }}>
            {order.note}
          </div>
        )}

        {/* Stat strip */}
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)',
          gap: 1, background: 'var(--border-2)',
          border: '1px solid var(--border-2)', borderRadius: 12,
          overflow: 'hidden', marginBottom: 20,
        }}>
          <SumStat label="Vendors" value={vendorGroups.length} />
          <SumStat label="Lines to order" value={totalOrdered} />
          <SumStat label="Overrides" value={overrides} warn={overrides > 0} />
        </div>

        {vendorGroups.length === 0 ? (
          <div style={{ padding: 28, textAlign: 'center', fontSize: 14, color: 'var(--fg-2)' }}>
            Nothing to order in this count.
          </div>
        ) : vendorGroups.map(group => (
          <VendorSection key={group.vendor.id} group={group} onExport={() => setPdfOpenFor(group)} />
        ))}

        {noOrderLines.length > 0 && (
          <details style={{
            marginTop: 18, padding: '12px 14px',
            background: '#FBFAF8',
            border: '1px solid var(--border-2)',
            borderRadius: 12,
          }}>
            <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: 10, display: 'flex', flexDirection: 'column', gap: 4 }}>
              {noOrderLines.map(l => (
                <div key={l.itemId} style={{ fontSize: 12.5, color: 'var(--fg-2)', display: 'flex', alignItems: 'center', gap: 6 }}>
                  <Icon name="check" size={11} color="var(--fg-3)" strokeWidth={2} />
                  {l.item.name}
                  <span style={{ color: 'var(--fg-3)', fontFamily: 'var(--font-num)' }}>
                    · {toFmtQtyTo(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>

      {pdfOpenFor && (
        <PdfPreviewOverlay
          group={pdfOpenFor}
          order={order}
          onClose={() => setPdfOpenFor(null)}
        />
      )}
    </div>
  );
};

const VendorSection = ({ group, onExport }) => {
  const totalUnits = group.lines.reduce((s, l) => s + (l.final || 0), 0);
  return (
    <div style={{
      background: '#FFFFFF',
      border: '1px solid var(--border-2)',
      borderRadius: 12,
      overflow: 'hidden',
      marginBottom: 12,
    }}>
      <div style={{
        padding: '12px 14px',
        background: '#FAFAF9',
        borderBottom: '1px solid var(--border-2)',
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <span style={{
          width: 34, height: 34, borderRadius: 8,
          background: '#FFFFFF',
          border: '1px solid var(--border-2)',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 13, fontWeight: 700, color: 'var(--fg-1)',
          letterSpacing: '-0.01em',
        }}>{group.vendor.name.slice(0, 2).toUpperCase()}</span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--fg-1)', letterSpacing: '-0.005em' }}>
            {group.vendor.name}
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--fg-3)', marginTop: 2 }}>
            {group.lines.length} item{group.lines.length === 1 ? '' : 's'} · {totalUnits} unit{totalUnits === 1 ? '' : 's'}
          </div>
        </div>
        <Btn variant="secondary" size="sm" icon="download" onClick={onExport}>PDF</Btn>
      </div>
      {group.lines.map((line, i) => (
        <SummaryLine key={line.itemId} line={line} isLast={i === group.lines.length - 1} />
      ))}
    </div>
  );
};

const SummaryLine = ({ line, isLast }) => {
  const item = line.item;
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: '90px 1fr 88px',
      gap: 12, alignItems: 'center',
      padding: '10px 14px',
      borderBottom: isLast ? 'none' : '1px solid var(--border-2)',
    }}>
      <div style={{ fontFamily: 'var(--font-num)', fontSize: 11.5, color: 'var(--fg-3)' }}>
        {item.vendorSku || '—'}
      </div>
      <div style={{ minWidth: 0 }}>
        <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,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>
            {(item.vendorAliases || []).join(' · ')}
          </div>
        )}
      </div>
      <div style={{ textAlign: 'right' }}>
        <div style={{
          fontSize: 17, fontWeight: 700,
          color: line.overridden ? '#92400E' : '#2D6A2A',
          fontFamily: 'var(--font-num)', letterSpacing: '-0.01em', lineHeight: 1.1,
        }}>{line.final}</div>
        <div style={{ fontSize: 10, color: 'var(--fg-3)', marginTop: 1 }}>{item.purchaseUnit}</div>
        {line.overridden && (
          <div style={{ marginTop: 3, display: 'inline-block' }}>
            <span style={{
              fontSize: 9, fontWeight: 700, color: '#92400E',
              background: '#FDE68A', padding: '2px 6px', borderRadius: 4,
              letterSpacing: '0.04em', textTransform: 'uppercase', whiteSpace: 'nowrap',
            }}>auto was {line.suggested}</span>
          </div>
        )}
      </div>
    </div>
  );
};

const SumStat = ({ label, value, warn }) => (
  <div style={{ background: '#FFFFFF', padding: '12px 14px' }}>
    <div style={{
      fontSize: 22, fontWeight: 700,
      fontFamily: 'var(--font-num)', letterSpacing: '-0.02em',
      color: warn ? '#92400E' : 'var(--fg-1)',
    }}>{value}</div>
    <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginTop: 3 }}>
      {label}
    </div>
  </div>
);

// ------------------------------------------------------------------
// PDF — iframe-inside-the-app overlay (PWA friendly).
// On Safari iPad PWA, window.open is unreliable, so we render the print
// HTML into an iframe sized to the screen with a topbar offering Print
// and "Open in new tab" fallback.
// ------------------------------------------------------------------
const PdfPreviewOverlay = ({ group, order, onClose }) => {
  const iframeRef = useRefOs(null);
  const [ready, setReady] = useOs(false);

  // Build the print HTML once per group/order.
  const html = useMemoOs(() => buildPrintHtml(group, order), [group, order]);

  // Write into the iframe and auto-open print when ready.
  useEffectOs(() => {
    setReady(false);
    const f = iframeRef.current;
    if (!f) return;
    const doc = f.contentDocument || f.contentWindow?.document;
    if (!doc) return;
    doc.open();
    doc.write(html);
    doc.close();
    const w = f.contentWindow;
    const printIt = () => {
      try { w.focus(); w.print(); } catch (_) {}
    };
    const onReady = () => {
      setReady(true);
      // Wait for fonts before printing
      const startPrint = () => setTimeout(printIt, 400);
      try {
        if (w.document.fonts && w.document.fonts.ready) {
          w.document.fonts.ready.then(startPrint);
        } else startPrint();
      } catch (_) { startPrint(); }
    };
    if (w.document.readyState === 'complete') onReady();
    else w.addEventListener('load', onReady, { once: true });
  }, [html]);

  const openInNewTab = () => {
    const w = window.open('', '_blank');
    if (!w) {
      alert('Pop-up blocked. Use Print here or allow pop-ups for this site.');
      return;
    }
    w.document.open();
    w.document.write(html);
    w.document.close();
  };

  const triggerPrint = () => {
    try { iframeRef.current?.contentWindow?.focus(); } catch (_) {}
    try { iframeRef.current?.contentWindow?.print(); } catch (e) { openInNewTab(); }
  };

  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: 'rgba(0,0,0,0.55)',
      zIndex: 40,
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{
        flexShrink: 0,
        background: '#FFFFFF',
        padding: '12px 18px',
        display: 'flex', alignItems: 'center', gap: 12,
        borderBottom: '1px solid var(--border-1)',
      }}>
        <button onClick={onClose} style={{
          width: 34, height: 34, borderRadius: 999,
          background: 'var(--bg-sunken)', border: 'none',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer',
        }}>
          <Icon name="x" size={16} color="var(--fg-1)" strokeWidth={2} />
        </button>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>
            PDF preview
          </div>
          <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--fg-1)' }}>
            {group.vendor.name}
          </div>
        </div>
        <Btn variant="secondary" size="sm" onClick={openInNewTab}>Open in tab</Btn>
        <Btn variant="primary" size="sm" icon="download" onClick={triggerPrint}>Save as PDF</Btn>
      </div>
      <div style={{ flex: 1, background: '#525252', overflow: 'auto', padding: 14 }}>
        <iframe
          ref={iframeRef}
          title="Truck order PDF"
          style={{
            width: '100%', height: '100%',
            background: '#FFFFFF', border: 'none',
            borderRadius: 6, boxShadow: '0 4px 16px rgba(0,0,0,0.3)',
            minHeight: 720,
            display: ready ? 'block' : 'block',
          }}
        />
      </div>
    </div>
  );
};

// ------------------------------------------------------------------
// Build the print-styled HTML string (same shape as the portal's,
// with Noto Sans SC linked so Chinese aliases render correctly).
// ------------------------------------------------------------------
function buildPrintHtml(group, order) {
  const { vendor, lines } = group;
  const finalizer = window.SAMPLE_STAFF.find(s => s.id === order.finalizedByStaffId);
  const dateStr = toFmtDateTo(order.finalizedAt);
  const timeStr = toFmtTimeTo(order.finalizedAt);
  const totalUnits = lines.reduce((s, l) => s + (l.final || 0), 0);
  const safeVendor = vendor.name.replace(/[^a-z0-9\u4e00-\u9fff]+/gi, '_');
  const safeDate = (order.finalizedAt || '').slice(0, 10);
  const docTitle = `truck-order_${safeVendor}_${safeDate}`;

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

  return `<!doctype html>
<html lang="en"><head>
<meta charset="utf-8" />
<title>${escapeHtmlTo(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, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif; }
  .sheet { padding: 48px 32px; max-width: 7.5in; margin: 0 auto; }
  @media print { .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="sheet">
    <div class="header">
      <div>
        <div class="brand">Truck Order</div>
        <div class="title">${escapeHtmlTo(vendor.name)}</div>
      </div>
      <div class="meta">
        <div><b>${dateStr}</b> · ${timeStr}</div>
        ${finalizer ? `<div>Finalized by <b>${escapeHtmlTo(finalizer.name)}</b></div>` : ''}
        <div>Ref: ${escapeHtmlTo(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> ${escapeHtmlTo(order.note)}</div>` : ''}
  </div>
</body></html>`;
}

Object.assign(window, { TruckOrderSummaryView });
