// MobileShop.jsx — mobile catalog: inline filter pills, single-column cards, sort toggle
const MobileShop = ({ onOpen, onAdd, onBack, initialLine }) => {
  const [products, setProducts] = React.useState([]);
  const lines = window.OBC_LINES || [];

  React.useEffect(() => { window.OBC_API.getAllProducts().then(setProducts); }, []);

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

  // Sync when initialLine prop changes (e.g., navigating from home line cards)
  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': 'DEFAULT',
    '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,
      }}>
        {onBack && (
          <button
            onClick={onBack}
            style={{
              background: 'transparent', border: '1px solid rgba(255,255,255,0.2)',
              color: '#B8B8B8', padding: '6px 10px', fontFamily: 'inherit',
              fontSize: 10, letterSpacing: '0.15em', cursor: 'pointer', minHeight: 44,
              minWidth: 44, display: 'grid', placeItems: 'center',
            }}
          >
            {'<-'}
          </button>
        )}
        <div style={{ flex: 1 }}>
          <h2 style={{
            fontSize: 20, letterSpacing: '0.04em', textTransform: 'uppercase',
            fontWeight: 800, color: '#FFF', margin: 0,
          }}>
            ~/shop
          </h2>
          <div style={{
            fontSize: 10, color: '#6E6E6E', 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', overflowX: 'auto', WebkitOverflowScrolling: 'touch',
        display: 'flex', gap: 8, borderBottom: '1px solid rgba(255,255,255,0.06)',
      }}>
        <MobilePill
          label="ALL"
          active={!activeLine}
          color="#00FF41"
          onClick={() => setActiveLine(null)}
        />
        {lines.map((l) => (
          <MobilePill
            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,
          }}>
            $ ./shop --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: '#6E6E6E', 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) => (
              <MobileProductCard key={p.id} p={p} onOpen={onOpen} onAdd={onAdd} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

// Product card — shows art, grind toggle, quick-add button
const MobileProductCard = ({ p, onOpen, onAdd }) => {
  const [grind, setGrind] = React.useState('WHOLE BEAN');

  const strengthBar = (level, max) => {
    const blocks = [];
    for (let i = 1; i <= max; i++) {
      blocks.push(
        React.createElement('span', {
          key: i,
          style: {
            display: 'inline-block', width: 6, height: 10,
            background: i <= level ? p.accent : 'rgba(255,255,255,0.12)',
            marginRight: 2,
          },
        })
      );
    }
    return blocks;
  };

  return (
    <div
      onClick={() => onOpen(p)}
      style={{
        background: '#0A0A0A', border: '1px solid rgba(255,255,255,0.15)',
        cursor: 'pointer',
      }}
    >
      {/* TOP ROW: glyph + name + price */}
      <div style={{
        padding: '14px 14px 10px', display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <div style={{
          width: 44, height: 44, border: '1px solid ' + p.accent,
          color: p.accent, display: 'grid', placeItems: 'center',
          fontSize: 20, fontWeight: 800, flexShrink: 0,
        }}>
          {p.glyph}
        </div>

        <div style={{ flex: 1, minWidth: 0 }}>
          <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={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 5 }}>
            <span style={{ fontSize: 12, color: '#6E6E6E', letterSpacing: '0.12em' }}>
              {p.roast.length > 18 ? p.roast.slice(0, 18) + '..' : p.roast}
            </span>
            <span style={{ display: 'flex', alignItems: 'center' }}>
              {strengthBar(p.strength, 5)}
            </span>
          </div>
        </div>

        <span style={{ fontSize: 22, fontWeight: 800, color: '#FFF', flexShrink: 0 }}>
          ${p.price}
        </span>
      </div>

      {/* BOTTOM ROW: grind toggle + add button */}
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          padding: '0 14px 12px', display: 'flex', alignItems: 'center', gap: 8,
        }}
      >
        <div style={{ display: 'flex', gap: 4, flex: 1 }}>
          {['WHOLE BEAN', 'GROUND'].map((g) => (
            <button
              key={g}
              onClick={() => setGrind(g)}
              style={{
                padding: '7px 12px',
                background: grind === g ? p.accent : 'transparent',
                color: grind === g ? '#000' : '#6E6E6E',
                border: '1px solid ' + (grind === g ? p.accent : 'rgba(255,255,255,0.12)'),
                fontFamily: "'JetBrains Mono', monospace",
                fontSize: 10, fontWeight: 700, letterSpacing: '0.08em',
                cursor: 'pointer', borderRadius: 2, minHeight: 34,
              }}
            >
              {g === 'WHOLE BEAN' ? 'BEAN' : 'GND'}
            </button>
          ))}
        </div>
        <button
          onClick={() => onAdd(p, 1, grind)}
          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>
    </div>
  );
};

// Filter pill button
const MobilePill = ({ 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.MobileShop = MobileShop;
