mucahitkantepe commited on
Commit
1607a5a
Β·
1 Parent(s): 6241e51

Improve Discover page interactions and taste feedback

Browse files

- Card click opens store page (no more click-to-swipe)
- Drag gesture only triggers on actual movement (>5px threshold)
- Added undo button (+ Ctrl+Z keyboard shortcut)
- Match % badge on each card (green/blue/amber by score)
- Store badge and "tap to view" hint
- Backend: undo endpoint reverts rating + taste model
- Backend: dislikes now saved to taste model (was likes-only)
- Backend: startup sync ensures all discover ratings reflected
- Backend: rescore now rescores ALL products (not just low scores)

backend/app/routers/discover.py CHANGED
@@ -10,29 +10,55 @@ from backend.app.schemas import ProductOut
10
 
11
  router = APIRouter(prefix="/api/discover", tags=["discover"])
12
 
13
- # Track pending re-score state
14
  _rescore_lock = threading.Lock()
15
  _rescore_pending = False
 
16
 
17
 
18
- @router.get("/next", response_model=list[ProductOut])
19
- def get_next_products(count: int = 10):
20
- """Get a batch of unrated products to show in the swipe UI.
 
 
 
21
 
22
- Returns products sorted by score desc that haven't been rated yet.
23
- Skips products without images.
24
- """
25
  store = get_store()
26
  engine = get_engine()
 
 
 
 
 
 
27
 
28
- # Get already-rated product URLs (from the discover_ratings table)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  conn = store.conn
30
  _ensure_discover_table(conn)
 
31
  rated_urls = set(
32
  r[0] for r in conn.execute("SELECT url FROM discover_ratings").fetchall()
33
  )
34
 
35
- # Get top unrated products with images
36
  rows = conn.execute("""
37
  SELECT * FROM products
38
  WHERE image_url != '' AND score > 0
@@ -51,58 +77,84 @@ def get_next_products(count: int = 10):
51
 
52
  @router.post("/rate")
53
  def rate_product(url: str = Body(...), rating: str = Body(...)):
54
- """Rate a product: 'like', 'dislike', or 'skip'.
55
-
56
- Stores the rating and triggers async taste model update when enough
57
- new ratings accumulate.
58
- """
59
  store = get_store()
 
60
  conn = store.conn
61
  _ensure_discover_table(conn)
62
 
63
- # Map string rating to int
64
  rating_val = {"like": 1, "dislike": -1, "skip": 0}.get(rating, 0)
65
 
66
  conn.execute("""
67
- INSERT OR REPLACE INTO discover_ratings (url, rating)
68
- VALUES (?, ?)
69
  """, (url, rating_val))
70
  conn.commit()
71
 
72
- # If liked, also save as a reference image rating for the taste model
73
- if rating_val == 1:
74
- _save_product_as_liked(url, store, get_engine(), get_config())
75
 
76
- # Check if we should trigger a rescore
77
- new_likes = conn.execute(
78
- "SELECT COUNT(*) FROM discover_ratings WHERE rating = 1 AND processed = 0"
79
  ).fetchone()[0]
80
-
81
- if new_likes >= 3:
82
  _trigger_async_rescore()
83
 
84
- total = conn.execute("SELECT COUNT(*) FROM discover_ratings").fetchone()[0]
85
- likes = conn.execute("SELECT COUNT(*) FROM discover_ratings WHERE rating = 1").fetchone()[0]
86
- dislikes = conn.execute("SELECT COUNT(*) FROM discover_ratings WHERE rating = -1").fetchone()[0]
87
 
88
- return {
89
- "ok": True,
90
- "stats": {"total": total, "likes": likes, "dislikes": dislikes},
91
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
 
94
  @router.get("/stats")
95
  def discover_stats():
96
- """Get discover rating statistics."""
97
  store = get_store()
98
  conn = store.conn
99
  _ensure_discover_table(conn)
 
 
100
 
 
101
  total = conn.execute("SELECT COUNT(*) FROM discover_ratings").fetchone()[0]
102
  likes = conn.execute("SELECT COUNT(*) FROM discover_ratings WHERE rating = 1").fetchone()[0]
103
  dislikes = conn.execute("SELECT COUNT(*) FROM discover_ratings WHERE rating = -1").fetchone()[0]
104
  skips = conn.execute("SELECT COUNT(*) FROM discover_ratings WHERE rating = 0").fetchone()[0]
105
-
106
  return {"total": total, "likes": likes, "dislikes": dislikes, "skips": skips}
107
 
108
 
@@ -117,22 +169,19 @@ def _ensure_discover_table(conn):
117
  """)
118
 
119
 
120
- def _save_product_as_liked(url: str, store, engine, config):
121
- """When a product is liked, save its image as a reference for the taste model."""
122
  row = store.conn.execute(
123
  "SELECT image_path FROM products WHERE url = ?", (url,)
124
  ).fetchone()
125
-
126
  if row and row["image_path"]:
127
  p = Path(row["image_path"])
128
  if p.exists():
129
- engine.save_rating(p, 1)
130
 
131
 
132
  def _trigger_async_rescore():
133
- """Trigger an async taste model rebuild + rescore of unscored products."""
134
  global _rescore_pending
135
-
136
  with _rescore_lock:
137
  if _rescore_pending:
138
  return
@@ -143,53 +192,60 @@ def _trigger_async_rescore():
143
 
144
 
145
  def _do_rescore():
146
- """Rebuild taste model with new liked images and rescore products."""
147
  global _rescore_pending
148
-
149
  try:
150
  engine = get_engine()
151
  store = get_store()
152
- config = get_config()
153
 
154
- print("[discover] Rebuilding taste model with new likes...", flush=True)
155
  centroids = engine.build_taste_vector()
156
  if centroids is None:
157
  return
158
 
159
- print(f"[discover] {len(centroids)} clusters. Rescoring unscored...", flush=True)
160
 
161
- # Mark processed
162
  store.conn.execute("UPDATE discover_ratings SET processed = 1 WHERE processed = 0")
163
  store.conn.commit()
164
 
165
- # Rescore products that have low or zero scores
166
  rows = store.conn.execute("""
167
- SELECT url, image_path FROM products
168
- WHERE image_path != '' AND score < 0.5
169
- LIMIT 500
170
  """).fetchall()
171
 
172
- if rows:
173
- paths, urls = [], []
174
- for r in rows:
175
- p = Path(r["image_path"])
176
- if p.exists():
177
- paths.append(p)
178
- urls.append(r["url"])
 
 
179
 
180
- if paths:
181
- scored = engine.score_product_images(paths, centroids)
182
- score_map = {str(path): score for path, score in scored}
 
183
 
184
- for url, path in zip(urls, paths):
185
- s = score_map.get(str(path), 0)
186
- store.update_score(url, s)
187
- store.commit()
188
 
189
- print(f"[discover] Rescored {len(paths)} products.", flush=True)
 
190
 
191
  except Exception as e:
192
  print(f"[discover] Rescore error: {e}", flush=True)
193
  finally:
194
  with _rescore_lock:
195
  _rescore_pending = False
 
 
 
 
 
 
 
 
 
10
 
11
  router = APIRouter(prefix="/api/discover", tags=["discover"])
12
 
 
13
  _rescore_lock = threading.Lock()
14
  _rescore_pending = False
15
+ _synced = False
16
 
17
 
18
+ def _sync_discover_ratings():
19
+ """Ensure all discover ratings are reflected in the taste model."""
20
+ global _synced
21
+ if _synced:
22
+ return
23
+ _synced = True
24
 
 
 
 
25
  store = get_store()
26
  engine = get_engine()
27
+ conn = store.conn
28
+ _ensure_discover_table(conn)
29
+
30
+ rows = conn.execute(
31
+ "SELECT url, rating FROM discover_ratings WHERE rating != 0"
32
+ ).fetchall()
33
 
34
+ synced = 0
35
+ ratings = engine.load_ratings()
36
+ for r in rows:
37
+ img_row = conn.execute("SELECT image_path FROM products WHERE url = ?", (r["url"],)).fetchone()
38
+ if img_row and img_row["image_path"]:
39
+ p = Path(img_row["image_path"])
40
+ resolved = str(p.resolve())
41
+ if p.exists() and resolved not in ratings:
42
+ engine.save_rating(p, r["rating"])
43
+ synced += 1
44
+ ratings[resolved] = r["rating"]
45
+
46
+ if synced:
47
+ print(f"[discover] Synced {synced} ratings to taste model", flush=True)
48
+
49
+
50
+ @router.get("/next", response_model=list[ProductOut])
51
+ def get_next_products(count: int = 10):
52
+ """Get unrated products sorted by score desc."""
53
+ _sync_discover_ratings()
54
+ store = get_store()
55
  conn = store.conn
56
  _ensure_discover_table(conn)
57
+
58
  rated_urls = set(
59
  r[0] for r in conn.execute("SELECT url FROM discover_ratings").fetchall()
60
  )
61
 
 
62
  rows = conn.execute("""
63
  SELECT * FROM products
64
  WHERE image_url != '' AND score > 0
 
77
 
78
  @router.post("/rate")
79
  def rate_product(url: str = Body(...), rating: str = Body(...)):
80
+ """Rate a product: 'like', 'dislike', or 'skip'."""
 
 
 
 
81
  store = get_store()
82
+ engine = get_engine()
83
  conn = store.conn
84
  _ensure_discover_table(conn)
85
 
 
86
  rating_val = {"like": 1, "dislike": -1, "skip": 0}.get(rating, 0)
87
 
88
  conn.execute("""
89
+ INSERT OR REPLACE INTO discover_ratings (url, rating, processed)
90
+ VALUES (?, ?, 0)
91
  """, (url, rating_val))
92
  conn.commit()
93
 
94
+ # Save liked/disliked images to taste model immediately
95
+ if rating_val in (1, -1):
96
+ _save_product_rating(url, rating_val, store, engine)
97
 
98
+ # Trigger rescore after enough new feedback
99
+ unprocessed = conn.execute(
100
+ "SELECT COUNT(*) FROM discover_ratings WHERE processed = 0 AND rating != 0"
101
  ).fetchone()[0]
102
+ if unprocessed >= 3:
 
103
  _trigger_async_rescore()
104
 
105
+ return {"ok": True, "stats": _get_stats(conn)}
 
 
106
 
107
+
108
+ @router.post("/undo")
109
+ def undo_last_rating():
110
+ """Undo the most recent rating β€” remove from DB and revert taste model."""
111
+ store = get_store()
112
+ engine = get_engine()
113
+ conn = store.conn
114
+ _ensure_discover_table(conn)
115
+
116
+ last = conn.execute(
117
+ "SELECT url, rating FROM discover_ratings ORDER BY created_at DESC LIMIT 1"
118
+ ).fetchone()
119
+
120
+ if not last:
121
+ return {"ok": False, "message": "Nothing to undo"}
122
+
123
+ url = last["url"]
124
+ old_rating = last["rating"]
125
+
126
+ # Remove the rating
127
+ conn.execute("DELETE FROM discover_ratings WHERE url = ?", (url,))
128
+ conn.commit()
129
+
130
+ # Revert taste model: if was liked, remove from ratings
131
+ if old_rating in (1, -1):
132
+ row = conn.execute("SELECT image_path FROM products WHERE url = ?", (url,)).fetchone()
133
+ if row and row["image_path"]:
134
+ p = Path(row["image_path"])
135
+ if p.exists():
136
+ engine.clear_ratings([p])
137
+
138
+ # Get the undone product to return to frontend
139
+ product_row = conn.execute("SELECT * FROM products WHERE url = ?", (url,)).fetchone()
140
+ product = ProductOut(**dict(product_row)) if product_row else None
141
+
142
+ return {"ok": True, "product": product, "stats": _get_stats(conn)}
143
 
144
 
145
  @router.get("/stats")
146
  def discover_stats():
 
147
  store = get_store()
148
  conn = store.conn
149
  _ensure_discover_table(conn)
150
+ return _get_stats(conn)
151
+
152
 
153
+ def _get_stats(conn) -> dict:
154
  total = conn.execute("SELECT COUNT(*) FROM discover_ratings").fetchone()[0]
155
  likes = conn.execute("SELECT COUNT(*) FROM discover_ratings WHERE rating = 1").fetchone()[0]
156
  dislikes = conn.execute("SELECT COUNT(*) FROM discover_ratings WHERE rating = -1").fetchone()[0]
157
  skips = conn.execute("SELECT COUNT(*) FROM discover_ratings WHERE rating = 0").fetchone()[0]
 
158
  return {"total": total, "likes": likes, "dislikes": dislikes, "skips": skips}
159
 
160
 
 
169
  """)
170
 
171
 
172
+ def _save_product_rating(url: str, rating_val: int, store, engine):
173
+ """Save product image as liked (1) or disliked (-1) in the taste engine."""
174
  row = store.conn.execute(
175
  "SELECT image_path FROM products WHERE url = ?", (url,)
176
  ).fetchone()
 
177
  if row and row["image_path"]:
178
  p = Path(row["image_path"])
179
  if p.exists():
180
+ engine.save_rating(p, rating_val)
181
 
182
 
183
  def _trigger_async_rescore():
 
184
  global _rescore_pending
 
185
  with _rescore_lock:
186
  if _rescore_pending:
187
  return
 
192
 
193
 
194
  def _do_rescore():
195
+ """Rebuild taste model with all feedback and rescore products."""
196
  global _rescore_pending
 
197
  try:
198
  engine = get_engine()
199
  store = get_store()
 
200
 
201
+ print("[discover] Rebuilding taste model...", flush=True)
202
  centroids = engine.build_taste_vector()
203
  if centroids is None:
204
  return
205
 
206
+ print(f"[discover] {len(centroids)} clusters. Rescoring...", flush=True)
207
 
208
+ # Mark all as processed
209
  store.conn.execute("UPDATE discover_ratings SET processed = 1 WHERE processed = 0")
210
  store.conn.commit()
211
 
212
+ # Rescore ALL products (not just low scores β€” taste changed)
213
  rows = store.conn.execute("""
214
+ SELECT url, image_path FROM products WHERE image_path != ''
 
 
215
  """).fetchall()
216
 
217
+ batch_size = 100
218
+ total_rescored = 0
219
+ paths_batch, urls_batch = [], []
220
+
221
+ for r in rows:
222
+ p = Path(r["image_path"])
223
+ if p.exists():
224
+ paths_batch.append(p)
225
+ urls_batch.append(r["url"])
226
 
227
+ if len(paths_batch) >= batch_size:
228
+ _score_batch(engine, store, paths_batch, urls_batch, centroids)
229
+ total_rescored += len(paths_batch)
230
+ paths_batch, urls_batch = [], []
231
 
232
+ if paths_batch:
233
+ _score_batch(engine, store, paths_batch, urls_batch, centroids)
234
+ total_rescored += len(paths_batch)
 
235
 
236
+ store.commit()
237
+ print(f"[discover] Rescored {total_rescored} products.", flush=True)
238
 
239
  except Exception as e:
240
  print(f"[discover] Rescore error: {e}", flush=True)
241
  finally:
242
  with _rescore_lock:
243
  _rescore_pending = False
244
+
245
+
246
+ def _score_batch(engine, store, paths, urls, centroids):
247
+ scored = engine.score_product_images(paths, centroids)
248
+ score_map = {str(path): score for path, score in scored}
249
+ for url, path in zip(urls, paths):
250
+ s = score_map.get(str(path), 0)
251
+ store.update_score(url, s)
frontend/src/api.ts CHANGED
@@ -101,6 +101,14 @@ export async function rateDiscoverProduct(
101
  });
102
  }
103
 
 
 
 
 
 
 
 
 
104
  export async function getDiscoverStats(): Promise<DiscoverStats> {
105
  return request<DiscoverStats>("/discover/stats");
106
  }
 
101
  });
102
  }
103
 
104
+ export async function undoDiscoverRating(): Promise<{
105
+ ok: boolean;
106
+ product: Product | null;
107
+ stats: DiscoverStats;
108
+ }> {
109
+ return request("/discover/undo", { method: "POST" });
110
+ }
111
+
112
  export async function getDiscoverStats(): Promise<DiscoverStats> {
113
  return request<DiscoverStats>("/discover/stats");
114
  }
frontend/src/index.css CHANGED
@@ -741,6 +741,41 @@ select:focus {
741
  background: rgba(0,0,0,0.5);
742
  }
743
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
744
  .swipe-buttons {
745
  display: flex;
746
  gap: 20px;
@@ -768,6 +803,9 @@ select:focus {
768
  .swipe-btn.dislike:hover { background: rgba(239,68,68,0.15); }
769
  .swipe-btn.skip { border-color: var(--amber); color: var(--amber); width: 48px; height: 48px; }
770
  .swipe-btn.skip:hover { background: rgba(245,158,11,0.15); }
 
 
 
771
 
772
  .discover-shortcuts {
773
  font-size: 12px;
 
741
  background: rgba(0,0,0,0.5);
742
  }
743
 
744
+ .swipe-match-badge {
745
+ position: absolute;
746
+ top: 12px;
747
+ right: 12px;
748
+ padding: 4px 10px;
749
+ border-radius: 8px;
750
+ font-size: 12px;
751
+ font-weight: 700;
752
+ color: #fff;
753
+ z-index: 5;
754
+ }
755
+
756
+ .swipe-details {
757
+ display: flex;
758
+ align-items: center;
759
+ gap: 8px;
760
+ margin-top: 4px;
761
+ }
762
+
763
+ .swipe-store-badge {
764
+ font-size: 11px;
765
+ padding: 2px 8px;
766
+ background: rgba(59,130,246,0.2);
767
+ color: var(--accent);
768
+ border-radius: 4px;
769
+ font-weight: 600;
770
+ }
771
+
772
+ .swipe-view-hint {
773
+ font-size: 11px;
774
+ color: var(--text-muted);
775
+ margin-top: 4px;
776
+ opacity: 0.7;
777
+ }
778
+
779
  .swipe-buttons {
780
  display: flex;
781
  gap: 20px;
 
803
  .swipe-btn.dislike:hover { background: rgba(239,68,68,0.15); }
804
  .swipe-btn.skip { border-color: var(--amber); color: var(--amber); width: 48px; height: 48px; }
805
  .swipe-btn.skip:hover { background: rgba(245,158,11,0.15); }
806
+ .swipe-btn.undo { border-color: var(--text-muted); color: var(--text-muted); width: 44px; height: 44px; }
807
+ .swipe-btn.undo:hover { background: rgba(163,163,163,0.1); border-color: var(--text-secondary); }
808
+ .swipe-btn:disabled { opacity: 0.25; cursor: default; transform: none !important; }
809
 
810
  .discover-shortcuts {
811
  font-size: 12px;
frontend/src/pages/DiscoverPage.tsx CHANGED
@@ -1,6 +1,6 @@
1
- import { useState, useEffect, useCallback } from "react";
2
  import type { Product, DiscoverStats } from "../types";
3
- import { getDiscoverProducts, rateDiscoverProduct } from "../api";
4
 
5
  export function DiscoverPage() {
6
  const [products, setProducts] = useState<Product[]>([]);
@@ -11,7 +11,11 @@ export function DiscoverPage() {
11
  const [dragX, setDragX] = useState(0);
12
  const [dragY, setDragY] = useState(0);
13
  const [dragging, setDragging] = useState(false);
 
14
  const [startPos, setStartPos] = useState({ x: 0, y: 0 });
 
 
 
15
 
16
  const loadProducts = useCallback(async () => {
17
  setLoading(true);
@@ -38,6 +42,9 @@ export function DiscoverPage() {
38
  const direction = rating === "like" ? "right" : rating === "dislike" ? "left" : "up";
39
  setSwiping(direction);
40
 
 
 
 
41
  try {
42
  const result = await rateDiscoverProduct(current.url, rating);
43
  setStats(result.stats);
@@ -57,17 +64,47 @@ export function DiscoverPage() {
57
  }, 300);
58
  };
59
 
60
- // Mouse/touch drag handlers
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  const handlePointerDown = (e: React.PointerEvent) => {
62
  setDragging(true);
 
63
  setStartPos({ x: e.clientX, y: e.clientY });
64
  (e.target as HTMLElement).setPointerCapture(e.pointerId);
65
  };
66
 
67
  const handlePointerMove = (e: React.PointerEvent) => {
68
  if (!dragging) return;
69
- setDragX(e.clientX - startPos.x);
70
- setDragY(e.clientY - startPos.y);
 
 
 
71
  };
72
 
73
  const handlePointerUp = () => {
@@ -93,12 +130,12 @@ export function DiscoverPage() {
93
  if (e.key === "ArrowRight") handleRate("like");
94
  else if (e.key === "ArrowLeft") handleRate("dislike");
95
  else if (e.key === "ArrowUp") handleRate("skip");
 
96
  };
97
  window.addEventListener("keydown", handler);
98
  return () => window.removeEventListener("keydown", handler);
99
  });
100
 
101
- // Card transform based on drag
102
  const getCardStyle = () => {
103
  if (swiping === "right") return { transform: "translateX(120%) rotate(20deg)", opacity: 0, transition: "all 0.3s ease-out" };
104
  if (swiping === "left") return { transform: "translateX(-120%) rotate(-20deg)", opacity: 0, transition: "all 0.3s ease-out" };
@@ -110,7 +147,6 @@ export function DiscoverPage() {
110
  return { transform: "translate(0, 0) rotate(0deg)", transition: "all 0.3s ease-out" };
111
  };
112
 
113
- // Swipe indicator overlay
114
  const getIndicator = () => {
115
  if (swiping === "right" || dragX > 60) return { text: "LIKE", color: "#22c55e", opacity: Math.min(1, (swiping ? 1 : Math.abs(dragX) / 100)) };
116
  if (swiping === "left" || dragX < -60) return { text: "NOPE", color: "#ef4444", opacity: Math.min(1, (swiping ? 1 : Math.abs(dragX) / 100)) };
@@ -119,6 +155,8 @@ export function DiscoverPage() {
119
  };
120
 
121
  const indicator = getIndicator();
 
 
122
 
123
  if (loading) {
124
  return <div className="discover-container"><p className="discover-loading">Loading products...</p></div>;
@@ -130,7 +168,7 @@ export function DiscoverPage() {
130
  <div className="discover-empty">
131
  <h2>All caught up!</h2>
132
  <p>No more products to discover. Run a new scan to find more.</p>
133
- <button className="btn-primary" onClick={loadProducts}>Refresh</button>
134
  </div>
135
  </div>
136
  );
@@ -140,26 +178,25 @@ export function DiscoverPage() {
140
  <div className="discover-container">
141
  <div className="discover-header">
142
  <h1>Discover</h1>
143
- <p className="subtitle">Swipe right to like, left to dislike, up to skip</p>
144
  </div>
145
 
146
  <div className="discover-stats-bar">
147
  <span className="discover-stat like-stat">{stats.likes} liked</span>
148
- <span className="discover-stat dislike-stat">{stats.dislikes} disliked</span>
149
  <span className="discover-stat skip-stat">{stats.skips} skipped</span>
150
- <span className="discover-stat">{products.length - currentIndex - 1} remaining</span>
151
  </div>
152
 
153
  <div className="swipe-area">
154
- {/* Next card (behind) */}
155
  {next && (
156
  <div className="swipe-card swipe-card-behind">
157
  <img src={next.image_url} alt={next.name} />
158
  </div>
159
  )}
160
 
161
- {/* Current card */}
162
  <div
 
163
  className="swipe-card swipe-card-active"
164
  style={getCardStyle()}
165
  onPointerDown={handlePointerDown}
@@ -174,15 +211,28 @@ export function DiscoverPage() {
174
  {indicator.text}
175
  </div>
176
  )}
177
- <img src={current.image_url} alt={current.name} draggable={false} />
178
- <div className="swipe-card-info">
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  <div className="swipe-brand">{current.brand}</div>
180
  <div className="swipe-name">{current.name}</div>
181
- <div className="swipe-meta">
182
- <span className="swipe-store">{current.store}</span>
183
  <span className="swipe-price">{current.price_text || `${current.price_nok} kr`}</span>
184
- <span className="swipe-score">{Math.round(current.score * 100)}%</span>
185
  </div>
 
186
  </div>
187
  </div>
188
  </div>
@@ -191,6 +241,14 @@ export function DiscoverPage() {
191
  <button className="swipe-btn dislike" onClick={() => handleRate("dislike")} title="Dislike (←)">
192
  <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
193
  </button>
 
 
 
 
 
 
 
 
194
  <button className="swipe-btn skip" onClick={() => handleRate("skip")} title="Skip (↑)">
195
  <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="18 15 12 9 6 15"/></svg>
196
  </button>
@@ -200,7 +258,7 @@ export function DiscoverPage() {
200
  </div>
201
 
202
  <div className="discover-shortcuts">
203
- <kbd>←</kbd> Dislike &nbsp; <kbd>↑</kbd> Skip &nbsp; <kbd>β†’</kbd> Like
204
  </div>
205
  </div>
206
  );
 
1
+ import { useState, useEffect, useCallback, useRef } from "react";
2
  import type { Product, DiscoverStats } from "../types";
3
+ import { getDiscoverProducts, rateDiscoverProduct, undoDiscoverRating } from "../api";
4
 
5
  export function DiscoverPage() {
6
  const [products, setProducts] = useState<Product[]>([]);
 
11
  const [dragX, setDragX] = useState(0);
12
  const [dragY, setDragY] = useState(0);
13
  const [dragging, setDragging] = useState(false);
14
+ const [dragMoved, setDragMoved] = useState(false);
15
  const [startPos, setStartPos] = useState({ x: 0, y: 0 });
16
+ const [history, setHistory] = useState<Product[]>([]);
17
+
18
+ const cardRef = useRef<HTMLDivElement>(null);
19
 
20
  const loadProducts = useCallback(async () => {
21
  setLoading(true);
 
42
  const direction = rating === "like" ? "right" : rating === "dislike" ? "left" : "up";
43
  setSwiping(direction);
44
 
45
+ // Save to undo history
46
+ setHistory((h) => [...h, current]);
47
+
48
  try {
49
  const result = await rateDiscoverProduct(current.url, rating);
50
  setStats(result.stats);
 
64
  }, 300);
65
  };
66
 
67
+ const handleUndo = async () => {
68
+ if (history.length === 0 || swiping) return;
69
+
70
+ try {
71
+ const result = await undoDiscoverRating();
72
+ if (result.ok && result.product) {
73
+ setStats(result.stats);
74
+ // Put the product back
75
+ if (currentIndex > 0) {
76
+ setCurrentIndex((i) => i - 1);
77
+ } else {
78
+ setProducts((prev) => [result.product!, ...prev]);
79
+ }
80
+ setHistory((h) => h.slice(0, -1));
81
+ }
82
+ } catch (e) {
83
+ console.error("Undo failed:", e);
84
+ }
85
+ };
86
+
87
+ // Card click β€” open store page (only if didn't drag)
88
+ const handleCardClick = () => {
89
+ if (!current || dragMoved) return;
90
+ window.open(current.url, "_blank");
91
+ };
92
+
93
+ // Drag handlers β€” only on the drag handle area, not the whole card
94
  const handlePointerDown = (e: React.PointerEvent) => {
95
  setDragging(true);
96
+ setDragMoved(false);
97
  setStartPos({ x: e.clientX, y: e.clientY });
98
  (e.target as HTMLElement).setPointerCapture(e.pointerId);
99
  };
100
 
101
  const handlePointerMove = (e: React.PointerEvent) => {
102
  if (!dragging) return;
103
+ const dx = e.clientX - startPos.x;
104
+ const dy = e.clientY - startPos.y;
105
+ if (Math.abs(dx) > 5 || Math.abs(dy) > 5) setDragMoved(true);
106
+ setDragX(dx);
107
+ setDragY(dy);
108
  };
109
 
110
  const handlePointerUp = () => {
 
130
  if (e.key === "ArrowRight") handleRate("like");
131
  else if (e.key === "ArrowLeft") handleRate("dislike");
132
  else if (e.key === "ArrowUp") handleRate("skip");
133
+ else if (e.key === "z" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); handleUndo(); }
134
  };
135
  window.addEventListener("keydown", handler);
136
  return () => window.removeEventListener("keydown", handler);
137
  });
138
 
 
139
  const getCardStyle = () => {
140
  if (swiping === "right") return { transform: "translateX(120%) rotate(20deg)", opacity: 0, transition: "all 0.3s ease-out" };
141
  if (swiping === "left") return { transform: "translateX(-120%) rotate(-20deg)", opacity: 0, transition: "all 0.3s ease-out" };
 
147
  return { transform: "translate(0, 0) rotate(0deg)", transition: "all 0.3s ease-out" };
148
  };
149
 
 
150
  const getIndicator = () => {
151
  if (swiping === "right" || dragX > 60) return { text: "LIKE", color: "#22c55e", opacity: Math.min(1, (swiping ? 1 : Math.abs(dragX) / 100)) };
152
  if (swiping === "left" || dragX < -60) return { text: "NOPE", color: "#ef4444", opacity: Math.min(1, (swiping ? 1 : Math.abs(dragX) / 100)) };
 
155
  };
156
 
157
  const indicator = getIndicator();
158
+ const matchPct = current ? Math.round(current.score * 100) : 0;
159
+ const matchColor = matchPct >= 70 ? "var(--green)" : matchPct >= 40 ? "var(--accent)" : "var(--amber)";
160
 
161
  if (loading) {
162
  return <div className="discover-container"><p className="discover-loading">Loading products...</p></div>;
 
168
  <div className="discover-empty">
169
  <h2>All caught up!</h2>
170
  <p>No more products to discover. Run a new scan to find more.</p>
171
+ <button className="btn btn-primary" onClick={loadProducts}>Refresh</button>
172
  </div>
173
  </div>
174
  );
 
178
  <div className="discover-container">
179
  <div className="discover-header">
180
  <h1>Discover</h1>
181
+ <p className="subtitle">Drag to swipe, or use buttons below. Click image to view in store.</p>
182
  </div>
183
 
184
  <div className="discover-stats-bar">
185
  <span className="discover-stat like-stat">{stats.likes} liked</span>
186
+ <span className="discover-stat dislike-stat">{stats.dislikes} nope</span>
187
  <span className="discover-stat skip-stat">{stats.skips} skipped</span>
188
+ <span className="discover-stat">{products.length - currentIndex - 1} left</span>
189
  </div>
190
 
191
  <div className="swipe-area">
 
192
  {next && (
193
  <div className="swipe-card swipe-card-behind">
194
  <img src={next.image_url} alt={next.name} />
195
  </div>
196
  )}
197
 
 
198
  <div
199
+ ref={cardRef}
200
  className="swipe-card swipe-card-active"
201
  style={getCardStyle()}
202
  onPointerDown={handlePointerDown}
 
211
  {indicator.text}
212
  </div>
213
  )}
214
+
215
+ {/* Match badge */}
216
+ <div className="swipe-match-badge" style={{ background: matchColor }}>
217
+ {matchPct}% match
218
+ </div>
219
+
220
+ <img
221
+ src={current.image_url}
222
+ alt={current.name}
223
+ draggable={false}
224
+ onClick={handleCardClick}
225
+ style={{ cursor: "pointer" }}
226
+ />
227
+
228
+ <div className="swipe-card-info" onClick={handleCardClick} style={{ cursor: "pointer" }}>
229
  <div className="swipe-brand">{current.brand}</div>
230
  <div className="swipe-name">{current.name}</div>
231
+ <div className="swipe-details">
 
232
  <span className="swipe-price">{current.price_text || `${current.price_nok} kr`}</span>
233
+ <span className="swipe-store-badge">{current.store}</span>
234
  </div>
235
+ <div className="swipe-view-hint">Tap to view in store &rarr;</div>
236
  </div>
237
  </div>
238
  </div>
 
241
  <button className="swipe-btn dislike" onClick={() => handleRate("dislike")} title="Dislike (←)">
242
  <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
243
  </button>
244
+ <button
245
+ className="swipe-btn undo"
246
+ onClick={handleUndo}
247
+ disabled={history.length === 0}
248
+ title="Undo (Ctrl+Z)"
249
+ >
250
+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></svg>
251
+ </button>
252
  <button className="swipe-btn skip" onClick={() => handleRate("skip")} title="Skip (↑)">
253
  <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="18 15 12 9 6 15"/></svg>
254
  </button>
 
258
  </div>
259
 
260
  <div className="discover-shortcuts">
261
+ <kbd>←</kbd> Nope &nbsp; <kbd>↑</kbd> Skip &nbsp; <kbd>β†’</kbd> Like &nbsp; <kbd>Ctrl+Z</kbd> Undo
262
  </div>
263
  </div>
264
  );