// 1Radar v3 — Shopify Stores & Product Import

// ─── Mock data ────────────────────────────────────────────────────────────────

const MOCK_STORES = [
  {
    id: 's1', name: 'Monarch Paris', domain: 'monarch-paris.myshopify.com',
    status: 'connected', productsCount: 142, collectionsCount: 18,
    currency: 'EUR', syncedAt: '2025-05-11T14:32:00Z',
  },
  {
    id: 's2', name: 'Glossier US', domain: 'glossier.myshopify.com',
    status: 'connected', productsCount: 89, collectionsCount: 12,
    currency: 'USD', syncedAt: '2025-05-10T09:15:00Z',
  },
];

const MOCK_CATALOG = {
  s1: {
    products: [
      { id: 'p1', title: 'Radiance Glow Serum', collection: 'Face Care', price: '58.00', image: null, status: 'active', vendor: 'Monarch Paris' },
      { id: 'p2', title: '24h Hydrating Cream', collection: 'Face Care', price: '42.00', image: null, status: 'active', vendor: 'Monarch Paris' },
      { id: 'p3', title: 'Precious Dry Oil', collection: 'Body & Spa', price: '36.00', image: null, status: 'active', vendor: 'Monarch Paris' },
      { id: 'p4', title: 'Clay Detox Mask', collection: 'Face Care', price: '28.00', image: null, status: 'draft', vendor: 'Monarch Paris' },
      { id: 'p5', title: 'Gentle Micellar Water', collection: 'Cleansers', price: '22.00', image: null, status: 'active', vendor: 'Monarch Paris' },
      { id: 'p6', title: 'Honey Lip Balm', collection: 'Lips', price: '14.00', image: null, status: 'active', vendor: 'Monarch Paris' },
      { id: 'p7', title: 'Eye Contour Concentrate', collection: 'Face Care', price: '64.00', image: null, status: 'active', vendor: 'Monarch Paris' },
      { id: 'p8', title: 'Autumn Ritual Gift Set', collection: 'Gift Sets', price: '98.00', image: null, status: 'active', vendor: 'Monarch Paris' },
    ],
    collections: [
      { id: 'c1', title: 'Face Care', productsCount: 4, image: null },
      { id: 'c2', title: 'Body & Spa', productsCount: 1, image: null },
      { id: 'c3', title: 'Cleansers', productsCount: 1, image: null },
      { id: 'c4', title: 'Lips', productsCount: 1, image: null },
      { id: 'c5', title: 'Gift Sets', productsCount: 1, image: null },
    ],
  },
  s2: {
    products: [
      { id: 'p9',  title: 'Boy Brow',              collection: 'Brows',     price: '18.00', image: null, status: 'active', vendor: 'Glossier' },
      { id: 'p10', title: 'Cloud Paint',            collection: 'Cheeks',    price: '22.00', image: null, status: 'active', vendor: 'Glossier' },
      { id: 'p11', title: 'Milky Jelly Cleanser',   collection: 'Skin',      price: '19.00', image: null, status: 'active', vendor: 'Glossier' },
      { id: 'p12', title: 'Priming Moisturizer',    collection: 'Skin',      price: '25.00', image: null, status: 'active', vendor: 'Glossier' },
      { id: 'p13', title: 'You Eau de Parfum',      collection: 'Fragrance', price: '68.00', image: null, status: 'active', vendor: 'Glossier' },
    ],
    collections: [
      { id: 'c6', title: 'Brows',     productsCount: 1, image: null },
      { id: 'c7', title: 'Cheeks',    productsCount: 1, image: null },
      { id: 'c8', title: 'Skin',      productsCount: 2, image: null },
      { id: 'c9', title: 'Fragrance', productsCount: 1, image: null },
    ],
  },
};

// ─── Helpers ──────────────────────────────────────────────────────────────────

const timeSince = (iso) => {
  const d = new Date(iso);
  const mins = Math.floor((Date.now() - d) / 60000);
  if (mins < 60) return `${mins}m ago`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}h ago`;
  return `${Math.floor(hrs / 24)}d ago`;
};

const productInitials = (title) =>
  title.split(' ').slice(0, 2).map(w => w[0]).join('').toUpperCase();

// ─── Sub-components ───────────────────────────────────────────────────────────

const StatusDot = ({ status }) => (
  <span style={{
    display: 'inline-block', width: 7, height: 7, borderRadius: '50%',
    background: status === 'connected' ? 'var(--success)' : 'var(--warn)',
    flexShrink: 0,
  }}/>
);

const StoreCard = ({ store, onSync, onDisconnect }) => (
  <div style={{
    padding: '14px 16px',
    borderRadius: 'var(--r-lg)',
    border: '1px solid var(--border)',
    background: 'var(--bg-surface)',
    display: 'flex', flexDirection: 'column', gap: 10,
  }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <div style={{
        width: 36, height: 36, borderRadius: 10, flexShrink: 0,
        background: 'var(--bg-soft)', border: '1px solid var(--border)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 13, fontWeight: 700, color: 'var(--accent)',
        fontFamily: 'var(--font-display)',
      }}>
        {store.name[0]}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {store.name}
        </div>
        <div style={{ fontSize: 12, color: 'var(--text-faint)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {store.domain}
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <StatusDot status={store.status}/>
        <span style={{ fontSize: 11, color: 'var(--text-faint)' }}>
          {store.status === 'connected' ? 'Connected' : 'Disconnected'}
        </span>
      </div>
    </div>
    <div style={{ display: 'flex', gap: 12, fontSize: 12, color: 'var(--text-muted)' }}>
      <span><strong style={{ color: 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>{store.productsCount}</strong> products</span>
      <span><strong style={{ color: 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>{store.collectionsCount}</strong> collections</span>
      <span style={{ marginLeft: 'auto', color: 'var(--text-faint)' }}>Synced {timeSince(store.syncedAt)}</span>
    </div>
    <div style={{ display: 'flex', gap: 6, marginTop: -2 }}>
      <button className="btn btn-sm btn-stroke" onClick={() => onSync(store.id)} style={{ flex: 1, fontSize: 12 }}>
        <Icon name="download" size={12}/>
        Sync
      </button>
      <button
        className="btn btn-sm"
        onClick={() => onDisconnect(store.id)}
        style={{ fontSize: 12, background: 'var(--danger-soft)', color: 'var(--danger)', borderColor: 'transparent' }}
      >
        Disconnect
      </button>
    </div>
  </div>
);

// Modal — confirm store disconnection
const DisconnectConfirmModal = ({ store, onClose, onConfirm }) => (
  <div style={{
    position: 'fixed', inset: 0, zIndex: 210,
    background: 'rgba(0,0,0,0.45)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    padding: 24,
  }} onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
    <div style={{
      width: 400, background: 'var(--bg-surface)',
      borderRadius: 'var(--r-xl)', border: '1px solid var(--border)',
      boxShadow: 'var(--shadow-pop)', overflow: 'hidden',
    }}>
      <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div style={{
          width: 44, height: 44, borderRadius: 'var(--r-lg)',
          background: 'var(--danger-soft)', border: '1px solid var(--danger)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="logout" size={20} style={{ color: 'var(--danger)' }}/>
        </div>
        <div>
          <div className="font-display" style={{ fontWeight: 600, fontSize: 16, color: 'var(--text)', marginBottom: 6 }}>
            Disconnect {store.name}?
          </div>
          <div style={{ fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.6 }}>
            This will remove <strong>{store.domain}</strong> from 1Radar.
            Previously imported products will not be deleted.
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, marginTop: 4 }}>
          <button className="btn btn-stroke" onClick={onClose} style={{ flex: 1 }}>Cancel</button>
          <button
            className="btn"
            onClick={onConfirm}
            style={{ flex: 1, background: 'var(--danger)', color: '#fff', borderColor: 'var(--danger)', fontSize: 13 }}
          >
            Yes, disconnect
          </button>
        </div>
      </div>
    </div>
  </div>
);

// Modal — connect a new store
const ConnectStoreModal = ({ onClose, onConnect }) => {
  const [domain, setDomain] = React.useState('');
  const [token, setToken] = React.useState('');
  const [step, setStep] = React.useState(1); // 1 = form, 2 = loading, 3 = success
  const [error, setError] = React.useState('');

  const handleConnect = () => {
    if (!domain.trim()) { setError('Please enter your store domain.'); return; }
    if (!token.trim()) { setError('Admin API token is required.'); return; }
    setError('');
    setStep(2);
    setTimeout(() => setStep(3), 1800);
  };

  const handleDone = () => {
    onConnect({
      id: 's' + Date.now(),
      name: domain.split('.')[0].replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase()),
      domain: domain.includes('.') ? domain : domain + '.myshopify.com',
      status: 'connected',
      productsCount: 0,
      collectionsCount: 0,
      currency: 'USD',
      syncedAt: new Date().toISOString(),
    });
    onClose();
  };

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 200,
      background: 'rgba(0,0,0,0.45)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24,
    }} onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div style={{
        width: 480, background: 'var(--bg-surface)',
        borderRadius: 'var(--r-xl)', border: '1px solid var(--border)',
        boxShadow: 'var(--shadow-pop)',
        overflow: 'hidden',
      }}>
        {/* Header */}
        <div style={{
          padding: '20px 24px', borderBottom: '1px solid var(--border)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <div>
            <div className="font-display" style={{ fontWeight: 600, fontSize: 16 }}>Connect a Shopify store</div>
            <div style={{ fontSize: 13, color: 'var(--text-faint)', marginTop: 2 }}>
              Enter your Shopify access credentials
            </div>
          </div>
          <button className="btn btn-ghost btn-icon" onClick={onClose}>
            <Icon name="close" size={18}/>
          </button>
        </div>

        {/* Body */}
        <div style={{ padding: 24 }}>
          {step === 1 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              {/* Info banner */}
              <div style={{
                padding: 16, borderRadius: 'var(--r-lg)',
                background: 'var(--bg-soft)', border: '1px dashed var(--border)',
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                <div style={{ width: 40, height: 40, flexShrink: 0 }}>
                  <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 256 292"><path fill="#95bf46" d="M223.774 57.34c-.201-1.46-1.48-2.268-2.537-2.357a19614 19614 0 0 0-23.383-1.743s-15.507-15.395-17.209-17.099c-1.703-1.703-5.029-1.185-6.32-.805c-.19.056-3.388 1.043-8.678 2.68c-5.18-14.906-14.322-28.604-30.405-28.604c-.444 0-.901.018-1.358.044C129.31 3.407 123.644.779 118.75.779c-37.465 0-55.364 46.835-60.976 70.635c-14.558 4.511-24.9 7.718-26.221 8.133c-8.126 2.549-8.383 2.805-9.45 10.462C21.3 95.806.038 260.235.038 260.235l165.678 31.042l89.77-19.42S223.973 58.8 223.775 57.34M156.49 40.848l-14.019 4.339c.005-.988.01-1.96.01-3.023c0-9.264-1.286-16.723-3.349-22.636c8.287 1.04 13.806 10.469 17.358 21.32m-27.638-19.483c2.304 5.773 3.802 14.058 3.802 25.238c0 .572-.005 1.095-.01 1.624c-9.117 2.824-19.024 5.89-28.953 8.966c5.575-21.516 16.025-31.908 25.161-35.828m-11.131-10.537c1.617 0 3.246.549 4.805 1.622c-12.007 5.65-24.877 19.88-30.312 48.297l-22.886 7.088C75.694 46.16 90.81 10.828 117.72 10.828"/><path fill="#5e8e3e" d="M221.237 54.983a19614 19614 0 0 0-23.383-1.743s-15.507-15.395-17.209-17.099c-.637-.634-1.496-.959-2.394-1.099l-12.527 256.233l89.762-19.418S223.972 58.8 223.774 57.34c-.201-1.46-1.48-2.268-2.537-2.357"/><path fill="#fff" d="m135.242 104.585l-11.069 32.926s-9.698-5.176-21.586-5.176c-17.428 0-18.305 10.937-18.305 13.693c0 15.038 39.2 20.8 39.2 56.024c0 27.713-17.577 45.558-41.277 45.558c-28.44 0-42.984-17.7-42.984-17.7l7.615-25.16s14.95 12.835 27.565 12.835c8.243 0 11.596-6.49 11.596-11.232c0-19.616-32.16-20.491-32.16-52.724c0-27.129 19.472-53.382 58.778-53.382c15.145 0 22.627 4.338 22.627 4.338"/></svg>
                </div>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)' }}>
                    Connect via Admin API
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--text-faint)', marginTop: 1 }}>
                    Create a private Shopify app to get your token
                  </div>
                </div>
                <a style={{
                  marginLeft: 'auto', fontSize: 12, color: 'var(--accent)',
                  display: 'flex', alignItems: 'center', gap: 4, textDecoration: 'none', flexShrink: 0,
                }}>
                  Guide <Icon name="external" size={12}/>
                </a>
              </div>

              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                <div>
                  <label style={{ fontSize: 12, fontWeight: 500, color: 'var(--text-2)', display: 'block', marginBottom: 5 }}>
                    Shopify domain
                  </label>
                  <div className="fld" style={{ gap: 8, width: '100%' }}>
                    <Icon name="globe" size={15} style={{ color: 'var(--text-faint)', flexShrink: 0 }}/>
                    <input
                      value={domain}
                      onChange={e => setDomain(e.target.value)}
                      placeholder="my-store.myshopify.com"
                      style={{ flex: 1, background: 'none', border: 'none', outline: 'none', fontSize: 14, color: 'var(--text)' }}
                    />
                  </div>
                </div>
                <div>
                  <label style={{ fontSize: 12, fontWeight: 500, color: 'var(--text-2)', display: 'block', marginBottom: 5 }}>
                    Admin API access token
                  </label>
                  <div className="fld" style={{ gap: 8, width: '100%' }}>
                    <Icon name="settings" size={15} style={{ color: 'var(--text-faint)', flexShrink: 0 }}/>
                    <input
                      type="password"
                      value={token}
                      onChange={e => setToken(e.target.value)}
                      placeholder="shpat_••••••••••••••••••••••"
                      style={{ flex: 1, background: 'none', border: 'none', outline: 'none', fontSize: 14, color: 'var(--text)', fontFamily: 'var(--font-mono)' }}
                    />
                  </div>
                </div>
              </div>

              {error && (
                <div style={{
                  padding: '10px 12px', borderRadius: 'var(--r-md)',
                  background: 'var(--danger-soft)', color: 'var(--danger)',
                  fontSize: 13, display: 'flex', alignItems: 'center', gap: 8,
                }}>
                  <Icon name="close" size={13}/>
                  {error}
                </div>
              )}

              <div style={{ display: 'flex', gap: 8, marginTop: 4 }}>
                <button className="btn btn-stroke" onClick={onClose} style={{ flex: 1 }}>Cancel</button>
                <button className="btn btn-primary" onClick={handleConnect} style={{ flex: 2 }}>
                  Connect store
                </button>
              </div>
            </div>
          )}

          {step === 2 && (
            <div style={{ padding: '32px 0', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16 }}>
              <div style={{
                width: 48, height: 48, borderRadius: '50%',
                border: '3px solid var(--border)',
                borderTopColor: 'var(--accent)',
                animation: 'spin 0.8s linear infinite',
              }}/>
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontWeight: 600, fontSize: 15, color: 'var(--text)' }}>Connecting…</div>
                <div style={{ fontSize: 13, color: 'var(--text-faint)', marginTop: 4 }}>Verifying Shopify credentials</div>
              </div>
            </div>
          )}

          {step === 3 && (
            <div style={{ padding: '32px 0', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16 }}>
              <div style={{
                width: 52, height: 52, borderRadius: '50%',
                background: 'var(--success-soft)', border: '1px solid var(--success)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <Icon name="check" size={24} style={{ color: 'var(--success)' }}/>
              </div>
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontWeight: 600, fontSize: 15, color: 'var(--text)' }}>Store connected!</div>
                <div style={{ fontSize: 13, color: 'var(--text-faint)', marginTop: 4 }}>
                  Products are syncing in the background
                </div>
              </div>
              <button className="btn btn-primary" onClick={handleDone} style={{ marginTop: 8 }}>
                Continue
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

// Shared: destination store picker (shown after product selection)
const DestinationPicker = ({ stores, value, onChange }) => (
  <div>
    <label style={{ fontSize: 12, fontWeight: 500, color: 'var(--text-2)', display: 'block', marginBottom: 5 }}>
      Destination store
    </label>
    <div className="fld" style={{ gap: 8 }}>
      <Icon name="shop" size={15} style={{ color: 'var(--text-faint)', flexShrink: 0 }}/>
      <select value={value} onChange={e => onChange(e.target.value)}
        style={{ flex: 1, background: 'none', border: 'none', outline: 'none', fontSize: 13, color: 'var(--text)', cursor: 'pointer' }}>
        {stores.map(s => <option key={s.id} value={s.id}>{s.name} — {s.domain}</option>)}
      </select>
      <StatusDot status="connected"/>
    </div>
  </div>
);

// Shared: spinner line
const Spinner = ({ label }) => (
  <div style={{ padding: '20px 0', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, color: 'var(--text-faint)', fontSize: 13 }}>
    <div style={{ width: 18, height: 18, borderRadius: '50%', border: '2px solid var(--border)', borderTopColor: 'var(--accent)', animation: 'spin 0.8s linear infinite', flexShrink: 0 }}/>
    {label}
  </div>
);

// Shared: checkbox row
const CheckRow = ({ item, checked, onToggle, subtitle, badge }) => (
  <div
    onClick={onToggle}
    style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '11px 14px', cursor: 'pointer',
      background: checked ? 'var(--accent-soft)' : 'transparent',
      transition: 'background .1s',
    }}
  >
    <div style={{
      width: 18, height: 18, borderRadius: 5, flexShrink: 0,
      border: checked ? 'none' : '1.5px solid var(--border)',
      background: checked ? 'var(--accent)' : 'var(--bg-soft)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      {checked && <Icon name="check" size={11} style={{ color: '#fff' }}/>}
    </div>
    <div style={{
      width: 40, height: 40, borderRadius: 'var(--r-sm)', flexShrink: 0,
      background: 'var(--bg-soft)', border: '1px solid var(--border)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontSize: 12, fontWeight: 700, color: 'var(--text-muted)', fontFamily: 'var(--font-display)',
    }}>
      {productInitials(item.title)}
    </div>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
        {item.title}
      </div>
      <div style={{ fontSize: 12, color: 'var(--text-faint)' }}>{subtitle}</div>
    </div>
    {badge}
  </div>
);

// Tab: import from a product URL → push to a connected store
const ImportByProductUrl = ({ stores }) => {
  const [url, setUrl] = React.useState('');
  const [fetchStatus, setFetchStatus] = React.useState('idle'); // idle | loading | done
  const [result, setResult] = React.useState(null);
  const [destId, setDestId] = React.useState(stores[0]?.id || '');
  const [pushStatus, setPushStatus] = React.useState('idle'); // idle | loading | success

  const handleFetch = () => {
    if (!url.trim()) return;
    setFetchStatus('loading');
    setResult(null);
    setPushStatus('idle');
    setTimeout(() => {
      setResult({
        title: 'Radiance Glow Serum — Limited Edition',
        price: '58.00', currency: 'USD',
        variants: 3, images: 4,
        vendor: 'Glossier', collection: 'Face Care', status: 'active',
      });
      setFetchStatus('done');
    }, 1400);
  };

  const handlePush = () => {
    setPushStatus('loading');
    setTimeout(() => setPushStatus('success'), 1200);
  };

  const dest = stores.find(s => s.id === destId);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{
        padding: 16, borderRadius: 'var(--r-lg)',
        background: 'var(--bg-soft)', border: '1px solid var(--border)',
        fontSize: 13, color: 'var(--text-muted)',
        display: 'flex', alignItems: 'flex-start', gap: 10,
      }}>
        <Icon name="link" size={16} style={{ color: 'var(--accent)', marginTop: 1, flexShrink: 0 }}/>
        <span>
          Paste any product URL (competitor, supplier…). 1Radar fetches the product data and pushes it directly into your Shopify store.
        </span>
      </div>

      {/* Step 1 — URL */}
      <div>
        <label style={{ fontSize: 12, fontWeight: 500, color: 'var(--text-2)', display: 'block', marginBottom: 5 }}>Product URL</label>
        <div style={{ display: 'flex', gap: 8 }}>
          <div className="fld" style={{ flex: 1, gap: 8 }}>
            <Icon name="link" size={15} style={{ color: 'var(--text-faint)', flexShrink: 0 }}/>
            <input
              value={url}
              onChange={e => { setUrl(e.target.value); setFetchStatus('idle'); setResult(null); setPushStatus('idle'); }}
              placeholder="https://competitor.com/products/…"
              style={{ flex: 1, background: 'none', border: 'none', outline: 'none', fontSize: 13, color: 'var(--text)' }}
              onKeyDown={e => { if (e.key === 'Enter') handleFetch(); }}
            />
            {url && (
              <button onClick={() => { setUrl(''); setFetchStatus('idle'); setResult(null); setPushStatus('idle'); }}
                style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, color: 'var(--text-faint)', display: 'flex' }}>
                <Icon name="close" size={13}/>
              </button>
            )}
          </div>
          <button className="btn btn-primary" onClick={handleFetch} disabled={!url.trim() || fetchStatus === 'loading'} style={{ flexShrink: 0 }}>
            {fetchStatus === 'loading' ? 'Fetching…' : 'Fetch product'}
          </button>
        </div>
      </div>

      {fetchStatus === 'loading' && <Spinner label="Fetching product data…"/>}

      {/* Step 2 — Preview + destination + push */}
      {fetchStatus === 'done' && result && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {/* Preview card */}
          <div style={{ borderRadius: 'var(--r-lg)', border: '1px solid var(--border)', background: 'var(--bg-surface)', overflow: 'hidden' }}>
            <div style={{
              padding: '10px 14px', borderBottom: '1px solid var(--border)',
              display: 'flex', alignItems: 'center', gap: 8,
              fontSize: 13, color: 'var(--success)', fontWeight: 500,
              background: 'var(--success-soft)',
            }}>
              <Icon name="check" size={14}/>
              Product found
            </div>
            <div style={{ padding: 16, display: 'flex', gap: 14, alignItems: 'flex-start' }}>
              <div style={{
                width: 72, height: 72, borderRadius: 'var(--r-md)',
                background: 'var(--bg-soft)', border: '1px solid var(--border)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 18, fontWeight: 700, color: 'var(--text-muted)',
                flexShrink: 0, fontFamily: 'var(--font-display)',
              }}>
                {productInitials(result.title)}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600, fontSize: 15, color: 'var(--text)' }}>{result.title}</div>
                <div style={{ fontSize: 13, color: 'var(--text-faint)', marginTop: 2 }}>{result.vendor} · {result.collection}</div>
                <div style={{ display: 'flex', gap: 8, marginTop: 8, flexWrap: 'wrap' }}>
                  <span className="chip">{result.currency} {result.price}</span>
                  <span className="chip">{result.variants} variant{result.variants > 1 ? 's' : ''}</span>
                  <span className="chip">{result.images} image{result.images > 1 ? 's' : ''}</span>
                  <span className="chip" style={{
                    background: result.status === 'active' ? 'var(--success-soft)' : 'var(--warn-soft)',
                    color: result.status === 'active' ? 'var(--success)' : 'var(--warn)',
                  }}>
                    {result.status === 'active' ? 'Active' : 'Draft'}
                  </span>
                </div>
              </div>
            </div>
          </div>

          {/* Destination + push */}
          {pushStatus !== 'success' && (
            <>
              <DestinationPicker stores={stores} value={destId} onChange={setDestId}/>
              <button className="btn btn-primary" onClick={handlePush} disabled={pushStatus === 'loading'}>
                {pushStatus === 'loading' ? (
                  <>
                    <div style={{ width: 14, height: 14, borderRadius: '50%', border: '2px solid rgba(255,255,255,0.3)', borderTopColor: '#fff', animation: 'spin 0.8s linear infinite' }}/>
                    Pushing to {dest?.name}…
                  </>
                ) : (
                  <>
                    <Icon name="download" size={15}/>
                    Push to {dest?.name}
                  </>
                )}
              </button>
            </>
          )}

          {pushStatus === 'success' && (
            <div style={{
              padding: '14px 16px', borderRadius: 'var(--r-lg)',
              background: 'var(--success-soft)', border: '1px solid var(--success)',
              display: 'flex', alignItems: 'center', gap: 10,
              fontSize: 13, color: 'var(--success)', fontWeight: 500,
            }}>
              <Icon name="check" size={16}/>
              Product successfully added to <strong>{dest?.name}</strong>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

// Tab: import from a collection URL → pick products → push to a connected store
const ImportByCollectionUrl = ({ stores }) => {
  const [url, setUrl] = React.useState('');
  const [fetchStatus, setFetchStatus] = React.useState('idle');
  const [results, setResults] = React.useState([]);
  const [selected, setSelected] = React.useState(new Set());
  const [destId, setDestId] = React.useState(stores[0]?.id || '');
  const [pushStatus, setPushStatus] = React.useState('idle');

  const handleFetch = () => {
    if (!url.trim()) return;
    setFetchStatus('loading');
    setSelected(new Set());
    setPushStatus('idle');
    setTimeout(() => {
      setResults(MOCK_CATALOG['s1'].products.slice(0, 5));
      setFetchStatus('done');
    }, 1600);
  };

  const toggleAll = () => {
    if (selected.size === results.length) setSelected(new Set());
    else setSelected(new Set(results.map(p => p.id)));
  };

  const toggleOne = (id) => setSelected(s => {
    const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n;
  });

  const handlePush = () => {
    setPushStatus('loading');
    setTimeout(() => setPushStatus('success'), 1400);
  };

  const dest = stores.find(s => s.id === destId);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{
        padding: 16, borderRadius: 'var(--r-lg)',
        background: 'var(--bg-soft)', border: '1px solid var(--border)',
        fontSize: 13, color: 'var(--text-muted)',
        display: 'flex', alignItems: 'flex-start', gap: 10,
      }}>
        <Icon name="link" size={16} style={{ color: 'var(--accent)', marginTop: 1, flexShrink: 0 }}/>
        <span>
          Paste a collection URL. 1Radar fetches all products in it — select the ones to push to your store.
        </span>
      </div>

      {/* URL row */}
      <div>
        <label style={{ fontSize: 12, fontWeight: 500, color: 'var(--text-2)', display: 'block', marginBottom: 5 }}>Collection URL</label>
        <div style={{ display: 'flex', gap: 8 }}>
          <div className="fld" style={{ flex: 1, gap: 8 }}>
            <Icon name="link" size={15} style={{ color: 'var(--text-faint)', flexShrink: 0 }}/>
            <input
              value={url}
              onChange={e => { setUrl(e.target.value); setFetchStatus('idle'); setResults([]); setPushStatus('idle'); }}
              placeholder="https://competitor.com/collections/…"
              style={{ flex: 1, background: 'none', border: 'none', outline: 'none', fontSize: 13, color: 'var(--text)' }}
              onKeyDown={e => { if (e.key === 'Enter') handleFetch(); }}
            />
            {url && (
              <button onClick={() => { setUrl(''); setFetchStatus('idle'); setResults([]); setPushStatus('idle'); }}
                style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, color: 'var(--text-faint)', display: 'flex' }}>
                <Icon name="close" size={13}/>
              </button>
            )}
          </div>
          <button className="btn btn-primary" onClick={handleFetch} disabled={!url.trim() || fetchStatus === 'loading'} style={{ flexShrink: 0 }}>
            {fetchStatus === 'loading' ? 'Fetching…' : 'Fetch collection'}
          </button>
        </div>
      </div>

      {fetchStatus === 'loading' && <Spinner label="Fetching collection products…"/>}

      {fetchStatus === 'done' && results.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {/* Product list */}
          <div style={{ borderRadius: 'var(--r-lg)', border: '1px solid var(--border)', background: 'var(--bg-surface)', overflow: 'hidden' }}>
            <div style={{
              padding: '10px 14px', borderBottom: '1px solid var(--border)',
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <button onClick={toggleAll} style={{
                width: 18, height: 18, borderRadius: 5, flexShrink: 0, cursor: 'pointer',
                border: selected.size === results.length ? 'none' : '1.5px solid var(--border)',
                background: selected.size === results.length ? 'var(--accent)' : 'var(--bg-soft)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                {selected.size === results.length && <Icon name="check" size={11} style={{ color: '#fff' }}/>}
              </button>
              <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>
                <strong style={{ color: 'var(--text)' }}>{results.length}</strong> products found
              </span>
              {selected.size > 0 && (
                <span className="chip" style={{ marginLeft: 'auto', background: 'var(--accent-soft)', color: 'var(--accent)' }}>
                  {selected.size} selected
                </span>
              )}
            </div>
            {results.map((product, i) => (
              <div key={product.id} style={{ borderTop: i ? '1px solid var(--border-soft)' : 'none' }}>
                <CheckRow
                  item={product}
                  checked={selected.has(product.id)}
                  onToggle={() => toggleOne(product.id)}
                  subtitle={`${product.collection} · ${product.price}`}
                  badge={
                    <span className="chip" style={{
                      flexShrink: 0, fontSize: 11,
                      background: product.status === 'active' ? 'var(--success-soft)' : 'var(--warn-soft)',
                      color: product.status === 'active' ? 'var(--success)' : 'var(--warn)',
                    }}>
                      {product.status === 'active' ? 'Active' : 'Draft'}
                    </span>
                  }
                />
              </div>
            ))}
          </div>

          {/* Destination + push */}
          {selected.size > 0 && pushStatus !== 'success' && (
            <>
              <DestinationPicker stores={stores} value={destId} onChange={setDestId}/>
              <button className="btn btn-primary" onClick={handlePush} disabled={pushStatus === 'loading'}>
                {pushStatus === 'loading' ? (
                  <>
                    <div style={{ width: 14, height: 14, borderRadius: '50%', border: '2px solid rgba(255,255,255,0.3)', borderTopColor: '#fff', animation: 'spin 0.8s linear infinite' }}/>
                    Pushing {selected.size} product{selected.size > 1 ? 's' : ''} to {dest?.name}…
                  </>
                ) : (
                  <>
                    <Icon name="download" size={15}/>
                    Push {selected.size} product{selected.size > 1 ? 's' : ''} to {dest?.name}
                  </>
                )}
              </button>
            </>
          )}

          {pushStatus === 'success' && (
            <div style={{
              padding: '14px 16px', borderRadius: 'var(--r-lg)',
              background: 'var(--success-soft)', border: '1px solid var(--success)',
              display: 'flex', alignItems: 'center', gap: 10,
              fontSize: 13, color: 'var(--success)', fontWeight: 500,
            }}>
              <Icon name="check" size={16}/>
              {selected.size} product{selected.size > 1 ? 's' : ''} successfully added to <strong>{dest?.name}</strong>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

// Tab: browse any store catalog → select → push to a connected store
const ImportGlobal = ({ stores }) => {
  const [sourceUrl, setSourceUrl] = React.useState('');
  const [tab, setTab] = React.useState('products');
  const [search, setSearch] = React.useState('');
  const [selected, setSelected] = React.useState(new Set());
  const [loading, setLoading] = React.useState(false);
  const [loaded, setLoaded] = React.useState(false);
  const [destId, setDestId] = React.useState(stores[0]?.id || '');
  const [pushStatus, setPushStatus] = React.useState('idle');
  const [expandedCollections, setExpandedCollections] = React.useState(new Set());

  const toggleExpand = (id) => setExpandedCollections(s => {
    const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n;
  });

  // Simulate fetching catalog from the source URL (uses mock s1)
  const catalog = loaded ? (MOCK_CATALOG['s1'] || { products: [], collections: [] }) : { products: [], collections: [] };
  const dest = stores.find(s => s.id === destId);

  const handleLoad = () => {
    if (!sourceUrl.trim()) return;
    setLoading(true);
    setLoaded(false);
    setSelected(new Set());
    setSearch('');
    setPushStatus('idle');
    setTimeout(() => { setLoading(false); setLoaded(true); }, 1200);
  };

  React.useEffect(() => {
    setLoaded(false);
    setSelected(new Set());
    setSearch('');
    setPushStatus('idle');
  }, [sourceUrl]);

  const filteredProducts = catalog.products.filter(p =>
    p.title.toLowerCase().includes(search.toLowerCase()) ||
    p.collection.toLowerCase().includes(search.toLowerCase())
  );
  const filteredCollections = catalog.collections.filter(c =>
    c.title.toLowerCase().includes(search.toLowerCase())
  );
  const items = tab === 'products' ? filteredProducts : filteredCollections;

  // All product IDs visible in the current tab (products in collections tab too)
  const getColProducts = (col) => catalog.products.filter(p => p.collection === col.title);
  const allVisibleProductIds = tab === 'products'
    ? filteredProducts.map(p => p.id)
    : filteredCollections.flatMap(c => getColProducts(c).map(p => p.id));
  const allSelected = allVisibleProductIds.length > 0 && allVisibleProductIds.every(id => selected.has(id));

  const toggleOne = (id) => setSelected(s => {
    const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n;
  });
  const toggleCollection = (col) => {
    const ids = getColProducts(col).map(p => p.id);
    const allSel = ids.every(id => selected.has(id));
    setSelected(s => {
      const n = new Set(s);
      allSel ? ids.forEach(id => n.delete(id)) : ids.forEach(id => n.add(id));
      return n;
    });
  };
  const toggleAll = () => {
    if (allSelected) setSelected(new Set());
    else setSelected(new Set(allVisibleProductIds));
  };

  const handlePush = () => {
    setPushStatus('loading');
    setTimeout(() => setPushStatus('success'), 1400);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{
        padding: 16, borderRadius: 'var(--r-lg)',
        background: 'var(--bg-soft)', border: '1px solid var(--border)',
        fontSize: 13, color: 'var(--text-muted)',
        display: 'flex', alignItems: 'flex-start', gap: 10,
      }}>
        <Icon name="globe" size={16} style={{ color: 'var(--accent)', marginTop: 1, flexShrink: 0 }}/>
        <span>
          Enter any Shopify store URL to browse its full catalog. Pick the products and collections you want, then push them to one of your stores.
        </span>
      </div>

      {/* Source URL + load */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <label style={{ fontSize: 12, fontWeight: 500, color: 'var(--text-2)' }}>Source store URL</label>
        <div style={{ display: 'flex', gap: 8 }}>
          <div className="fld" style={{ flex: 1, gap: 8 }}>
            <Icon name="globe" size={15} style={{ color: 'var(--text-faint)', flexShrink: 0 }}/>
            <input
              value={sourceUrl}
              onChange={e => setSourceUrl(e.target.value)}
              placeholder="https://competitor.myshopify.com"
              style={{ flex: 1, background: 'none', border: 'none', outline: 'none', fontSize: 13, color: 'var(--text)' }}
              onKeyDown={e => { if (e.key === 'Enter') handleLoad(); }}
            />
          </div>
          <button className="btn btn-primary" onClick={handleLoad} disabled={!sourceUrl.trim() || loading} style={{ flexShrink: 0 }}>
            {loading ? (
              <>
                <div style={{ width: 14, height: 14, borderRadius: '50%', border: '2px solid var(--border)', borderTopColor: 'var(--accent)', animation: 'spin 0.8s linear infinite' }}/>
                Loading…
              </>
            ) : (
              <><Icon name="search" size={14}/>{loaded ? 'Refresh' : 'Browse catalog'}</>
            )}
          </button>
        </div>
      </div>

      {!loaded && !loading && (
        <div style={{
          padding: '40px 24px', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
          borderRadius: 'var(--r-lg)', border: '1px dashed var(--border)',
          color: 'var(--text-faint)', fontSize: 13, textAlign: 'center',
        }}>
          <Icon name="globe" size={28} style={{ opacity: 0.35 }}/>
          <div>
            <div style={{ fontWeight: 500, color: 'var(--text-muted)', marginBottom: 2 }}>No catalog loaded</div>
            Enter a store URL above to browse its products
          </div>
        </div>
      )}

      {loading && <Spinner label="Browsing store catalog…"/>}

      {loaded && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div style={{ borderRadius: 'var(--r-lg)', border: '1px solid var(--border)', background: 'var(--bg-surface)', overflow: 'hidden' }}>
            {/* Toolbar */}
            <div style={{ padding: '10px 14px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
              {/* Tabs */}
              <div style={{ display: 'flex', background: 'var(--bg-soft)', borderRadius: 'var(--r-sm)', padding: 3, gap: 2, flexShrink: 0 }}>
                {[
                  { id: 'products',    label: 'Products',    count: catalog.products.length },
                  { id: 'collections', label: 'Collections', count: catalog.collections.length },
                ].map(t => (
                  <button key={t.id} onClick={() => { setTab(t.id); setSelected(new Set()); setSearch(''); }} style={{
                    padding: '4px 10px', borderRadius: 'var(--r-xs)',
                    background: tab === t.id ? 'var(--bg-surface)' : 'transparent',
                    border: tab === t.id ? '1px solid var(--border)' : '1px solid transparent',
                    fontSize: 12, fontWeight: tab === t.id ? 600 : 400,
                    color: tab === t.id ? 'var(--text)' : 'var(--text-faint)',
                    cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 5,
                    boxShadow: tab === t.id ? 'var(--shadow-card)' : 'none',
                  }}>
                    {t.label}
                    <span style={{
                      fontSize: 10, padding: '1px 5px', borderRadius: 999,
                      background: tab === t.id ? 'var(--accent-soft)' : 'var(--bg-surface)',
                      color: tab === t.id ? 'var(--accent)' : 'var(--text-faint)',
                      fontVariantNumeric: 'tabular-nums',
                    }}>{t.count}</span>
                  </button>
                ))}
              </div>
              {/* Search */}
              <div className="fld" style={{ flex: 1, minWidth: 140, gap: 6, height: 32 }}>
                <Icon name="search" size={13} style={{ color: 'var(--text-faint)', flexShrink: 0 }}/>
                <input value={search} onChange={e => setSearch(e.target.value)}
                  placeholder={tab === 'products' ? 'Filter products…' : 'Filter collections…'}
                  style={{ flex: 1, background: 'none', border: 'none', outline: 'none', fontSize: 12, color: 'var(--text)' }}/>
                {search && <button onClick={() => setSearch('')} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, color: 'var(--text-faint)', display: 'flex' }}><Icon name="close" size={12}/></button>}
              </div>
              {/* Select all */}
              <button onClick={toggleAll} style={{
                display: 'flex', alignItems: 'center', gap: 5, flexShrink: 0,
                background: 'none', border: '1px solid var(--border)',
                borderRadius: 'var(--r-sm)', padding: '4px 9px',
                fontSize: 12, cursor: 'pointer', color: 'var(--text-muted)',
              }}>
                <div style={{
                  width: 14, height: 14, borderRadius: 4, flexShrink: 0,
                  border: allSelected ? 'none' : '1.5px solid var(--border)',
                  background: allSelected ? 'var(--accent)' : 'var(--bg-soft)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  {allSelected && <Icon name="check" size={9} style={{ color: '#fff' }}/>}
                </div>
                Select all
              </button>
            </div>

            {/* List */}
            <div style={{ maxHeight: 400, overflow: 'auto' }} className="scroll">
              {items.length === 0 ? (
                <div style={{ padding: '24px 0', textAlign: 'center', color: 'var(--text-faint)', fontSize: 13 }}>
                  No results for "{search}"
                </div>
              ) : tab === 'products' ? items.map((item, i) => (
                <div key={item.id} style={{ borderTop: i ? '1px solid var(--border-soft)' : 'none' }}>
                  <CheckRow
                    item={item}
                    checked={selected.has(item.id)}
                    onToggle={() => toggleOne(item.id)}
                    subtitle={`${item.collection} · ${item.price}`}
                    badge={
                      <span className="chip" style={{
                        flexShrink: 0, fontSize: 11,
                        background: item.status === 'active' ? 'var(--success-soft)' : 'var(--warn-soft)',
                        color: item.status === 'active' ? 'var(--success)' : 'var(--warn)',
                      }}>
                        {item.status === 'active' ? 'Active' : 'Draft'}
                      </span>
                    }
                  />
                </div>
              )) : items.map((col, i) => {
                const isExpanded = expandedCollections.has(col.id);
                const cProds = getColProducts(col);
                const colAllSel = cProds.length > 0 && cProds.every(p => selected.has(p.id));
                const colSomeSel = !colAllSel && cProds.some(p => selected.has(p.id));
                return (
                  <div key={col.id} style={{ borderTop: i ? '1px solid var(--border-soft)' : 'none' }}>
                    {/* Collection header row */}
                    <div
                      onClick={() => toggleCollection(col)}
                      style={{
                        display: 'flex', alignItems: 'center', gap: 12,
                        padding: '11px 14px', cursor: 'pointer',
                        background: colAllSel ? 'var(--accent-soft)' : colSomeSel ? 'var(--bg-soft)' : 'transparent',
                        transition: 'background .1s',
                      }}
                    >
                      <div style={{
                        width: 18, height: 18, borderRadius: 5, flexShrink: 0,
                        border: colAllSel ? 'none' : '1.5px solid var(--border)',
                        background: colAllSel ? 'var(--accent)' : colSomeSel ? 'var(--accent-soft)' : 'var(--bg-soft)',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                      }}>
                        {colAllSel && <Icon name="check" size={11} style={{ color: '#fff' }}/>}
                        {colSomeSel && <div style={{ width: 8, height: 2, borderRadius: 1, background: 'var(--accent)' }}/>}
                      </div>
                      <div style={{
                        width: 40, height: 40, borderRadius: 'var(--r-sm)', flexShrink: 0,
                        background: 'var(--bg-soft)', border: '1px solid var(--border)',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        fontSize: 12, fontWeight: 700, color: 'var(--text-muted)', fontFamily: 'var(--font-display)',
                      }}>
                        {productInitials(col.title)}
                      </div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text)' }}>{col.title}</div>
                        <div style={{ fontSize: 12, color: 'var(--text-faint)' }}>
                          {cProds.filter(p => selected.has(p.id)).length
                            ? `${cProds.filter(p => selected.has(p.id)).length} / ${col.productsCount} selected`
                            : `${col.productsCount} product${col.productsCount !== 1 ? 's' : ''}`
                          }
                        </div>
                      </div>
                      <button
                        onClick={e => { e.stopPropagation(); toggleExpand(col.id); }}
                        style={{
                          background: 'none', border: 'none', cursor: 'pointer', padding: 4,
                          color: 'var(--text-faint)', display: 'flex', alignItems: 'center',
                          borderRadius: 'var(--r-sm)', flexShrink: 0,
                        }}
                      >
                        <Icon name={isExpanded ? 'chevron-up' : 'chevron-down'} size={15}/>
                      </button>
                    </div>

                    {/* Expanded products */}
                    {isExpanded && (
                      <div style={{ borderTop: '1px solid var(--border-soft)', background: 'var(--bg-soft)' }}>
                        {cProds.length === 0 ? (
                          <div style={{ padding: '10px 14px 10px 74px', fontSize: 12, color: 'var(--text-faint)' }}>
                            No products in this collection
                          </div>
                        ) : cProds.map((p, j) => (
                          <div
                            key={p.id}
                            onClick={() => toggleOne(p.id)}
                            style={{
                              display: 'flex', alignItems: 'center', gap: 10,
                              padding: '9px 14px 9px 46px',
                              borderTop: j ? '1px solid var(--border-soft)' : 'none',
                              cursor: 'pointer',
                              background: selected.has(p.id) ? 'var(--accent-soft)' : 'transparent',
                              transition: 'background .1s',
                            }}
                          >
                            <div style={{
                              width: 16, height: 16, borderRadius: 4, flexShrink: 0,
                              border: selected.has(p.id) ? 'none' : '1.5px solid var(--border)',
                              background: selected.has(p.id) ? 'var(--accent)' : 'var(--bg-surface)',
                              display: 'flex', alignItems: 'center', justifyContent: 'center',
                            }}>
                              {selected.has(p.id) && <Icon name="check" size={10} style={{ color: '#fff' }}/>}
                            </div>
                            <div style={{
                              width: 30, height: 30, borderRadius: 6, flexShrink: 0,
                              background: 'var(--bg-surface)', border: '1px solid var(--border)',
                              display: 'flex', alignItems: 'center', justifyContent: 'center',
                              fontSize: 10, fontWeight: 700, color: 'var(--text-muted)', fontFamily: 'var(--font-display)',
                            }}>
                              {productInitials(p.title)}
                            </div>
                            <div style={{ flex: 1, minWidth: 0 }}>
                              <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--text)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                                {p.title}
                              </div>
                              <div style={{ fontSize: 11, color: 'var(--text-faint)' }}>{p.vendor} · {p.price}</div>
                            </div>
                            <span className="chip" style={{
                              flexShrink: 0, fontSize: 10,
                              background: p.status === 'active' ? 'var(--success-soft)' : 'var(--warn-soft)',
                              color: p.status === 'active' ? 'var(--success)' : 'var(--warn)',
                            }}>
                              {p.status === 'active' ? 'Active' : 'Draft'}
                            </span>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>

          {/* Destination + push */}
          {selected.size > 0 && pushStatus !== 'success' && (
            <>
              <DestinationPicker stores={stores} value={destId} onChange={setDestId}/>
              <button className="btn btn-primary" onClick={handlePush} disabled={pushStatus === 'loading'}>
                {pushStatus === 'loading' ? (
                  <>
                    <div style={{ width: 14, height: 14, borderRadius: '50%', border: '2px solid rgba(255,255,255,0.3)', borderTopColor: '#fff', animation: 'spin 0.8s linear infinite' }}/>
                    Pushing {selected.size} item{selected.size > 1 ? 's' : ''} to {dest?.name}…
                  </>
                ) : (
                  <>
                    <Icon name="download" size={15}/>
                    Push {selected.size} item{selected.size > 1 ? 's' : ''} to {dest?.name}
                  </>
                )}
              </button>
            </>
          )}

          {pushStatus === 'success' && (
            <div style={{
              padding: '14px 16px', borderRadius: 'var(--r-lg)',
              background: 'var(--success-soft)', border: '1px solid var(--success)',
              display: 'flex', alignItems: 'center', gap: 10,
              fontSize: 13, color: 'var(--success)', fontWeight: 500,
            }}>
              <Icon name="check" size={16}/>
              {selected.size} item{selected.size > 1 ? 's' : ''} successfully pushed to <strong>{dest?.name}</strong>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

// ─── Main screen ──────────────────────────────────────────────────────────────

const ShopifyV3 = () => {
  const [stores, setStores] = React.useState(MOCK_STORES);
  const [importTab, setImportTab] = React.useState('product'); // product | collection | global
  const [connectOpen, setConnectOpen] = React.useState(false);
  const [disconnectTarget, setDisconnectTarget] = React.useState(null);

  const handleConnect = (newStore) => {
    setStores(prev => [...prev, newStore]);
  };

  const handleSync = (id) => {};

  const handleDisconnect = (id) => {
    setStores(prev => prev.filter(s => s.id !== id));
    setDisconnectTarget(null);
  };

  const IMPORT_TABS = [
    { id: 'product',    label: 'Product link',    icon: 'link',     desc: 'Import a single product' },
    { id: 'collection', label: 'Collection link', icon: 'bookmark', desc: 'All products from a collection' },
    { id: 'global',     label: 'Browse catalog',  icon: 'globe',    desc: 'Pick products & collections' },
  ];

  return (
    <>
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
      <PageHeader
        icon="shop"
        title="Shopify Stores"
        subtitle="Connect your stores and import products"
        right={
          <button className="btn btn-primary" onClick={() => setConnectOpen(true)}>
            <Icon name="plus" size={15}/>
            Connect a store
          </button>
        }
      />

      <div style={{ flex: 1, overflow: 'auto', padding: 24 }} className="scroll">
        <div style={{ maxWidth: 960, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 24 }}>

          {/* ── Connected stores ── */}
          <div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
              <div>
                <div className="font-display" style={{ fontWeight: 600, fontSize: 15, color: 'var(--text)' }}>
                  Connected stores
                </div>
                <div style={{ fontSize: 13, color: 'var(--text-faint)', marginTop: 2 }}>
                  {stores.length} store{stores.length !== 1 ? 's' : ''} · Click a store to use it in the import panel
                </div>
              </div>
              <button className="btn btn-stroke btn-sm" onClick={() => setConnectOpen(true)}>
                <Icon name="plus" size={13}/>
                Add
              </button>
            </div>

            {stores.length === 0 ? (
              <div style={{
                padding: '40px 24px', borderRadius: 'var(--r-lg)',
                border: '1.5px dashed var(--border)',
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12,
                color: 'var(--text-faint)', textAlign: 'center',
              }}>
                <div style={{
                  width: 52, height: 52, borderRadius: 'var(--r-lg)',
                  background: 'var(--bg-soft)', border: '1px solid var(--border)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <Icon name="shop" size={24} style={{ opacity: 0.5 }}/>
                </div>
                <div>
                  <div style={{ fontWeight: 500, fontSize: 14, color: 'var(--text-muted)', marginBottom: 4 }}>No stores connected</div>
                  <div style={{ fontSize: 13 }}>Connect your first Shopify store to start importing products</div>
                </div>
                <button className="btn btn-primary" onClick={() => setConnectOpen(true)}>
                  <Icon name="plus" size={14}/>
                  Connect a store
                </button>
              </div>
            ) : (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 12 }}>
                {stores.map(store => (
                  <StoreCard
                    key={store.id}
                    store={store}
                    onSync={handleSync}
                    onDisconnect={() => setDisconnectTarget(store)}
                  />
                ))}
                <button
                  onClick={() => setConnectOpen(true)}
                  style={{
                    padding: '14px 16px', borderRadius: 'var(--r-lg)',
                    border: '1.5px dashed var(--border)',
                    background: 'transparent',
                    display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                    gap: 8, cursor: 'pointer', color: 'var(--text-faint)',
                    minHeight: 120,
                    transition: 'border-color .15s, background .15s',
                  }}
                  onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--accent)'; e.currentTarget.style.background = 'var(--accent-soft)'; }}
                  onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.background = 'transparent'; }}
                >
                  <Icon name="plus" size={20}/>
                  <span style={{ fontSize: 13 }}>Add a store</span>
                </button>
              </div>
            )}
          </div>

          {/* ── Import panel ── */}
          {stores.length > 0 && (
            <div>
              <div style={{ marginBottom: 16 }}>
                <div className="font-display" style={{ fontWeight: 600, fontSize: 15, color: 'var(--text)', marginBottom: 2 }}>
                  Import products
                </div>
                <div style={{ fontSize: 13, color: 'var(--text-faint)' }}>
                  Choose your import mode
                </div>
              </div>

              {/* Mode selector */}
              <div style={{ display: 'flex', gap: 8, marginBottom: 20, flexWrap: 'wrap' }}>
                {IMPORT_TABS.map(t => {
                  const active = importTab === t.id;
                  return (
                    <button
                      key={t.id}
                      onClick={() => setImportTab(t.id)}
                      style={{
                        display: 'flex', alignItems: 'center', gap: 10,
                        padding: '10px 16px', borderRadius: 'var(--r-lg)',
                        border: active ? '1.5px solid var(--accent)' : '1px solid var(--border)',
                        background: active ? 'var(--accent-soft)' : 'var(--bg-surface)',
                        cursor: 'pointer', flex: 1, minWidth: 160,
                        transition: 'all .15s', textAlign: 'left',
                      }}
                    >
                      <div style={{
                        width: 34, height: 34, borderRadius: 'var(--r-sm)', flexShrink: 0,
                        background: active ? 'var(--accent)' : 'var(--bg-soft)',
                        border: active ? 'none' : '1px solid var(--border)',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        color: active ? '#fff' : 'var(--text-muted)',
                      }}>
                        <Icon name={t.icon} size={16}/>
                      </div>
                      <div>
                        <div style={{ fontSize: 13, fontWeight: 600, color: active ? 'var(--accent)' : 'var(--text)' }}>
                          {t.label}
                        </div>
                        <div style={{ fontSize: 11, color: active ? 'var(--accent)' : 'var(--text-faint)', marginTop: 1 }}>
                          {t.desc}
                        </div>
                      </div>
                      {active && (
                        <div style={{ marginLeft: 'auto', flexShrink: 0 }}>
                          <Icon name="check" size={14} style={{ color: 'var(--accent)' }}/>
                        </div>
                      )}
                    </button>
                  );
                })}
              </div>

              <div style={{ padding: 24, borderRadius: 'var(--r-xl)', border: '1px solid var(--border)', background: 'var(--bg-surface)' }}>
                {importTab === 'product'    && <ImportByProductUrl stores={stores}/>}
                {importTab === 'collection' && <ImportByCollectionUrl stores={stores}/>}
                {importTab === 'global'     && <ImportGlobal stores={stores}/>}
              </div>
            </div>
          )}

        </div>
      </div>

      {connectOpen && (
        <ConnectStoreModal
          onClose={() => setConnectOpen(false)}
          onConnect={handleConnect}
        />
      )}

      {disconnectTarget && (
        <DisconnectConfirmModal
          store={disconnectTarget}
          onClose={() => setDisconnectTarget(null)}
          onConfirm={() => handleDisconnect(disconnectTarget.id)}
        />
      )}
    </>
  );
};
