// MobileMerchShop.jsx — mobile merch catalog: filter pills, single-column cards, sort, tier locks
const MobileMerchShop = ({ onOpen, onAdd, initialLine, user }) => {
  const [products, setProducts] = React.useState([]);

  React.useEffect(() => {
    var api = window.OBC_API || {};
    (api.getMerchProducts ? api.getMerchProducts() : Promise.resolve(window.OBC_PRODUCTS_MERCH || []))
      .then(setProducts);
  }, []);

  const lines = React.useMemo(() => window.OBC_GET_MERCH_LINES ? window.OBC_GET_MERCH_LINES(products) : [], [products]);

  const [activeLine, setActiveLine] = React.useState(initialLine || null);
  const [sort, setSort] = React.useState('default');
  const [sortOpen, setSortOpen] = React.useState(false);

  React.useEffect(() => {
    setActiveLine(initialLine || null);
  }, [initialLine]);

  const filtered = React.useMemo(() => {
    let out = products;
    if (activeLine) out = out.filter((p) => p.line === activeLine);
    if (sort === 'price-asc') out = [...out].sort((a, b) => a.price - b.price);
    else if (sort === 'price-desc') out = [...out].sort((a, b) => b.price - a.price);
    else if (sort === 'name') out = [...out].sort((a, b) => a.name.localeCompare(b.name));
    return out;
  }, [products, activeLine, sort]);

  const sortLabels = {
    'default': 'BY LINE',
    'name': 'A-Z',
    'price-asc': 'PRICE ASC',
    'price-desc': 'PRICE DESC',
  };

  const activeLineData = activeLine ? lines.find((l) => l.id === activeLine) : null;

  return (
    <div style={{ minHeight: '100vh', background: '#000', fontFamily: "'JetBrains Mono', monospace" }}>

      {/* ============================== HEADER ============================== */}
      <div style={{
        padding: '16px', borderBottom: '1px solid rgba(255,255,255,0.1)',
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <div style={{ flex: 1 }}>
          <h2 style={{
            fontSize: 20, letterSpacing: '0.04em', textTransform: 'uppercase',
            fontWeight: 800, color: '#FFF', margin: 0,
          }}>
            ~/merch
          </h2>
          <div style={{
            fontSize: 10, color: '#A0A0A0', letterSpacing: '0.18em', marginTop: 4,
          }}>
            {filtered.length} / {products.length} SKUs
          </div>
        </div>

        {/* SORT TOGGLE */}
        <div style={{ position: 'relative' }}>
          <button
            onClick={() => setSortOpen(!sortOpen)}
            style={{
              background: 'transparent', border: '1px solid rgba(255,255,255,0.2)',
              color: '#B8B8B8', padding: '8px 12px', fontFamily: 'inherit',
              fontSize: 10, letterSpacing: '0.12em', cursor: 'pointer', minHeight: 44,
            }}
          >
            SORT: {sortLabels[sort]}
          </button>
          {sortOpen && (
            <div style={{
              position: 'absolute', top: '100%', right: 0, marginTop: 4,
              background: '#0A0A0A', border: '1px solid rgba(255,255,255,0.2)',
              zIndex: 20, minWidth: 140,
            }}>
              {Object.entries(sortLabels).map(([id, label]) => (
                <button
                  key={id}
                  onClick={() => { setSort(id); setSortOpen(false); }}
                  style={{
                    display: 'block', width: '100%', textAlign: 'left',
                    background: sort === id ? '#00FF41' : 'transparent',
                    color: sort === id ? '#000' : '#B8B8B8',
                    border: 'none', borderBottom: '1px solid rgba(255,255,255,0.08)',
                    padding: '12px 14px', fontFamily: 'inherit',
                    fontSize: 10, letterSpacing: '0.12em', cursor: 'pointer',
                    minHeight: 44,
                  }}
                >
                  {sort === id ? '[*] ' : '[ ] '}{label}
                </button>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* ============================== FILTER PILLS ============================== */}
      <div style={{
        padding: '12px 16px',
        display: 'flex', gap: 8, overflowX: 'auto', WebkitOverflowScrolling: 'touch',
        borderBottom: '1px solid rgba(255,255,255,0.06)',
      }}>
        <MerchPill
          label="ALL"
          active={!activeLine}
          color="#00FF41"
          onClick={() => setActiveLine(null)}
        />
        {lines.map((l) => (
          <MerchPill
            key={l.id}
            label={l.label.split('/')[0].trim()}
            active={activeLine === l.id}
            color={l.color}
            onClick={() => setActiveLine(activeLine === l.id ? null : l.id)}
          />
        ))}
      </div>

      {/* ============================== ACTIVE FILTER BANNER ============================== */}
      {activeLineData && (
        <div style={{
          margin: '12px 16px 0', padding: '10px 14px',
          background: `${activeLineData.color}14`, border: `1px solid ${activeLineData.color}44`,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <span style={{
            fontSize: 11, color: activeLineData.color, letterSpacing: '0.12em', fontWeight: 700,
          }}>
            $ ./merch --line={activeLineData.id}
          </span>
          <button
            onClick={() => setActiveLine(null)}
            style={{
              background: 'transparent', border: 'none', color: '#FF3344',
              fontFamily: 'inherit', fontSize: 10, letterSpacing: '0.12em',
              cursor: 'pointer', padding: '4px 8px', minHeight: 44,
              display: 'grid', placeItems: 'center',
            }}
          >
            [X]
          </button>
        </div>
      )}

      {/* ============================== PRODUCT LIST ============================== */}
      <div style={{ padding: '12px 16px 80px' }}>
        {filtered.length === 0 ? (
          <div style={{
            padding: '48px 16px', textAlign: 'center',
            border: '1px dashed rgba(255,255,255,0.2)',
            marginTop: 12,
          }}>
            <div style={{ color: '#FF3344', fontSize: 14, letterSpacing: '0.18em', marginBottom: 10 }}>
              {'>'} no results
            </div>
            <div style={{ color: '#A0A0A0', fontSize: 12 }}>
              // loosen filters or{' '}
              <span
                style={{ color: '#00FF41', cursor: 'pointer' }}
                onClick={() => setActiveLine(null)}
              >
                ./reset
              </span>
            </div>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 4 }}>
            {filtered.map((p) => (
              <MobileMerchCard key={p.id} p={p} onOpen={onOpen} onAdd={onAdd} user={user} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

const MobileMerchCard = ({ p, onOpen, onAdd, user }) => {
  const [selectedSize, setSelectedSize] = React.useState(p.sizes ? p.sizes[0] : null);

  const sku = `OBC-MERCH-${p.id}`;
  const mitre = p.mitre || '';
  const spend = (user && user.tierData && user.tierData.lifetime_spend) || 0;
  const helpers = window.OBC_TIER_HELPERS || {};
  const tiers = window.OBC_TIERS || [];

  const locked = p.minTier != null && helpers.canPurchaseMerch && !helpers.canPurchaseMerch(spend, p.minTier);
  const requiredTierName = p.minTier != null && tiers[p.minTier] ? tiers[p.minTier].name : 'UNKNOWN';

  return (
    <div
      onClick={() => onOpen(p)}
      style={{
        background: '#0A0A0A', border: '1px solid rgba(255,255,255,0.15)',
        cursor: 'pointer', position: 'relative', overflow: 'hidden',
      }}
    >
      {/* HEADER STRIP: SKU + MITRE */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8,
        padding: '8px 14px', borderBottom: '1px solid rgba(255,255,255,0.1)',
        background: '#050505',
      }}>
        <span style={{
          width: 7, height: 7, borderRadius: '50%', background: p.accent,
          boxShadow: `0 0 6px ${p.accent}`, flexShrink: 0,
        }}></span>
        <span style={{
          fontSize: 9, letterSpacing: '0.18em', color: p.accent, fontWeight: 700,
        }}>
          {sku}
        </span>
        <span style={{
          marginLeft: 'auto', fontSize: 9, letterSpacing: '0.15em', color: '#6E6E6E',
        }}>
          {mitre}
        </span>
      </div>

      {/* NAME + TYPE */}
      <div style={{ padding: '12px 14px 8px' }}>
        <div style={{
          fontSize: 18, fontWeight: 800, color: p.accent,
          letterSpacing: '0.02em', textTransform: 'uppercase',
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        }}>
          {p.name}
        </div>
        <div style={{
          fontSize: 10, letterSpacing: '0.2em', color: '#A0A0A0',
          fontWeight: 700, marginTop: 4,
        }}>
          {p.type}
        </div>
      </div>

      {/* IMAGE PLACEHOLDER */}
      <div style={{
        margin: '0 14px', height: 120,
        background: `${p.accent}1A`, border: `1px solid ${p.accent}44`,
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        position: 'relative', overflow: 'hidden',
      }}>
        <div style={{ fontSize: 48, opacity: 0.3, lineHeight: 1, color: p.accent, pointerEvents: 'none' }}>
          {p.glyph}
        </div>
        <div style={{
          fontSize: 9, letterSpacing: '0.2em', color: '#6E6E6E',
          fontWeight: 600, marginTop: 6,
        }}>
          // IMAGE PENDING
        </div>
      </div>

      {/* MATERIAL + WEIGHT */}
      <div style={{
        padding: '8px 14px 0', fontSize: 10, letterSpacing: '0.1em',
        color: '#6E6E6E',
      }}>
        {p.material}{p.weight ? ` · ${p.weight}` : ''}
      </div>

      {/* SIZE CHIPS */}
      {p.sizes && p.sizes.length > 0 && (
        <div
          onClick={(e) => e.stopPropagation()}
          style={{ padding: '8px 14px 0', display: 'flex', gap: 4, flexWrap: 'wrap' }}
        >
          {p.sizes.map((s) => (
            <button
              key={s}
              onClick={() => setSelectedSize(s)}
              style={{
                padding: '4px 8px', fontSize: 9, fontWeight: 700, letterSpacing: '0.08em',
                fontFamily: "'JetBrains Mono', monospace", cursor: 'pointer', borderRadius: 2,
                background: selectedSize === s ? p.accent : 'transparent',
                color: selectedSize === s ? '#000' : '#6E6E6E',
                border: `1px solid ${selectedSize === s ? p.accent : 'rgba(255,255,255,0.12)'}`,
                minHeight: 28,
              }}
            >
              {s}
            </button>
          ))}
        </div>
      )}

      {/* PRICE + ADD BUTTON */}
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          padding: '10px 14px 12px', display: 'flex', alignItems: 'center',
          justifyContent: 'space-between',
        }}
      >
        <span style={{ fontSize: 22, fontWeight: 800, color: '#FFF' }}>
          ${p.price}
        </span>
        {locked ? (
          <span style={{
            padding: '8px 14px', border: '1px solid #FF3344', color: '#FF3344',
            fontSize: 10, fontWeight: 800, letterSpacing: '0.1em',
            fontFamily: "'JetBrains Mono', monospace",
          }}>
            LOCKED — {requiredTierName}
          </span>
        ) : (
          <button
            onClick={() => onAdd(p, 1, { size: selectedSize, color: p.colors ? p.colors[0] : null, customizations: {} })}
            style={{
              background: p.accent, color: '#000', border: 'none',
              padding: '8px 16px', fontFamily: "'JetBrains Mono', monospace",
              fontSize: 11, fontWeight: 800, letterSpacing: '0.1em',
              cursor: 'pointer', minHeight: 38, borderRadius: 2,
            }}
          >
            [ADD]
          </button>
        )}
      </div>

      {/* TIER LOCK OVERLAY */}
      {locked && (
        <div style={{
          position: 'absolute', inset: 0,
          background: 'rgba(0,0,0,0.65)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          zIndex: 5,
        }}>
          <div style={{
            padding: '10px 16px', border: '1px solid #FF3344', color: '#FF3344',
            fontSize: 11, letterSpacing: '0.12em', fontWeight: 700,
            fontFamily: "'JetBrains Mono', monospace",
          }}>
            LOCKED — {requiredTierName}
          </div>
        </div>
      )}
    </div>
  );
};

const MerchPill = ({ label, active, color, onClick }) => (
  <button
    onClick={onClick}
    style={{
      flexShrink: 0, padding: '10px 16px',
      background: active ? color : 'transparent',
      color: active ? '#000' : (color || '#B8B8B8'),
      border: '1px solid ' + (active ? color : 'rgba(255,255,255,0.18)'),
      fontFamily: "'JetBrains Mono', monospace",
      fontSize: 10, fontWeight: 700, letterSpacing: '0.1em',
      cursor: 'pointer', borderRadius: 2, whiteSpace: 'nowrap',
      minHeight: 44,
    }}
  >
    {label}
  </button>
);

window.MobileMerchShop = MobileMerchShop;
