// Side-by-side product comparison.
//
// Two pieces:
//   1. ComparisonTray — a floating pill at the bottom of the screen that
//      shows what's currently selected for comparison, with "Compare N →"
//      and "Clear" actions. Hidden when nothing is selected.
//   2. ComparisonModal — when triggered, renders a 2- or 3-column spec
//      table with the selected products side-by-side. Cells where the
//      values differ are highlighted so the reader can scan diffs fast.

const { useState: _ce, useEffect: _cu, useMemo: _cm } = React;

// Spec rows we surface in the comparison. Each row knows how to extract its
// value from a product object, formats it, and optionally provides a custom
// "equal" comparator (e.g. so price strings compare as numbers).
const COMPARE_ROWS = [
  { key: 'price',       label: 'Price',                get: p => p.price != null    ? `${p.currency === 'AUD' ? 'A$' : '$'}${p.price}` : '—', valueFor: p => p.price },
  { key: 'priceRange',  label: 'Price tier',           get: p => p.priceRange || p.price_range || '—' },
  { key: 'age',         label: 'Recommended ages',     get: p => formatCompareAge(p.ageMin, p.ageMax) },
  { key: 'category',    label: 'Category',             get: p => p.subcategory || p.category || '—' },
  { key: 'dimsOpen',    label: 'Dimensions (open)',    get: p => p.dimensionsUnfolded || p.size || '—' },
  { key: 'dimsFolded',  label: 'Dimensions (folded)',  get: p => p.dimensionsFolded || '—' },
  { key: 'weight',      label: 'Weight',               get: p => p.weight || '—' },
  { key: 'foldType',    label: 'Fold type',            get: p => p.foldType || '—' },
  { key: 'carBoot',     label: 'Fits small car boot',  get: p => p.fitsSmallCarBoot == null ? '—' : (p.fitsSmallCarBoot ? 'Yes' : 'No'), onlyWhen: p => p.category === 'travel' },
  { key: 'materials',   label: 'Materials',            get: p => p.materials || '—' },
  { key: 'madeIn',      label: 'Made in',              get: p => p.countryOfOrigin || p.madeIn || '—' },
  { key: 'warranty',    label: 'Warranty',             get: p => p.warranty || '—' },
  { key: 'why',         label: 'Why we love it',       get: p => p.why || p.description || '—', wrap: true },
];

function formatCompareAge(min, max) {
  if (min == null && max == null) return '—';
  if (min === -1) return 'Pre-baby';
  if (max == null) return `${min}+ mo`;
  if (max <= 12) return `${min}–${max} mo`;
  return `${Math.floor(min / 12)}–${Math.floor(max / 12)} yr`;
}

function valuesAllEqual(values) {
  if (values.length < 2) return true;
  const first = values[0];
  return values.every(v => v === first);
}

function ComparisonTray({ ids, productMap, onCompare, onRemove, onClear }) {
  if (!ids || ids.length === 0) return null;
  const items = ids.map(id => productMap[id]).filter(Boolean);
  if (items.length === 0) return null;
  return (
    <div className="compare-tray" role="region" aria-label="Comparison tray">
      <div className="compare-tray-items">
        {items.map(p => (
          <div key={p.id} className="compare-tray-item" title={p.name}>
            {p.img
              ? <img src={p.img} alt={p.name} />
              : <span className="compare-tray-empty">?</span>}
            <button type="button" className="compare-tray-remove" onClick={() => onRemove(p.id)} aria-label="Remove">×</button>
          </div>
        ))}
        {items.length < 3 && (
          <div className="compare-tray-slot">+</div>
        )}
      </div>
      <div className="compare-tray-actions">
        <button type="button" className="compare-tray-clear" onClick={onClear}>Clear</button>
        <button
          type="button"
          className="btn compare-tray-cta"
          disabled={items.length < 2}
          onClick={onCompare}
          style={{ width: 'auto', padding: '10px 18px' }}
        >
          <span className="btn-row">{items.length < 2 ? `Pick ${2 - items.length} more` : `Compare ${items.length}`}</span>
          <span className="arrow">→</span>
        </button>
      </div>
    </div>
  );
}

function ComparisonModal({ open, ids, productMap, onClose, onRemove }) {
  if (!open) return null;
  const items = (ids || []).map(id => productMap[id]).filter(Boolean);
  if (items.length === 0) return null;

  // Only include rows that have at least one non-empty value across the
  // selected products, AND where the row's `onlyWhen` (if any) matches at
  // least one product.
  const visibleRows = COMPARE_ROWS.filter(r => {
    if (r.onlyWhen && !items.some(r.onlyWhen)) return false;
    return items.some(p => {
      const v = r.get(p);
      return v && v !== '—';
    });
  });

  return (
    <>
      <div className="auth-scrim" onClick={onClose} />
      <div className="compare-modal">
        <div className="compare-modal-head">
          <div>
            <div className="thankyou-eyebrow">Comparing</div>
            <h2 className="thankyou-h">{items.length} products, side by side</h2>
          </div>
          <button type="button" className="thankyou-close" onClick={onClose} aria-label="Close">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6 L18 18 M18 6 L6 18"/></svg>
          </button>
        </div>

        <div className="compare-modal-body">
          <div className="compare-grid" style={{ gridTemplateColumns: `200px repeat(${items.length}, minmax(200px, 1fr))` }}>
            {/* Header row */}
            <div className="compare-cell compare-cell--corner" />
            {items.map(p => (
              <div key={p.id} className="compare-cell compare-cell--header">
                <button type="button" className="compare-header-remove" onClick={() => onRemove(p.id)} aria-label="Remove from comparison">×</button>
                <div className="compare-header-img">
                  {p.img ? <img src={p.img} alt={p.name} /> : null}
                </div>
                <div className="compare-header-brand">{p.brand}</div>
                <div className="compare-header-name">{p.name}</div>
              </div>
            ))}

            {/* Spec rows — values + diff highlighting */}
            {visibleRows.map(row => {
              const cells = items.map(p => row.get(p));
              const allEqual = valuesAllEqual(cells);
              return (
                <React.Fragment key={row.key}>
                  <div className="compare-cell compare-cell--rowlabel">{row.label}</div>
                  {cells.map((value, i) => (
                    <div
                      key={i}
                      className={`compare-cell${allEqual ? ' compare-cell--equal' : ' compare-cell--differs'}${row.wrap ? ' compare-cell--wrap' : ''}`}
                    >
                      {value}
                    </div>
                  ))}
                </React.Fragment>
              );
            })}
          </div>
        </div>
      </div>
    </>
  );
}

window.ComparisonTray = ComparisonTray;
window.ComparisonModal = ComparisonModal;
