
// ── Admin Inventory Tab ───────────────────────────────────────────────────────
// Rendered inside AdminDashboard as the "Inventory" tab content.

const AdminInventoryTab = ({ inventory, setInventory, pricing, setPricing, onSavePricing }) => {
  const [showForm, setShowForm] = React.useState(false);
  const [editItem, setEditItem] = React.useState(null);
  const [filterStatus, setFilterStatus] = React.useState('all');
  const [saving, setSaving] = React.useState(false);
  const [marginSaving, setMarginSaving] = React.useState(false);
  const [marginMsg, setMarginMsg] = React.useState('');

  // Margin settings — stored in pricing_config with margin_ prefix
  const [defaultMargin, setDefaultMargin] = React.useState(
    pricing?.default_margin || pricing?.margin_default || '30'
  );
  const [minMargin, setMinMargin] = React.useState(
    pricing?.margin_min || '15'
  );
  const [targetMargin, setTargetMargin] = React.useState(
    pricing?.margin_target || '35'
  );

  const filtered = filterStatus === 'all' ? inventory : inventory.filter(i => i.status === filterStatus);
  const getItemQuantity = (item) => Math.max(1, Number(item?.quantity) || 1);

  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 getMarginColor = (margin) => {
    const m = Number(margin);
    const min = Number(minMargin);
    const target = Number(targetMargin);
    if (m < min) return '#E53E3E';
    if (m >= target) return '#38A169';
    return '#D69E2E';
  };

  const handleDelete = async (id) => {
    if (!window.confirm('Delete this container from inventory?')) return;
    if (SUPABASE_CONFIGURED) await supa.deleteInventoryItem(id);
    setInventory(inv => inv.filter(i => i.id !== id));
  };

  const saveMargins = async () => {
    setMarginSaving(true);
    const data = { default_margin: defaultMargin, margin_min: minMargin, margin_target: targetMargin };
    if (SUPABASE_CONFIGURED) await supa.savePricing(data);
    await new Promise(r => setTimeout(r, 300));
    setMarginSaving(false);
    setMarginMsg('✓ Margin settings saved');
    setTimeout(() => setMarginMsg(''), 3000);
  };

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

  // Summary stats
  const totalValue = inventory.filter(i => i.status !== 'sold').reduce((s, i) => s + (Number(i.price) * getItemQuantity(i)), 0);
  const totalCost = inventory.filter(i => i.status !== 'sold').reduce((s, i) => s + (Number(i.cost) * getItemQuantity(i)), 0);
  const avgMargin = inventory.length > 0
    ? Math.round(
        inventory.reduce((s, i) => s + (Number(i.margin || ((i.price - i.cost) / i.price * 100)) * getItemQuantity(i)), 0) /
        inventory.reduce((s, i) => s + getItemQuantity(i), 0)
      )
    : 0;

  return (
    <div>
      {/* Inventory stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '16px', marginBottom: '24px' }}>
        {[
          { label: 'Available', value: inventory.filter(i => i.status === 'available').reduce((s, i) => s + getItemQuantity(i), 0), color: '#38A169' },
          { label: 'Incoming', value: inventory.filter(i => i.status === 'incoming').reduce((s, i) => s + getItemQuantity(i), 0), color: '#4A9FD4' },
          { label: 'Reserved', value: inventory.filter(i => i.status === 'reserved').reduce((s, i) => s + getItemQuantity(i), 0), color: '#D69E2E' },
          { label: 'Total Inventory Value', value: `$${totalValue.toLocaleString()}`, color: '#4A9FD4' },
          { label: 'Avg. Margin', value: `${avgMargin}%`, color: getMarginColor(avgMargin) },
        ].map(s => (
          <div key={s.label} style={{ background: '#fff', borderRadius: '10px', padding: '18px 20px', border: '1px solid #E8EDF2' }}>
            <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '28px', fontWeight: '800', color: s.color, lineHeight: 1 }}>{s.value}</div>
            <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', color: '#6B7E96', fontWeight: '600', marginTop: '4px' }}>{s.label}</div>
          </div>
        ))}
      </div>

      {/* Margin settings */}
      <div style={{ background: '#fff', borderRadius: '12px', border: '1px solid #E8EDF2', padding: '24px', marginBottom: '24px' }}>
        <h3 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '20px', fontWeight: '700', color: '#1B2A4A', margin: '0 0 16px 0' }}>
          📊 Profit Margin Settings
        </h3>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '16px', marginBottom: '16px' }}>
          {[
            { label: 'Default Margin %', val: defaultMargin, set: setDefaultMargin, hint: 'Auto-filled when adding new containers' },
            { label: 'Minimum Acceptable %', val: minMargin, set: setMinMargin, hint: 'Red warning shown below this' },
            { label: 'Target Margin %', val: targetMargin, set: setTargetMargin, hint: 'Green indicator at or above this' },
          ].map(f => (
            <div key={f.label}>
              <label style={{ display: 'block', fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>{f.label}</label>
              <div style={{ display: 'flex', alignItems: 'center', border: '1.5px solid #E2E8F0', borderRadius: '8px', overflow: 'hidden' }}>
                <input type="number" value={f.val} onChange={e => f.set(e.target.value)} step="1" min="0" max="100"
                  style={{ flex: 1, border: 'none', outline: 'none', padding: '11px 14px', fontFamily: 'Inter, sans-serif', fontSize: '15px', fontWeight: '700', color: '#1B2A4A' }}
                  onFocus={e => e.target.parentElement.style.borderColor = '#4A9FD4'}
                  onBlur={e => e.target.parentElement.style.borderColor = '#E2E8F0'}
                />
                <span style={{ padding: '11px 14px 11px 4px', fontFamily: 'Inter, sans-serif', fontSize: '15px', fontWeight: '700', color: '#9AAAB8' }}>%</span>
              </div>
              <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', color: '#9AAAB8', marginTop: '4px' }}>{f.hint}</p>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '14px' }}>
          <button onClick={saveMargins} disabled={marginSaving} style={{ background: marginSaving ? '#9AAAB8' : '#1B2A4A', color: '#fff', border: 'none', borderRadius: '8px', padding: '10px 24px', cursor: marginSaving ? 'not-allowed' : 'pointer', fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '700', transition: 'background 0.2s' }}
            onMouseEnter={e => { if (!marginSaving) e.target.style.background = '#4A9FD4'; }}
            onMouseLeave={e => { if (!marginSaving) e.target.style.background = '#1B2A4A'; }}>
            {marginSaving ? 'Saving…' : 'Save Margin Settings'}
          </button>
          {marginMsg && <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#38A169', fontWeight: '600' }}>{marginMsg}</span>}
        </div>
      </div>

      {/* Inventory table header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px', flexWrap: 'wrap', gap: '12px' }}>
        <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
          {[['all','All'], ['available','Available'], ['incoming','Incoming'], ['reserved','Reserved'], ['sold','Sold']].map(([val, label]) => (
            <FilterBtn key={val} val={val} label={label} />
          ))}
        </div>
        <button onClick={() => { setEditItem(null); setShowForm(true); }} style={{
          background: '#1B2A4A', color: '#fff', border: 'none', borderRadius: '8px',
          padding: '11px 24px', cursor: 'pointer',
          fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '700', transition: 'background 0.2s',
        }}
        onMouseEnter={e => e.target.style.background = '#4A9FD4'}
        onMouseLeave={e => e.target.style.background = '#1B2A4A'}>
          + Add Container
        </button>
      </div>

      {/* Inventory list */}
      <div style={{ background: '#fff', borderRadius: '12px', border: '1px solid #E8EDF2', overflow: 'hidden' }}>
        {filtered.length === 0 ? (
          <div style={{ padding: '48px', textAlign: 'center', color: '#9AAAB8', fontFamily: 'Inter, sans-serif' }}>
            No containers found. Click "+ Add Container" to add inventory.
          </div>
        ) : (
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: '900px' }}>
              <thead>
                <tr style={{ background: '#F9FAFB' }}>
                  {['Photo', 'Type', 'Condition', 'Qty', 'Color', 'ZIP', 'Cost', 'Price', 'Margin', 'Status', 'Actions'].map(h => (
                    <th key={h} style={{ padding: '12px 14px', fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', textAlign: 'left', borderBottom: '1px solid #EEF2F7', whiteSpace: 'nowrap' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {filtered.map((item, idx) => {
                  const quantity = getItemQuantity(item);
                  const margin = item.margin !== undefined ? Number(item.margin) : Math.round((item.price - item.cost) / item.price * 100);
                  const sc = statusConfig[item.status] || statusConfig.available;
                  return (
                    <tr key={item.id} style={{ background: idx % 2 === 0 ? '#fff' : '#FAFBFC', borderBottom: '1px solid #F0F4F8' }}>
                      {/* Photo thumbnail */}
                      <td style={{ padding: '10px 14px' }}>
                        {item.photo_url ? (
                          <img src={item.photo_url} alt="" style={{ width: '56px', height: '40px', objectFit: 'cover', borderRadius: '5px', display: 'block' }} />
                        ) : (
                          <div style={{ width: '56px', height: '40px', background: '#EEF2F7', borderRadius: '5px', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '18px' }}>📦</div>
                        )}
                      </td>
                      <td style={{ padding: '10px 14px', fontFamily: '"Barlow Condensed", sans-serif', fontSize: '18px', fontWeight: '700', color: '#1B2A4A', whiteSpace: 'nowrap' }}>{item.type}</td>
                      <td style={{ padding: '10px 14px', fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#4A5568', whiteSpace: 'nowrap' }}>{item.condition}</td>
                      <td style={{ padding: '10px 14px', fontFamily: '"Barlow Condensed", sans-serif', fontSize: '20px', fontWeight: '700', color: '#1B2A4A' }}>{quantity}</td>
                      <td style={{ padding: '10px 14px' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                          <div style={{ width: '14px', height: '14px', borderRadius: '3px', background: item.color?.toLowerCase() === 'beige' ? '#E8D5B0' : item.color?.toLowerCase() === 'gray' ? '#9AAAB8' : item.color?.toLowerCase() === 'green' ? '#68D391' : item.color?.toLowerCase() === 'blue' ? '#4A9FD4' : item.color?.toLowerCase() === 'tan' ? '#C9A96E' : '#CBD5E0', border: '1px solid rgba(0,0,0,0.1)' }} />
                          <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#4A5568' }}>{item.color}</span>
                        </div>
                      </td>
                      <td style={{ padding: '10px 14px', fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#4A5568' }}>{item.home_zip}</td>
                      <td style={{ padding: '10px 14px', fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '600', color: '#4A5568' }}>${Number(item.cost).toLocaleString()}</td>
                      <td style={{ padding: '10px 14px', fontFamily: '"Barlow Condensed", sans-serif', fontSize: '18px', fontWeight: '700', color: '#1B2A4A' }}>${Number(item.price).toLocaleString()}</td>
                      <td style={{ padding: '10px 14px' }}>
                        <span style={{
                          fontFamily: 'Inter, sans-serif', fontSize: '13px', fontWeight: '700',
                          color: getMarginColor(margin),
                          background: getMarginColor(margin) + '18',
                          padding: '3px 10px', borderRadius: '100px',
                        }}>
                          {margin}%
                        </span>
                      </td>
                      <td style={{ padding: '10px 14px' }}>
                        <span style={{ background: sc.bg, color: sc.color, fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700', padding: '3px 10px', borderRadius: '100px', display: 'inline-flex', alignItems: 'center', gap: '5px' }}>
                          <span style={{ width: '6px', height: '6px', borderRadius: '50%', background: sc.dot }} />
                          {sc.label}
                        </span>
                      </td>
                      <td style={{ padding: '10px 14px' }}>
                        <div style={{ display: 'flex', gap: '6px' }}>
                          <button onClick={() => { setEditItem(item); setShowForm(true); }} style={{ background: 'none', border: '1px solid #E2E8F0', borderRadius: '6px', padding: '5px 12px', cursor: 'pointer', fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '600', color: '#4A9FD4', transition: 'all 0.2s' }}
                            onMouseEnter={e => e.target.style.borderColor = '#4A9FD4'}
                            onMouseLeave={e => e.target.style.borderColor = '#E2E8F0'}>
                            Edit
                          </button>
                          <button onClick={() => handleDelete(item.id)} style={{ background: 'none', border: '1px solid #E2E8F0', borderRadius: '6px', padding: '5px 12px', cursor: 'pointer', fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '600', color: '#E53E3E', transition: 'all 0.2s' }}
                            onMouseEnter={e => e.target.style.borderColor = '#E53E3E'}
                            onMouseLeave={e => e.target.style.borderColor = '#E2E8F0'}>
                            Delete
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Add/Edit modal */}
      {showForm && (
        <Modal title={editItem ? 'Edit Container' : 'Add Container to Inventory'} onClose={() => { setShowForm(false); setEditItem(null); }}>
          <InventoryItemForm
            item={editItem}
            defaultMargin={defaultMargin}
            saving={saving}
            onSave={async (data) => {
              setSaving(true);
              try {
                const numericPrice = Number(data.price);
                const numericCost = Number(data.cost);
                const numericQuantity = Math.max(1, Number(data.quantity) || 1);
                const margin = numericPrice > 0
                  ? Math.round(((numericPrice - numericCost) / numericPrice) * 100)
                  : 0;
                const dbData = {
                  ...data,
                  quantity: numericQuantity,
                  cost: numericCost,
                  price: numericPrice,
                };
                const localData = { ...dbData, margin };

                if (editItem) {
                  let savedItem = null;
                  if (SUPABASE_CONFIGURED) {
                    const result = await supa.updateInventoryItem(editItem.id, dbData);
                    savedItem = Array.isArray(result) ? result[0] : null;
                  }
                  setInventory(inv => inv.map(i => i.id === editItem.id ? { ...i, ...localData, ...(savedItem || {}) } : i));
                } else {
                  let savedItem = null;
                  if (SUPABASE_CONFIGURED) {
                    const result = await supa.saveInventoryItem(dbData);
                    savedItem = Array.isArray(result) ? result[0] : null;
                  }
                  const newItem = savedItem || { ...localData, id: String(Date.now()), created_at: new Date().toISOString() };
                  setInventory(inv => [{ ...newItem, margin: savedItem?.margin ?? margin }, ...inv]);
                }

                setShowForm(false);
                setEditItem(null);
              } catch (error) {
                window.alert(error?.message || 'Unable to save this inventory item.');
              } finally {
                setSaving(false);
              }
            }}
          />
        </Modal>
      )}
    </div>
  );
};

// ── Inventory Item Form ───────────────────────────────────────────────────────
const InventoryItemForm = ({ item, defaultMargin, saving, onSave }) => {
  const statusOptions = [
    ['available', 'Available'],
    ['incoming', 'Incoming'],
    ['reserved', 'Reserved'],
    ['sold', 'Sold'],
  ];
  const [form, setForm] = React.useState({
    type:      item?.type      || "20' Standard",
    condition: item?.condition || 'New',
    quantity:  String(Math.max(1, Number(item?.quantity) || 1)),
    color:     item?.color     || 'Beige',
    home_zip:  item?.home_zip  || '98001',
    status:    item?.status    || 'available',
    cost:      item?.cost      || '',
    price:     item?.price     || '',
    photo_url: item?.photo_url || '',
    notes:     item?.notes     || '',
  });
  const [photoUploading, setPhotoUploading] = React.useState(false);
  const [photoUploadError, setPhotoUploadError] = React.useState('');
  const [dragActive, setDragActive] = React.useState(false);
  const fileInputRef = React.useRef(null);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  // Auto-calculate price from cost + default margin
  const autoPrice = React.useMemo(() => {
    if (!form.cost) return '';
    const margin = Number(defaultMargin) / 100;
    return Math.round(Number(form.cost) / (1 - margin));
  }, [form.cost, defaultMargin]);

  const margin = form.cost && form.price
    ? Math.round((form.price - form.cost) / form.price * 100)
    : null;

  const fld = { fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '600', color: '#1B2A4A', border: '1.5px solid #E2E8F0', borderRadius: '8px', padding: '10px 14px', width: '100%', boxSizing: 'border-box', outline: 'none', transition: 'border-color 0.2s' };
  const Label = ({ children, hint }) => (
    <label style={{ display: 'block', fontSize: '11px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '5px' }}>
      {children} {hint && <span style={{ textTransform: 'none', letterSpacing: 0, fontWeight: '400', color: '#9AAAB8' }}>{hint}</span>}
    </label>
  );
  const uploadPhoto = async (file) => {
    if (!file) return;
    if (!file.type || !file.type.startsWith('image/')) {
      setPhotoUploadError('Please choose a PNG, JPG, WEBP, or other image file.');
      return;
    }
    if (!SUPABASE_CONFIGURED) {
      setPhotoUploadError('Supabase storage is not configured for photo uploads.');
      return;
    }

    setPhotoUploading(true);
    setPhotoUploadError('');
    try {
      const uploadedUrl = await supa.uploadInventoryPhoto(file);
      set('photo_url', uploadedUrl);
    } catch (error) {
      setPhotoUploadError(error?.message || 'Unable to upload photo.');
    } finally {
      setPhotoUploading(false);
      setDragActive(false);
    }
  };

  const handleFileSelection = async (event) => {
    const file = event.target.files?.[0];
    await uploadPhoto(file);
    if (event.target) event.target.value = '';
  };

  const uploadBoxBorder = dragActive ? '#4A9FD4' : '#D7E2EC';

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '14px' }}>
      {/* Row 1: Type + Condition */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
        <div>
          <Label>Container Type</Label>
          <select value={form.type} onChange={e => set('type', e.target.value)} style={{ ...fld, cursor: 'pointer' }}>
            {["20' Standard", "40' High Cube", "20' Double Door", "40' Double Door", "40' Open Side", "40' Flat Rack", "40' Open Top", "40' Reefer"].map(t => <option key={t}>{t}</option>)}
          </select>
        </div>
        <div>
          <Label>Condition</Label>
          <select value={form.condition} onChange={e => set('condition', e.target.value)} style={{ ...fld, cursor: 'pointer' }}>
            {['New', 'Premium Used', 'Cargo Worthy', 'Wind & Water Tight'].map(c => <option key={c}>{c}</option>)}
          </select>
        </div>
      </div>

      {/* Row 2: Color + Quantity + ZIP + Status */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 0.8fr 1fr 1fr', gap: '12px' }}>
        <div>
          <Label>Color</Label>
          <input value={form.color} onChange={e => set('color', e.target.value)} style={fld} placeholder="Beige, Gray, Green…"
            onFocus={e => e.target.style.borderColor = '#4A9FD4'} onBlur={e => e.target.style.borderColor = '#E2E8F0'} />
        </div>
        <div>
          <Label>Quantity</Label>
          <input type="number" min="1" step="1" value={form.quantity} onChange={e => set('quantity', e.target.value)} style={fld} placeholder="1"
            onFocus={e => e.target.style.borderColor = '#4A9FD4'} onBlur={e => e.target.style.borderColor = '#E2E8F0'} />
        </div>
        <div>
          <Label>Home ZIP</Label>
          <input value={form.home_zip} onChange={e => set('home_zip', e.target.value)} style={fld} placeholder="98001"
            onFocus={e => e.target.style.borderColor = '#4A9FD4'} onBlur={e => e.target.style.borderColor = '#E2E8F0'} />
        </div>
        <div>
          <Label>Status</Label>
          <select value={form.status} onChange={e => set('status', e.target.value)} style={{ ...fld, cursor: 'pointer' }}>
            {statusOptions.map(([value, label]) => <option key={value} value={value}>{label}</option>)}
          </select>
        </div>
      </div>

      {/* Row 3: Cost + Price + Margin indicator */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
        <div>
          <Label hint="(your cost)">Cost $</Label>
          <input type="number" value={form.cost} onChange={e => set('cost', e.target.value)} style={fld} placeholder="e.g. 1800"
            onFocus={e => e.target.style.borderColor = '#4A9FD4'} onBlur={e => e.target.style.borderColor = '#E2E8F0'} />
          {form.cost && !form.price && (
            <button type="button" onClick={() => set('price', autoPrice)} style={{ background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'Inter, sans-serif', fontSize: '12px', color: '#4A9FD4', fontWeight: '600', padding: '4px 0', textAlign: 'left' }}>
              → Auto-set price at {defaultMargin}% margin: ${autoPrice.toLocaleString()}
            </button>
          )}
        </div>
        <div>
          <Label hint="(sale price)">Price $</Label>
          <input type="number" value={form.price} onChange={e => set('price', e.target.value)} style={fld} placeholder="e.g. 2500"
            onFocus={e => e.target.style.borderColor = '#4A9FD4'} onBlur={e => e.target.style.borderColor = '#E2E8F0'} />
          {margin !== null && (
            <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginTop: '5px' }}>
              <div style={{ height: '4px', flex: 1, background: '#EEF2F7', borderRadius: '100px', overflow: 'hidden' }}>
                <div style={{ width: `${Math.min(100, margin)}%`, height: '100%', background: margin < 15 ? '#E53E3E' : margin >= 35 ? '#38A169' : '#D69E2E', transition: 'width 0.3s' }} />
              </div>
              <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '700', color: margin < 15 ? '#E53E3E' : margin >= 35 ? '#38A169' : '#D69E2E', whiteSpace: 'nowrap' }}>
                {margin}% margin
              </span>
            </div>
          )}
        </div>
      </div>

      {/* Profit preview */}
      {form.cost && form.price && (
        <div style={{ background: '#F9FAFB', border: '1px solid #E8EDF2', borderRadius: '8px', padding: '12px 16px', display: 'flex', justifyContent: 'space-between' }}>
          <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#6B7E96' }}>Estimated profit per unit</span>
          <span style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '18px', fontWeight: '800', color: '#38A169' }}>
            ${(Number(form.price) - Number(form.cost)).toLocaleString()}
          </span>
        </div>
      )}

      {/* Photo upload */}
      <div>
        <Label hint="(uploads to Supabase storage)">Photo</Label>
        <input
          ref={fileInputRef}
          type="file"
          accept="image/*"
          onChange={handleFileSelection}
          style={{ display: 'none' }}
        />
        <div
          onClick={() => !photoUploading && fileInputRef.current?.click()}
          onDragOver={(event) => {
            event.preventDefault();
            if (!photoUploading) setDragActive(true);
          }}
          onDragLeave={(event) => {
            event.preventDefault();
            setDragActive(false);
          }}
          onDrop={async (event) => {
            event.preventDefault();
            if (photoUploading) return;
            const file = event.dataTransfer.files?.[0];
            await uploadPhoto(file);
          }}
          style={{
            border: `1.5px dashed ${uploadBoxBorder}`,
            borderRadius: '12px',
            padding: '18px',
            background: dragActive ? '#F5FAFE' : '#F9FBFD',
            cursor: photoUploading ? 'progress' : 'pointer',
            transition: 'all 0.2s',
          }}
        >
          <div style={{ display: 'flex', gap: '16px', alignItems: 'center', flexWrap: 'wrap' }}>
            {form.photo_url ? (
              <img
                src={form.photo_url}
                alt="Container preview"
                style={{ width: '132px', height: '92px', objectFit: 'cover', borderRadius: '10px', display: 'block', border: '1px solid #E2E8F0' }}
                onError={e => e.target.style.display = 'none'}
              />
            ) : (
              <div style={{ width: '132px', height: '92px', borderRadius: '10px', background: '#EAF1F7', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '30px', color: '#6B7E96', border: '1px solid #D7E2EC' }}>
                +
              </div>
            )}
            <div style={{ flex: 1, minWidth: '220px' }}>
              <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '700', color: '#1B2A4A', marginBottom: '4px' }}>
                {photoUploading ? 'Uploading photo…' : form.photo_url ? 'Replace container photo' : 'Upload container photo'}
              </div>
              <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', lineHeight: 1.5, color: '#6B7E96' }}>
                Drag and drop an image here, or click to choose a file. Uploaded photos are saved to Supabase storage and attached to this inventory item.
              </div>
              {form.photo_url && (
                <div style={{ marginTop: '10px', display: 'flex', gap: '10px', flexWrap: 'wrap', alignItems: 'center' }}>
                  <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', color: '#38A169', fontWeight: '700' }}>Photo ready</span>
                  <button
                    type="button"
                    onClick={(event) => {
                      event.stopPropagation();
                      set('photo_url', '');
                      setPhotoUploadError('');
                    }}
                    style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '700', color: '#E53E3E' }}
                  >
                    Remove photo
                  </button>
                </div>
              )}
              {photoUploadError && (
                <div style={{ marginTop: '8px', fontFamily: 'Inter, sans-serif', fontSize: '12px', color: '#E53E3E', fontWeight: '600' }}>
                  {photoUploadError}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Notes */}
      <div>
        <Label>Special Notes</Label>
        <textarea value={form.notes} onChange={e => set('notes', e.target.value)} rows={3} style={{ ...fld, resize: 'vertical' }}
          placeholder="Condition details, delivery notes, customer info…"
          onFocus={e => e.target.style.borderColor = '#4A9FD4'} onBlur={e => e.target.style.borderColor = '#E2E8F0'} />
      </div>

      <button onClick={() => onSave(form)} disabled={photoUploading || saving} style={{
        width: '100%', background: '#1B2A4A', color: '#fff', border: 'none',
        borderRadius: '8px', padding: '13px', cursor: photoUploading || saving ? 'not-allowed' : 'pointer',
        fontFamily: 'Inter, sans-serif', fontSize: '15px', fontWeight: '700',
        transition: 'background 0.2s', opacity: photoUploading || saving ? 0.7 : 1,
      }}
      onMouseEnter={e => { if (!photoUploading && !saving) e.target.style.background = '#4A9FD4'; }}
      onMouseLeave={e => { if (!photoUploading && !saving) e.target.style.background = '#1B2A4A'; }}>
        {photoUploading ? 'Uploading Photo…' : saving ? 'Saving…' : item ? 'Save Changes' : 'Add to Inventory'}
      </button>
    </div>
  );
};

Object.assign(window, { AdminInventoryTab, InventoryItemForm });
