
// ── Public Inventory Page ─────────────────────────────────────────────────────
const InventoryPage = ({ setCurrentPage }) => {
  const goContact = () => { setCurrentPage('contact'); window.scrollTo({ top: 0, behavior: 'smooth' }); };

  const [inventory, setInventory] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [filterType, setFilterType] = React.useState('all');
  const [filterCondition, setFilterCondition] = React.useState('all');
  const [filterStatus, setFilterStatus] = React.useState('available');
  const [selectedItem, setSelectedItem] = React.useState(null);

  React.useEffect(() => {
    (async () => {
      setLoading(true);
      if (SUPABASE_CONFIGURED) {
        const items = await supa.getInventory();
        setInventory(Array.isArray(items) ? items : MOCK_DATA.inventory);
      } else {
        await new Promise(r => setTimeout(r, 300));
        setInventory(MOCK_DATA.inventory);
      }
      setLoading(false);
    })();
  }, []);

  const getItemQuantity = (item) => Math.max(1, Number(item?.quantity) || 1);
  const types = ['all', ...new Set(MOCK_DATA.inventory.map(i => i.type))];
  const conditions = ['all', 'New', 'Premium Used', 'Cargo Worthy', 'Wind & Water Tight'];
  const statuses = ['all', 'available', 'incoming', 'reserved', 'sold'];

  const filtered = inventory.filter(item => {
    if (filterType !== 'all' && item.type !== filterType) return false;
    if (filterCondition !== 'all' && item.condition !== filterCondition) return false;
    if (filterStatus !== 'all' && item.status !== filterStatus) return false;
    return true;
  });

  const statusConfig = {
    available: { bg: '#F0FFF4', color: '#276749', dot: '#38A169', label: 'Available' },
    incoming:  { bg: '#EBF8FF', color: '#1E5F8C', dot: '#4A9FD4', label: 'Incoming' },
    reserved:  { bg: '#FFFBEB', color: '#856404', dot: '#D69E2E', label: 'Reserved' },
    sold:      { bg: '#F7FAFC', color: '#4A5568', dot: '#A0AEC0', label: 'Sold' },
  };

  const conditionColor = {
    'New':              '#4A9FD4',
    'Premium Used':     '#805AD5',
    'Cargo Worthy':     '#2E6FA3',
    'Wind & Water Tight': '#6B7E96',
  };

  const FilterBtn = ({ val, current, onChange, children }) => (
    <button onClick={() => onChange(val)} style={{
      padding: '7px 16px', border: `1.5px solid ${current === val ? '#1B2A4A' : '#E2E8F0'}`,
      background: current === val ? '#1B2A4A' : '#fff',
      color: current === val ? '#fff' : '#4A5568',
      borderRadius: '100px', cursor: 'pointer',
      fontFamily: 'Inter, sans-serif', fontSize: '13px', fontWeight: '600',
      transition: 'all 0.2s', whiteSpace: 'nowrap',
    }}>
      {children}
    </button>
  );

  const totalUnits = filtered.reduce((sum, item) => sum + getItemQuantity(item), 0);

  return (
    <div>
      {/* Hero */}
      <section style={{
        background: 'linear-gradient(160deg, #0F1D33 0%, #1B2A4A 100%)',
        padding: '140px 32px 72px',
      }}>
        <div style={{ maxWidth: '1200px', margin: '0 auto' }}>
          <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '700', letterSpacing: '0.12em', textTransform: 'uppercase', color: '#4A9FD4', display: 'block', marginBottom: '12px' }}>
            Current Inventory
          </span>
          <h1 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: 'clamp(36px, 5vw, 64px)', fontWeight: '800', color: '#fff', margin: '0 0 16px 0', lineHeight: '1.05' }}>
            Containers<br /><span style={{ color: '#4A9FD4' }}>In Stock Now</span>
          </h1>
          <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '17px', color: 'rgba(255,255,255,0.7)', lineHeight: '1.65', maxWidth: '520px', margin: '0 0 32px 0' }}>
            Browse our current stock of new and used shipping containers. All units are priced and ready for delivery across WA, OR, and ID.
          </p>
          <div style={{ display: 'flex', gap: '16px', flexWrap: 'wrap' }}>
            {[
              { n: inventory.filter(i => i.status === 'available').reduce((sum, item) => sum + getItemQuantity(item), 0), label: 'Available Now' },
              { n: inventory.filter(i => i.type.startsWith("20'")).reduce((sum, item) => sum + getItemQuantity(item), 0), label: "20' Units" },
              { n: inventory.filter(i => i.type.startsWith("40'")).reduce((sum, item) => sum + getItemQuantity(item), 0), label: "40' Units" },
            ].map(s => (
              <div key={s.label} style={{ background: 'rgba(74,159,212,0.12)', border: '1px solid rgba(74,159,212,0.25)', borderRadius: '8px', padding: '14px 20px', textAlign: 'center' }}>
                <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '28px', fontWeight: '800', color: '#4A9FD4' }}>{s.n}</div>
                <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', color: 'rgba(255,255,255,0.5)', fontWeight: '600', marginTop: '2px' }}>{s.label}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Filters + Grid */}
      <Section bg="#F4F6F8">
        {/* Filter bar */}
        <div style={{ background: '#fff', borderRadius: '12px', padding: '20px 24px', marginBottom: '28px', border: '1px solid #E8EDF2' }}>
          <div style={{ display: 'flex', gap: '24px', flexWrap: 'wrap', alignItems: 'center' }}>
            <div>
              <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700', color: '#9AAAB8', letterSpacing: '0.08em', textTransform: 'uppercase', display: 'block', marginBottom: '8px' }}>Size</span>
              <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                {types.map(t => <FilterBtn key={t} val={t} current={filterType} onChange={setFilterType}>{t === 'all' ? 'All Sizes' : t}</FilterBtn>)}
              </div>
            </div>
            <div style={{ width: '1px', height: '40px', background: '#EEF2F7', flexShrink: 0 }} className="divider-hide" />
            <div>
              <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700', color: '#9AAAB8', letterSpacing: '0.08em', textTransform: 'uppercase', display: 'block', marginBottom: '8px' }}>Condition</span>
              <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                {conditions.map(c => <FilterBtn key={c} val={c} current={filterCondition} onChange={setFilterCondition}>{c === 'all' ? 'All Conditions' : c}</FilterBtn>)}
              </div>
            </div>
            <div style={{ width: '1px', height: '40px', background: '#EEF2F7', flexShrink: 0 }} className="divider-hide" />
            <div>
              <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700', color: '#9AAAB8', letterSpacing: '0.08em', textTransform: 'uppercase', display: 'block', marginBottom: '8px' }}>Status</span>
              <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                {statuses.map(s => <FilterBtn key={s} val={s} current={filterStatus} onChange={setFilterStatus}>{s === 'all' ? 'All' : s.charAt(0).toUpperCase() + s.slice(1)}</FilterBtn>)}
              </div>
            </div>
          </div>
        </div>

        {/* Results count */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
          <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '14px', color: '#6B7E96', margin: 0 }}>
            {loading ? 'Loading…' : `${totalUnits} unit${totalUnits !== 1 ? 's' : ''} across ${filtered.length} listing${filtered.length !== 1 ? 's' : ''}`}
          </p>
        </div>

        {/* Grid */}
        {loading ? (
          <div style={{ textAlign: 'center', padding: '80px 0' }}>
            <div style={{ width: '40px', height: '40px', border: '3px solid #E2E8F0', borderTopColor: '#4A9FD4', borderRadius: '50%', animation: 'spin 0.8s linear infinite', margin: '0 auto' }} />
            <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
          </div>
        ) : filtered.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '80px 32px', background: '#fff', borderRadius: '12px', border: '1px solid #E8EDF2' }}>
            <div style={{ fontSize: '48px', marginBottom: '16px' }}>🔍</div>
            <h3 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '24px', fontWeight: '700', color: '#1B2A4A', margin: '0 0 10px 0' }}>No containers match your filters</h3>
            <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '14px', color: '#6B7E96', marginBottom: '24px' }}>Try adjusting your filters or contact us — we may have units arriving soon.</p>
            <CTAButton variant="primary" onClick={goContact}>Contact Us</CTAButton>
          </div>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: '24px' }}>
            {filtered.map(item => {
              const quantity = getItemQuantity(item);
              const sc = statusConfig[item.status] || statusConfig.available;
              const cc = conditionColor[item.condition] || '#6B7E96';
              return (
                <div key={item.id} onClick={() => setSelectedItem(item)} style={{
                  background: '#fff', borderRadius: '12px', border: '1px solid #E8EDF2',
                  overflow: 'hidden', cursor: 'pointer',
                  transition: 'all 0.25s',
                  opacity: item.status === 'sold' ? 0.65 : 1,
                }}
                onMouseEnter={e => { e.currentTarget.style.boxShadow = '0 8px 32px rgba(27,42,74,0.12)'; e.currentTarget.style.transform = 'translateY(-3px)'; }}
                onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'translateY(0)'; }}
                >
                  {/* Photo */}
                  <div style={{ position: 'relative', height: '200px', overflow: 'hidden' }}>
                    {item.photo_url ? (
                      <img src={item.photo_url} alt={item.type}
                        style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                    ) : (
                      <ImgPlaceholder label={item.type} height="200px" />
                    )}
                    {/* Status badge overlay */}
                    <div style={{ position: 'absolute', top: '12px', left: '12px', display: 'flex', gap: '6px' }}>
                      <span style={{
                        background: sc.bg, color: sc.color,
                        fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700',
                        padding: '4px 10px', borderRadius: '100px', letterSpacing: '0.04em',
                        display: 'flex', alignItems: 'center', gap: '5px',
                        boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
                      }}>
                        <span style={{ width: '6px', height: '6px', borderRadius: '50%', background: sc.dot, display: 'inline-block' }} />
                        {sc.label}
                      </span>
                      <span style={{
                        background: 'rgba(15,29,51,0.82)', color: '#fff',
                        fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700',
                        padding: '4px 10px', borderRadius: '100px', letterSpacing: '0.04em',
                        boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
                      }}>
                        Qty {quantity}
                      </span>
                    </div>
                    {/* Color swatch */}
                    <div style={{
                      position: 'absolute', top: '12px', right: '12px',
                      background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(4px)',
                      borderRadius: '6px', padding: '5px 10px',
                      fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '600', color: '#fff',
                    }}>
                      {item.color}
                    </div>
                  </div>

                  {/* Card body */}
                  <div style={{ padding: '20px 22px' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '10px' }}>
                      <div>
                        <h3 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '22px', fontWeight: '800', color: '#1B2A4A', margin: '0 0 4px 0' }}>{item.type}</h3>
                        <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                          <span style={{
                            fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700',
                            color: cc, background: cc + '18',
                            padding: '3px 10px', borderRadius: '100px',
                          }}>
                            {item.condition}
                          </span>
                          <span style={{
                            fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700',
                            color: '#1E5F8C', background: '#EBF8FF',
                            padding: '3px 10px', borderRadius: '100px',
                          }}>
                            Qty {quantity}
                          </span>
                        </div>
                      </div>
                      <div style={{ textAlign: 'right' }}>
                        <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '26px', fontWeight: '800', color: item.status === 'available' ? '#1B2A4A' : '#9AAAB8' }}>
                          ${Number(item.price).toLocaleString()}
                        </div>
                        <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', color: '#9AAAB8', fontWeight: '500' }}>
                          📍 {item.home_zip}
                        </div>
                      </div>
                    </div>

                    {item.notes && (
                      <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#4A5568', lineHeight: '1.5', margin: '0 0 16px 0', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
                        {item.notes}
                      </p>
                    )}

                    {item.status === 'available' && (
                      <button onClick={e => { e.stopPropagation(); setCurrentPage('contact'); window.scrollTo({ top: 0, behavior: 'smooth' }); }} style={{
                        width: '100%', background: '#1B2A4A', color: '#fff', border: 'none', cursor: 'pointer',
                        fontFamily: 'Inter, sans-serif', fontSize: '13px', fontWeight: '700',
                        padding: '11px', borderRadius: '6px', transition: 'background 0.2s',
                      }}
                      onMouseEnter={e => e.target.style.background = '#4A9FD4'}
                      onMouseLeave={e => e.target.style.background = '#1B2A4A'}>
                        Get a Quote on This Container →
                      </button>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </Section>

      {/* Detail modal */}
      {selectedItem && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', zIndex: 9000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '24px' }}
          onClick={e => e.target === e.currentTarget && setSelectedItem(null)}>
          <div style={{ background: '#fff', borderRadius: '16px', width: '100%', maxWidth: '640px', maxHeight: '90vh', overflowY: 'auto', boxShadow: '0 24px 64px rgba(0,0,0,0.35)' }}>
            {/* Photo */}
            {selectedItem.photo_url && (
              <img src={selectedItem.photo_url} alt={selectedItem.type}
                style={{ width: '100%', height: '280px', objectFit: 'cover', borderRadius: '16px 16px 0 0', display: 'block' }} />
            )}
            <div style={{ padding: '28px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '20px' }}>
                <div>
                  <h2 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '32px', fontWeight: '800', color: '#1B2A4A', margin: '0 0 6px 0' }}>{selectedItem.type}</h2>
                  <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                    <span style={{ background: (conditionColor[selectedItem.condition] || '#6B7E96') + '18', color: conditionColor[selectedItem.condition] || '#6B7E96', fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '700', padding: '4px 12px', borderRadius: '100px' }}>{selectedItem.condition}</span>
                    <span style={{ background: (statusConfig[selectedItem.status] || statusConfig.available).bg, color: (statusConfig[selectedItem.status] || statusConfig.available).color, fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '700', padding: '4px 12px', borderRadius: '100px' }}>{(statusConfig[selectedItem.status] || statusConfig.available).label}</span>
                  </div>
                </div>
                <button onClick={() => setSelectedItem(null)} style={{ background: '#F4F6F8', border: 'none', cursor: 'pointer', width: '36px', height: '36px', borderRadius: '50%', fontSize: '16px', color: '#6B7E96', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>✕</button>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '20px' }}>
                {[
                  { label: 'Price', value: `$${Number(selectedItem.price).toLocaleString()}` },
                  { label: 'Quantity', value: String(getItemQuantity(selectedItem)) },
                  { label: 'Color', value: selectedItem.color },
                  { label: 'Location ZIP', value: selectedItem.home_zip },
                ].map(f => (
                  <div key={f.label} style={{ background: '#F4F6F8', borderRadius: '8px', padding: '14px', textAlign: 'center' }}>
                    <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', color: '#9AAAB8', fontWeight: '700', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '4px' }}>{f.label}</div>
                    <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '20px', fontWeight: '800', color: '#1B2A4A' }}>{f.value}</div>
                  </div>
                ))}
              </div>

              {selectedItem.notes && (
                <div style={{ background: '#F9FAFB', border: '1px solid #E8EDF2', borderRadius: '8px', padding: '16px', marginBottom: '20px' }}>
                  <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '14px', color: '#4A5568', lineHeight: '1.6', margin: 0 }}>{selectedItem.notes}</p>
                </div>
              )}

              {selectedItem.status === 'available' && (
                <CTAButton variant="primary" style={{ width: '100%', justifyContent: 'center' }} onClick={() => { setSelectedItem(null); goContact(); }}>
                  Get a Quote on This Container →
                </CTAButton>
              )}
            </div>
          </div>
        </div>
      )}

      <QuoteCTABand setCurrentPage={setCurrentPage} />
    </div>
  );
};

Object.assign(window, { InventoryPage });
