feat(admin): redesign product form modal (Atelier des Récoltes)

Replace the basic add/edit product modal with an editorial two-column
layout featuring Fraunces display serif, IBM Plex Mono section labels,
a custom drop zone, visual type cards, and pill toggles. Add a brand
selector visible only to platform admins to fix the 'Brand ID is
required' / RLS error when creating products without an assigned brand.

- Add ProductFormModal with two-column layout (image hero + form)
- Add Fraunces / IBM Plex Mono / Inter Tight via next/font/google
- Add atelier-* design system to globals.css
- Wire brand picker through page server component -> client
- Convert ProductsClient image handling to callback shape
- Move all submit/validation/upload logic into the new modal
This commit is contained in:
2026-06-04 19:49:03 +00:00
parent 8bca9e86b1
commit 69767eb250
4 changed files with 1477 additions and 394 deletions
+15 -1
View File
@@ -3,6 +3,7 @@ import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import AdminAccessDenied from "@/components/admin/AdminAccessDenied";
import ProductsClient from "@/components/admin/ProductsClient";
import { getBrands } from "@/actions/admin/users";
// Icon for page header
const PackageIcon = () => (
@@ -32,6 +33,14 @@ export default async function AdminProductsPage() {
const activeBrandId = await getActiveBrandId(adminUser);
const brandId = activeBrandId;
const isPlatformAdmin = adminUser.role === "platform_admin";
// Platform admins need a brand picker for new products
let brands: { id: string; name: string }[] = [];
if (isPlatformAdmin) {
const result = await getBrands();
brands = result.brands ?? [];
}
let query = supabase
.from("products")
@@ -71,7 +80,12 @@ export default async function AdminProductsPage() {
return (
<div className="min-h-screen bg-[var(--admin-bg)]">
<ProductsClient products={products ?? []} brandId={brandId ?? undefined} />
<ProductsClient
products={products ?? []}
brandId={brandId ?? undefined}
brands={brands}
isPlatformAdmin={isPlatformAdmin}
/>
</div>
);
}
+583
View File
@@ -447,3 +447,586 @@ select:-webkit-autofill:focus {
.transition-glass {
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
/* ─── Editorial Modal — "Atelier des Récoltes" ───────────────── */
/* Warm cream canvas for the modal — like aged paper */
.atelier-canvas {
background-color: #FAF7F0;
background-image:
radial-gradient(ellipse 70% 50% at 15% 0%, rgba(180, 155, 100, 0.10) 0%, transparent 55%),
radial-gradient(ellipse 60% 45% at 100% 100%, rgba(34, 78, 47, 0.06) 0%, transparent 55%);
position: relative;
}
/* Subtle grain texture for tactile feel */
.atelier-grain {
position: absolute;
inset: 0;
pointer-events: none;
opacity: 0.35;
mix-blend-mode: multiply;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix values='0 0 0 0 0.18 0 0 0 0 0.15 0 0 0 0 0.10 0 0 0 0.045 0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
}
/* Botanical wreath / corner ornament */
.atelier-flourish {
background-image: url("data:image/svg+xml,%3Csvg width='80' height='80' viewBox='0 0 80 80' xmlns='http://www.w3.org/2000/svg' fill='none' stroke='%23224E2F' stroke-width='1.2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M10 40 Q 25 20 40 30 Q 55 40 70 30'/%3E%3Cpath d='M22 32 Q 25 28 28 30'/%3E%3Cpath d='M52 38 Q 55 34 58 36'/%3E%3Cpath d='M14 45 Q 18 50 24 48'/%3E%3Ccircle cx='40' cy='30' r='2' fill='%23224E2F'/%3E%3C/svg%3E");
background-repeat: no-repeat;
}
/* The big editorial numeral — large, italic, gold */
.atelier-numeral {
font-family: var(--font-fraunces);
font-style: italic;
font-weight: 500;
font-variation-settings: "opsz" 144, "SOFT" 30;
line-height: 0.85;
letter-spacing: -0.04em;
background: linear-gradient(135deg, #CA8A04 0%, #854D0E 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
/* Editorial title — Fraunces with optical sizing */
.atelier-title {
font-family: var(--font-fraunces);
font-weight: 500;
font-variation-settings: "opsz" 144, "SOFT" 50;
letter-spacing: -0.025em;
line-height: 0.95;
color: #1C1917;
}
.atelier-italic {
font-family: var(--font-fraunces);
font-style: italic;
font-variation-settings: "opsz" 14, "SOFT" 100;
color: #786B53;
}
/* Section label — monospace, small caps style */
.atelier-section-label {
font-family: var(--font-fragment-mono);
font-size: 10px;
font-weight: 500;
letter-spacing: 0.18em;
text-transform: uppercase;
color: #786B53;
}
/* Section number badge */
.atelier-section-num {
font-family: var(--font-fragment-mono);
font-size: 11px;
font-weight: 500;
letter-spacing: 0.05em;
color: #CA8A04;
display: inline-flex;
align-items: center;
gap: 6px;
}
.atelier-section-num::before {
content: '';
display: inline-block;
width: 18px;
height: 1px;
background: linear-gradient(to right, #CA8A04, transparent);
}
/* Editorial hairline rule with fade at edges */
.atelier-rule {
height: 1px;
background: linear-gradient(to right, transparent, rgba(180, 155, 100, 0.4) 20%, rgba(34, 78, 47, 0.3) 50%, rgba(180, 155, 100, 0.4) 80%, transparent);
border: 0;
}
/* Input fields — bottom border only, editorial */
.atelier-input {
font-family: var(--font-manrope);
font-size: 15px;
font-weight: 400;
color: #1C1917;
background: transparent;
border: 0;
border-bottom: 1.5px solid rgba(28, 25, 23, 0.12);
border-radius: 0;
padding: 10px 0 10px 0;
width: 100%;
outline: none;
transition: border-color 220ms cubic-bezier(0.4, 0, 0.2, 1), padding 220ms cubic-bezier(0.4, 0, 0.2, 1);
}
.atelier-input::placeholder {
color: #A8A29E;
font-style: italic;
font-family: var(--font-fraunces);
font-variation-settings: "opsz" 14, "SOFT" 100;
}
.atelier-input:hover {
border-bottom-color: rgba(28, 25, 23, 0.28);
}
.atelier-input:focus {
border-bottom-color: #224E2F;
border-bottom-width: 2px;
padding-bottom: 9.5px;
}
.atelier-input.is-error {
border-bottom-color: #B91C1C;
}
/* Large display input — name field */
.atelier-input--display {
font-family: var(--font-fraunces);
font-size: 28px;
font-weight: 500;
font-variation-settings: "opsz" 144, "SOFT" 50;
letter-spacing: -0.02em;
padding: 8px 0 14px 0;
}
.atelier-input--display::placeholder {
color: #D6D3D1;
font-style: italic;
font-variation-settings: "opsz" 144, "SOFT" 100;
}
.atelier-input--display:focus {
border-bottom-width: 2.5px;
padding-bottom: 13px;
}
/* Price input — large currency treatment */
.atelier-price {
font-family: var(--font-fraunces);
font-variation-settings: "opsz" 144, "SOFT" 50;
font-weight: 500;
font-size: 38px;
letter-spacing: -0.03em;
color: #1C1917;
background: transparent;
border: 0;
border-bottom: 2px solid #224E2F;
border-radius: 0;
padding: 4px 0 12px 36px;
width: 100%;
outline: none;
transition: border-color 200ms ease;
-moz-appearance: textfield;
}
.atelier-price::-webkit-outer-spin-button,
.atelier-price::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
.atelier-price:focus {
border-bottom-color: #14532D;
border-bottom-width: 2.5px;
}
.atelier-price-sigil {
font-family: var(--font-fraunces);
font-style: italic;
font-weight: 400;
font-size: 38px;
color: #CA8A04;
position: absolute;
left: 0;
top: 4px;
pointer-events: none;
line-height: 1;
}
/* Type selector — visual cards */
.atelier-type-card {
position: relative;
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
padding: 14px 14px 12px;
background: rgba(255, 255, 255, 0.6);
border: 1.5px solid rgba(28, 25, 23, 0.10);
border-radius: 10px;
cursor: pointer;
transition: all 220ms cubic-bezier(0.4, 0, 0.2, 1);
text-align: left;
width: 100%;
min-height: 92px;
overflow: hidden;
}
.atelier-type-card::before {
content: '';
position: absolute;
inset: 0;
background: linear-gradient(135deg, rgba(34, 78, 47, 0.02) 0%, transparent 60%);
opacity: 0;
transition: opacity 220ms ease;
pointer-events: none;
}
.atelier-type-card:hover {
border-color: rgba(34, 78, 47, 0.25);
background: rgba(255, 255, 255, 0.85);
transform: translateY(-1px);
}
.atelier-type-card:hover::before {
opacity: 1;
}
.atelier-type-card:active {
transform: translateY(0) scale(0.985);
}
.atelier-type-card.is-selected {
background: linear-gradient(135deg, #224E2F 0%, #14532D 100%);
border-color: #14532D;
box-shadow: 0 8px 24px -8px rgba(20, 83, 45, 0.45), inset 0 1px 0 rgba(255, 255, 255, 0.10);
}
.atelier-type-card.is-selected::before {
opacity: 0;
}
.atelier-type-card .atelier-type-icon {
color: #786B53;
transition: color 220ms ease, transform 220ms ease;
}
.atelier-type-card.is-selected .atelier-type-icon {
color: #FCD34D;
transform: scale(1.06);
}
.atelier-type-card .atelier-type-name {
font-family: var(--font-fraunces);
font-size: 14px;
font-weight: 500;
font-variation-settings: "opsz" 14, "SOFT" 30;
letter-spacing: -0.01em;
color: #1C1917;
transition: color 220ms ease;
}
.atelier-type-card.is-selected .atelier-type-name {
color: #FFFFFF;
}
.atelier-type-card .atelier-type-check {
opacity: 0;
color: #FCD34D;
transform: scale(0.6);
transition: opacity 200ms ease, transform 200ms ease;
}
.atelier-type-card.is-selected .atelier-type-check {
opacity: 1;
transform: scale(1);
}
/* Pill toggle — Active / Taxable */
.atelier-toggle {
display: inline-flex;
align-items: center;
gap: 12px;
cursor: pointer;
user-select: none;
}
.atelier-toggle-track {
position: relative;
width: 38px;
height: 22px;
background: rgba(28, 25, 23, 0.12);
border-radius: 999px;
transition: background 220ms ease;
flex-shrink: 0;
}
.atelier-toggle.is-on .atelier-toggle-track {
background: linear-gradient(135deg, #224E2F 0%, #16A34A 100%);
box-shadow: 0 2px 8px -2px rgba(34, 78, 47, 0.4);
}
.atelier-toggle.is-on.is-gold .atelier-toggle-track {
background: linear-gradient(135deg, #CA8A04 0%, #EAB308 100%);
box-shadow: 0 2px 8px -2px rgba(202, 138, 4, 0.4);
}
.atelier-toggle-thumb {
position: absolute;
top: 2px;
left: 2px;
width: 18px;
height: 18px;
background: #FFFFFF;
border-radius: 999px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
transition: transform 240ms cubic-bezier(0.34, 1.56, 0.64, 1);
}
.atelier-toggle.is-on .atelier-toggle-thumb {
transform: translateX(16px);
}
.atelier-toggle-label {
font-family: var(--font-fragment-mono);
font-size: 11px;
font-weight: 500;
letter-spacing: 0.12em;
text-transform: uppercase;
color: #786B53;
transition: color 220ms ease;
}
.atelier-toggle.is-on .atelier-toggle-label {
color: #1C1917;
}
/* Image drop zone — large square with botanical treatment */
.atelier-drop {
position: relative;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
aspect-ratio: 1 / 1;
background: rgba(255, 255, 255, 0.5);
border: 1.5px dashed rgba(34, 78, 47, 0.25);
border-radius: 14px;
cursor: pointer;
transition: all 280ms cubic-bezier(0.4, 0, 0.2, 1);
overflow: hidden;
}
.atelier-drop::before {
content: '';
position: absolute;
inset: 12px;
border: 1px solid rgba(180, 155, 100, 0.18);
border-radius: 10px;
pointer-events: none;
}
.atelier-drop::after {
content: '';
position: absolute;
inset: 0;
background: radial-gradient(circle at center, rgba(34, 78, 47, 0.02) 0%, transparent 70%);
pointer-events: none;
}
.atelier-drop:hover {
border-color: rgba(34, 78, 47, 0.45);
background: rgba(255, 255, 255, 0.75);
transform: scale(1.005);
}
.atelier-drop.is-drag {
border-color: #224E2F;
border-style: solid;
background: rgba(34, 78, 47, 0.04);
transform: scale(1.01);
}
.atelier-drop.is-error {
border-color: #B91C1C;
background: rgba(185, 28, 28, 0.03);
}
.atelier-drop.has-image {
border-style: solid;
border-color: rgba(34, 78, 47, 0.3);
background: #FFFFFF;
}
.atelier-drop-eyebrow {
font-family: var(--font-fragment-mono);
font-size: 9px;
font-weight: 500;
letter-spacing: 0.2em;
text-transform: uppercase;
color: #A8A29E;
margin-top: -4px;
}
.atelier-drop-title {
font-family: var(--font-fraunces);
font-style: italic;
font-size: 18px;
font-variation-settings: "opsz" 14, "SOFT" 100;
color: #57534E;
text-align: center;
line-height: 1.2;
}
.atelier-drop-hint {
font-family: var(--font-manrope);
font-size: 11px;
color: #A8A29E;
letter-spacing: 0.01em;
}
/* Status pill in corner of image */
.atelier-status-pill {
position: absolute;
top: 14px;
right: 14px;
display: inline-flex;
align-items: center;
gap: 6px;
padding: 5px 10px 5px 8px;
background: rgba(255, 255, 255, 0.95);
border: 1px solid rgba(28, 25, 23, 0.08);
border-radius: 999px;
font-family: var(--font-fragment-mono);
font-size: 9px;
font-weight: 500;
letter-spacing: 0.15em;
text-transform: uppercase;
color: #1C1917;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.06);
z-index: 2;
}
.atelier-status-pill .atelier-dot {
width: 6px;
height: 6px;
border-radius: 999px;
background: #16A34A;
box-shadow: 0 0 0 2px rgba(22, 163, 74, 0.18);
}
.atelier-status-pill.is-empty .atelier-dot {
background: #D6D3D1;
box-shadow: 0 0 0 2px rgba(214, 211, 209, 0.2);
}
.atelier-status-pill.is-empty {
color: #A8A29E;
}
/* Modal enter animation */
@keyframes atelier-enter {
from { opacity: 0; transform: translateY(20px) scale(0.96); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
@keyframes atelier-backdrop {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes atelier-stagger {
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: translateY(0); }
}
.atelier-enter {
animation: atelier-enter 420ms cubic-bezier(0.22, 1, 0.36, 1) both;
}
.atelier-backdrop {
animation: atelier-backdrop 300ms ease both;
}
.atelier-stagger > * {
animation: atelier-stagger 480ms cubic-bezier(0.22, 1, 0.36, 1) both;
}
.atelier-stagger > *:nth-child(1) { animation-delay: 80ms; }
.atelier-stagger > *:nth-child(2) { animation-delay: 140ms; }
.atelier-stagger > *:nth-child(3) { animation-delay: 200ms; }
.atelier-stagger > *:nth-child(4) { animation-delay: 260ms; }
.atelier-stagger > *:nth-child(5) { animation-delay: 320ms; }
.atelier-stagger > *:nth-child(6) { animation-delay: 380ms; }
.atelier-stagger > *:nth-child(7) { animation-delay: 440ms; }
/* Primary CTA — gradient with subtle inner highlight */
.atelier-cta {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 10px;
padding: 12px 22px;
font-family: var(--font-manrope);
font-size: 14px;
font-weight: 600;
letter-spacing: -0.005em;
color: #FFFFFF;
background: linear-gradient(135deg, #14532D 0%, #1F6B3E 50%, #14532D 100%);
background-size: 200% 100%;
background-position: 0% 50%;
border: 0;
border-radius: 10px;
cursor: pointer;
box-shadow:
0 6px 18px -6px rgba(20, 83, 45, 0.55),
inset 0 1px 0 rgba(255, 255, 255, 0.14),
inset 0 -1px 0 rgba(0, 0, 0, 0.10);
transition: all 220ms cubic-bezier(0.4, 0, 0.2, 1);
overflow: hidden;
}
.atelier-cta:hover {
background-position: 100% 50%;
box-shadow:
0 10px 28px -8px rgba(20, 83, 45, 0.65),
inset 0 1px 0 rgba(255, 255, 255, 0.20),
inset 0 -1px 0 rgba(0, 0, 0, 0.10);
transform: translateY(-1px);
}
.atelier-cta:active {
transform: translateY(0) scale(0.985);
}
.atelier-cta:disabled {
opacity: 0.5;
cursor: not-allowed;
transform: none;
background: #57534E;
box-shadow: none;
}
.atelier-cta .atelier-cta-shimmer {
position: absolute;
top: 0;
left: -100%;
width: 60%;
height: 100%;
background: linear-gradient(105deg, transparent 30%, rgba(255, 255, 255, 0.18) 50%, transparent 70%);
pointer-events: none;
transition: left 700ms cubic-bezier(0.4, 0, 0.2, 1);
}
.atelier-cta:hover .atelier-cta-shimmer {
left: 130%;
}
/* Discard button */
.atelier-discard {
font-family: var(--font-fraunces);
font-style: italic;
font-size: 14px;
font-variation-settings: "opsz" 14, "SOFT" 100;
color: #786B53;
background: transparent;
border: 0;
padding: 8px 6px;
cursor: pointer;
transition: color 180ms ease;
}
.atelier-discard:hover {
color: #1C1917;
}
/* Brand selector */
.atelier-select {
font-family: var(--font-manrope);
font-size: 15px;
font-weight: 500;
color: #1C1917;
background: transparent;
border: 0;
border-bottom: 1.5px solid rgba(28, 25, 23, 0.12);
border-radius: 0;
padding: 10px 24px 10px 0;
width: 100%;
outline: none;
cursor: pointer;
appearance: none;
-webkit-appearance: none;
background-image: url("data:image/svg+xml,%3Csvg width='12' height='8' viewBox='0 0 12 8' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M1 1L6 6L11 1' stroke='%23786B53' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right center;
transition: border-color 220ms ease;
}
.atelier-select:hover { border-bottom-color: rgba(28, 25, 23, 0.28); }
.atelier-select:focus { border-bottom-color: #224E2F; border-bottom-width: 2px; padding-bottom: 9.5px; }
/* Hint / help text */
.atelier-hint {
font-family: var(--font-fraunces);
font-style: italic;
font-size: 12px;
font-variation-settings: "opsz" 14, "SOFT" 100;
color: #A8A29E;
line-height: 1.4;
margin-top: 6px;
}
/* Error banner */
.atelier-error {
display: flex;
align-items: flex-start;
gap: 10px;
padding: 12px 14px;
background: linear-gradient(135deg, rgba(185, 28, 28, 0.06) 0%, rgba(185, 28, 28, 0.03) 100%);
border: 1px solid rgba(185, 28, 28, 0.25);
border-radius: 10px;
font-family: var(--font-manrope);
font-size: 13px;
color: #991B1B;
}
.atelier-error svg { flex-shrink: 0; margin-top: 1px; }
+673
View File
@@ -0,0 +1,673 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import Image from "next/image";
import { createPortal } from "react-dom";
export type ProductFormModalProps = {
open: boolean;
mode: "add" | "edit";
onClose: () => void;
onSubmit: (values: ProductFormValues) => Promise<{ success: boolean; error?: string }>;
/** Defaults / initial values (edit mode passes the current product) */
initial?: Partial<ProductFormValues>;
/** List of selectable brands (only shown to platform admins) */
brands?: { id: string; name: string }[];
/** When true the brand picker is hidden and the admin's brand is used */
lockBrand?: boolean;
/** Hard-locked brand id (for brand_admin / store_employee) */
lockedBrandId?: string;
/** Pre-uploaded image URL (edit mode) */
initialImageUrl?: string | null;
/** Server action: upload a file and return the public URL */
onUploadImage: (file: File) => Promise<{ success: boolean; imageUrl?: string; error?: string }>;
};
export type ProductFormValues = {
name: string;
description: string;
price: string;
type: "pickup" | "wholesale" | "subscription";
brand_id: string;
active: boolean;
is_taxable: boolean;
image_url: string | null;
};
const TYPE_OPTIONS: Array<{
value: ProductFormValues["type"];
label: string;
italic: string;
icon: React.ReactNode;
}> = [
{
value: "pickup",
label: "Pickup",
italic: "Farm & stops",
icon: (
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.6} strokeLinecap="round" strokeLinejoin="round">
<path d="M3 9l1.5-4h15L21 9" />
<path d="M3 9v11a1 1 0 001 1h16a1 1 0 001-1V9" />
<path d="M3 9h18" />
<path d="M9 14h6" />
</svg>
),
},
{
value: "wholesale",
label: "Wholesale",
italic: "B2B portal",
icon: (
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.6} strokeLinecap="round" strokeLinejoin="round">
<path d="M3 7h18l-2 12H5L3 7z" />
<path d="M8 7V5a4 4 0 018 0v2" />
</svg>
),
},
{
value: "subscription",
label: "Subscription",
italic: "Recurring",
icon: (
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.6} strokeLinecap="round" strokeLinejoin="round">
<path d="M21 12a9 9 0 11-3-6.7" />
<path d="M21 4v5h-5" />
</svg>
),
},
];
export default function ProductFormModal({
open,
mode,
onClose,
onSubmit,
initial,
brands = [],
lockBrand = false,
lockedBrandId = "",
initialImageUrl = null,
onUploadImage,
}: ProductFormModalProps) {
// Form state
const [name, setName] = useState(initial?.name ?? "");
const [description, setDescription] = useState(initial?.description ?? "");
const [price, setPrice] = useState(initial?.price ?? "");
const [type, setType] = useState<ProductFormValues["type"]>(initial?.type ?? "pickup");
const [brandId, setBrandId] = useState(
initial?.brand_id ?? lockedBrandId ?? brands[0]?.id ?? ""
);
const [active, setActive] = useState(initial?.active ?? true);
const [isTaxable, setIsTaxable] = useState(initial?.is_taxable ?? true);
// Image state
const [imagePreview, setImagePreview] = useState<string | null>(initialImageUrl);
const [imageUrl, setImageUrl] = useState<string | null>(initialImageUrl);
const [uploading, setUploading] = useState(false);
const [uploadError, setUploadError] = useState<string | null>(null);
const [isDrag, setIsDrag] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
// Submit state
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
// Reset state when opening with new initial values
useEffect(() => {
if (!open) return;
setName(initial?.name ?? "");
setDescription(initial?.description ?? "");
setPrice(initial?.price ?? "");
setType((initial?.type as ProductFormValues["type"]) ?? "pickup");
setBrandId(initial?.brand_id ?? lockedBrandId ?? brands[0]?.id ?? "");
setActive(initial?.active ?? true);
setIsTaxable(initial?.is_taxable ?? true);
setImagePreview(initialImageUrl);
setImageUrl(initialImageUrl);
setUploading(false);
setUploadError(null);
setError(null);
setSaving(false);
setIsDrag(false);
}, [open, initial, initialImageUrl, lockedBrandId, brands]);
// Body scroll lock + escape key
useEffect(() => {
if (!open) return;
const original = document.body.style.overflow;
document.body.style.overflow = "hidden";
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", onKey);
return () => {
document.body.style.overflow = original;
window.removeEventListener("keydown", onKey);
};
}, [open, onClose]);
const handleFile = useCallback(
async (file: File) => {
const validTypes = ["image/png", "image/jpeg", "image/webp"];
if (!validTypes.includes(file.type)) {
setUploadError("PNG, JPEG, or WebP only.");
return;
}
if (file.size > 5 * 1024 * 1024) {
setUploadError("File must be under 5MB.");
return;
}
setUploadError(null);
setUploading(true);
// Local preview first
const localUrl = URL.createObjectURL(file);
setImagePreview(localUrl);
const result = await onUploadImage(file);
setUploading(false);
if (result.success && result.imageUrl) {
setImageUrl(result.imageUrl);
setImagePreview(result.imageUrl);
URL.revokeObjectURL(localUrl);
} else {
setUploadError(result.error ?? "Upload failed.");
setImagePreview(imageUrl); // revert
}
},
[onUploadImage, imageUrl]
);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
if (!name.trim()) {
setError("Product name is required.");
return;
}
if (!price || isNaN(parseFloat(price)) || parseFloat(price) < 0) {
setError("Valid price is required.");
return;
}
if (!lockBrand && !brandId) {
setError("Please select a brand.");
return;
}
setSaving(true);
const res = await onSubmit({
name: name.trim(),
description: description.trim(),
price,
type,
brand_id: lockBrand ? lockedBrandId : brandId,
active,
is_taxable: isTaxable,
image_url: imageUrl,
});
setSaving(false);
if (!res.success) {
setError(res.error ?? "Something went wrong.");
return;
}
onClose();
}
if (!mounted || !open) return null;
const showBrandPicker = !lockBrand;
const lockedBrandName = brands.find((b) => b.id === lockedBrandId)?.name ?? lockedBrandId;
return createPortal(
<div
className="fixed inset-0 z-[80] flex items-center justify-center p-3 sm:p-6 atelier-backdrop"
onClick={(e) => {
if (e.target === e.currentTarget) onClose();
}}
style={{
backgroundColor: "rgba(28, 25, 23, 0.55)",
backdropFilter: "blur(8px)",
WebkitBackdropFilter: "blur(8px)",
}}
>
<div
role="dialog"
aria-modal="true"
aria-label={mode === "add" ? "Add product" : "Edit product"}
className="atelier-enter atelier-canvas relative w-full max-w-5xl max-h-[calc(100vh-1.5rem)] sm:max-h-[calc(100vh-3rem)] rounded-2xl shadow-[0_30px_80px_-20px_rgba(28,25,23,0.45)] flex flex-col overflow-hidden border border-stone-200/60"
>
{/* grain overlay */}
<div className="atelier-grain" aria-hidden />
{/* HEADER */}
<div className="relative shrink-0 px-6 sm:px-10 pt-6 sm:pt-8 pb-5 sm:pb-6">
<div className="flex items-start justify-between gap-4">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2.5 mb-3">
<span className="atelier-section-num">
{mode === "add" ? "Nouveau" : "Mise à jour"} · MMXXVI
</span>
</div>
<h2 className="atelier-title text-3xl sm:text-4xl md:text-5xl">
{mode === "add" ? (
<>
Add a <span className="atelier-italic">product</span>
</>
) : (
<>
Edit <span className="atelier-italic">{initial?.name || "product"}</span>
</>
)}
</h2>
<p className="atelier-italic mt-2 text-sm sm:text-[15px] max-w-md leading-relaxed">
{mode === "add"
? "Compose a new entry for the harvest catalog — every detail, like a recipe."
: "Refine the details of this entry. The catalog is a living record."}
</p>
</div>
<button
type="button"
onClick={onClose}
className="shrink-0 flex h-9 w-9 items-center justify-center rounded-full transition-all duration-200 hover:bg-stone-900 hover:text-white text-stone-500"
aria-label="Close"
>
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
</div>
<div className="relative shrink-0 px-6 sm:px-10">
<hr className="atelier-rule" />
</div>
{/* BODY — two columns */}
<form
onSubmit={handleSubmit}
className="relative flex-1 overflow-y-auto"
onDragEnter={(e) => {
e.preventDefault();
setIsDrag(true);
}}
>
<div className="grid grid-cols-1 lg:grid-cols-[minmax(0,5fr)_minmax(0,7fr)] gap-0">
{/* LEFT — Image hero */}
<div className="relative px-6 sm:px-10 pt-6 sm:pt-8 pb-6 lg:border-r border-stone-200/60 lg:pr-8">
<div className="atelier-section-num mb-4">01 · Media</div>
<div
onDragOver={(e) => {
e.preventDefault();
setIsDrag(true);
}}
onDragLeave={(e) => {
if (e.currentTarget === e.target) setIsDrag(false);
}}
onDrop={(e) => {
e.preventDefault();
setIsDrag(false);
const file = e.dataTransfer.files?.[0];
if (file) handleFile(file);
}}
onClick={() => !uploading && fileInputRef.current?.click()}
className={[
"atelier-drop",
isDrag ? "is-drag" : "",
uploadError ? "is-error" : "",
imagePreview ? "has-image" : "",
].join(" ")}
>
{/* status pill */}
<div
className={[
"atelier-status-pill",
imagePreview ? "" : "is-empty",
].join(" ")}
>
<span className="atelier-dot" />
{imagePreview
? uploading
? "Uploading"
: "Image set"
: "No image yet"}
</div>
{uploading ? (
<div className="flex flex-col items-center gap-3">
<div className="h-6 w-6 rounded-full border-2 border-stone-300 border-t-[#224E2F] animate-spin" />
<p className="atelier-drop-title">Pouring into the cellar</p>
</div>
) : imagePreview ? (
<div className="absolute inset-0 p-3 sm:p-4">
<div className="relative h-full w-full">
<Image
src={imagePreview}
alt="Product preview"
fill
style={{ objectFit: "contain" }}
className="rounded-md"
/>
</div>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
setImagePreview(null);
setImageUrl(null);
}}
className="absolute bottom-4 left-1/2 -translate-x-1/2 inline-flex items-center gap-1.5 rounded-full bg-stone-900/85 backdrop-blur-sm px-3 py-1.5 text-[11px] font-mono uppercase tracking-wider text-white hover:bg-stone-900 transition-colors"
>
<svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
Remove
</button>
</div>
) : (
<>
{/* ornamental drop zone content */}
<svg
className="h-10 w-10 text-[#224E2F]/70"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={1.2}
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M12 3v13" />
<path d="M7 8l5-5 5 5" />
<path d="M4 16v3a2 2 0 002 2h12a2 2 0 002-2v-3" />
<circle cx="12" cy="20" r="0.8" fill="currentColor" />
</svg>
<p className="atelier-drop-eyebrow">Drag &amp; drop</p>
<p className="atelier-drop-title">
or click to choose<br />a harvest portrait
</p>
<p className="atelier-drop-hint">PNG · JPEG · WebP · 5MB max</p>
</>
)}
<input
ref={fileInputRef}
type="file"
accept="image/png,image/jpeg,image/webp"
className="hidden"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) handleFile(file);
e.target.value = "";
}}
/>
</div>
{uploadError && (
<p className="mt-3 atelier-hint" style={{ color: "#B91C1C" }}>
{uploadError}
</p>
)}
</div>
{/* RIGHT — Form fields */}
<div className="px-6 sm:px-10 pt-6 sm:pt-8 pb-6 lg:pl-10 space-y-7 atelier-stagger">
{error && (
<div className="atelier-error">
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span>{error}</span>
</div>
)}
{/* 02 IDENTITY */}
<section>
<div className="flex items-baseline justify-between mb-4">
<div className="atelier-section-num">02 · Identity</div>
</div>
<div>
<label
htmlFor="atelier-name"
className="atelier-section-label block mb-1"
>
Product name
</label>
<input
id="atelier-name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="e.g. Dozen Sweet Corn"
className="atelier-input atelier-input--display"
autoComplete="off"
/>
</div>
<div className="mt-5">
<label
htmlFor="atelier-desc"
className="atelier-section-label block mb-1"
>
Description
</label>
<textarea
id="atelier-desc"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="A note from the field — origin, variety, picking notes…"
rows={2}
className="atelier-input resize-none"
style={{ minHeight: 56 }}
/>
</div>
</section>
{/* 03 COMMERCE */}
<section>
<div className="atelier-section-num mb-4">03 · Commerce</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<div>
<label
htmlFor="atelier-price"
className="atelier-section-label block mb-1"
>
Price
</label>
<div className="relative">
<span className="atelier-price-sigil">$</span>
<input
id="atelier-price"
type="number"
step="0.01"
min="0"
value={price}
onChange={(e) => setPrice(e.target.value)}
placeholder="0.00"
className="atelier-price"
/>
</div>
</div>
{showBrandPicker ? (
<div>
<label
htmlFor="atelier-brand"
className="atelier-section-label block mb-1"
>
Brand
</label>
<select
id="atelier-brand"
value={brandId}
onChange={(e) => setBrandId(e.target.value)}
className="atelier-select"
>
{brands.length === 0 && <option value="">Loading brands</option>}
{brands.length > 0 && <option value="">Select a brand</option>}
{brands.map((b) => (
<option key={b.id} value={b.id}>
{b.name}
</option>
))}
</select>
<p className="atelier-hint">
You administer multiple brands choose the one this product belongs to.
</p>
</div>
) : (
<div>
<span className="atelier-section-label block mb-1">Brand</span>
<div className="py-2.5 border-b border-stone-300/40">
<span className="font-[family-name:var(--font-fraunces)] text-[15px] text-stone-700">
{lockedBrandName || "—"}
</span>
</div>
</div>
)}
</div>
<div className="mt-6">
<span className="atelier-section-label block mb-2">Type</span>
<div className="grid grid-cols-3 gap-2.5">
{TYPE_OPTIONS.map((opt) => (
<button
key={opt.value}
type="button"
onClick={() => setType(opt.value)}
className={[
"atelier-type-card",
type === opt.value ? "is-selected" : "",
].join(" ")}
aria-pressed={type === opt.value}
>
<div className="flex items-center justify-between w-full">
<span className="atelier-type-icon">{opt.icon}</span>
<svg
className="atelier-type-check h-3.5 w-3.5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={3}
>
<path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
</svg>
</div>
<div>
<div className="atelier-type-name">{opt.label}</div>
<div
className={[
"text-[10px] font-[family-name:var(--font-fragment-mono)] uppercase tracking-wider mt-0.5",
type === opt.value ? "text-white/60" : "text-stone-500",
].join(" ")}
>
{opt.italic}
</div>
</div>
</button>
))}
</div>
</div>
</section>
{/* 04 SETTINGS */}
<section>
<div className="atelier-section-num mb-4">04 · Settings</div>
<div className="flex flex-wrap items-center gap-6 sm:gap-10">
<button
type="button"
onClick={() => setActive((v) => !v)}
className={["atelier-toggle", active ? "is-on" : ""].join(" ")}
aria-pressed={active}
>
<span className="atelier-toggle-track">
<span className="atelier-toggle-thumb" />
</span>
<span className="atelier-toggle-label">Active</span>
</button>
<button
type="button"
onClick={() => setIsTaxable((v) => !v)}
className={["atelier-toggle is-gold", isTaxable ? "is-on" : ""].join(" ")}
aria-pressed={isTaxable}
>
<span className="atelier-toggle-track">
<span className="atelier-toggle-thumb" />
</span>
<span className="atelier-toggle-label">Taxable</span>
</button>
<p className="atelier-hint flex-1 min-w-[200px]">
Active products appear in the storefront. Taxable items add sales tax at checkout.
</p>
</div>
</section>
</div>
</div>
</form>
{/* FOOTER */}
<div className="relative shrink-0 px-6 sm:px-10 pt-4 pb-6 sm:pb-7 border-t border-stone-200/60 bg-[#FAF7F0]/80 backdrop-blur-sm">
<div className="flex items-center justify-between gap-4">
<button
type="button"
onClick={onClose}
className="atelier-discard"
>
discard changes
</button>
<div className="flex items-center gap-3">
{/* readiness indicator */}
<div className="hidden sm:flex items-center gap-2 text-[11px] font-mono uppercase tracking-wider text-stone-500">
<span
className={[
"h-1.5 w-1.5 rounded-full",
name.trim() && price
? "bg-emerald-600 shadow-[0_0_0_3px_rgba(22,163,74,0.15)]"
: "bg-stone-300",
].join(" ")}
/>
{name.trim() && price ? "Ready" : "Required fields pending"}
</div>
<button
type="submit"
form="atelier-product-form"
onClick={handleSubmit}
disabled={saving || uploading || !name.trim() || !price}
className="atelier-cta"
>
<span className="atelier-cta-shimmer" />
{saving ? (
<>
<span className="h-3.5 w-3.5 rounded-full border-2 border-white/40 border-t-white animate-spin" />
{mode === "add" ? "Composing…" : "Saving…"}
</>
) : (
<>
{mode === "add" ? "Add to catalog" : "Save changes"}
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M14 5l7 7m0 0l-7 7m7-7H3" />
</svg>
</>
)}
</button>
</div>
</div>
</div>
</div>
</div>,
document.body
);
}
+205 -392
View File
@@ -1,13 +1,14 @@
"use client";
import { useState, useCallback, useRef, useTransition } from "react";
import { useState, useCallback, useTransition, useEffect, useRef } from "react";
import { createPortal } from "react-dom";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { createProduct } from "@/actions/products/create-product";
import { updateProduct } from "@/actions/products/update-product";
import { deleteProduct } from "@/actions/products";
import { uploadProductImage } from "@/actions/products/upload-image";
import GlassModal from "@/components/admin/GlassModal";
import ProductFormModal, { type ProductFormValues } from "@/components/admin/ProductFormModal";
import { PageHeader, AdminButton, AdminIconButton, AdminSearchInput, AdminFilterTabs, AdminViewModeTabs, useToast, Skeleton } from "@/components/admin/design-system";
type Product = {
@@ -22,16 +23,6 @@ type Product = {
is_taxable: boolean;
};
type FormData = {
name: string;
description: string;
price: string;
type: string;
active: boolean;
image_url: string;
is_taxable: boolean;
};
type ViewMode = "table" | "cards";
// Icons
@@ -74,7 +65,17 @@ const PackageIconHeader = () => (
</svg>
);
export default function ProductsClient({ products, brandId }: { products: Product[]; brandId?: string }) {
export default function ProductsClient({
products,
brandId,
brands = [],
isPlatformAdmin = false,
}: {
products: Product[];
brandId?: string;
brands?: { id: string; name: string }[];
isPlatformAdmin?: boolean;
}) {
const router = useRouter();
const { success: showSuccess, error: showError } = useToast();
const [, startTransition] = useTransition();
@@ -83,28 +84,10 @@ export default function ProductsClient({ products, brandId }: { products: Produc
const [viewMode, setViewMode] = useState<ViewMode>("table");
const [showModal, setShowModal] = useState(false);
const [editingProduct, setEditingProduct] = useState<Product | null>(null);
const [formData, setFormData] = useState<FormData>({
name: "",
description: "",
price: "",
type: "pickup",
active: true,
image_url: "",
is_taxable: true,
});
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);
const [deletingId, setDeletingId] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
// Image upload states
const [imagePreview, setImagePreview] = useState<string | null>(null);
const [uploading, setUploading] = useState(false);
const [uploadError, setUploadError] = useState<string | null>(null);
const [pendingImageUrl, setPendingImageUrl] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const filtered = products.filter((p) => {
const matchesSearch =
!search ||
@@ -147,165 +130,104 @@ export default function ProductsClient({ products, brandId }: { products: Produc
});
}
async function handleFileSelect(file: File) {
const validTypes = ["image/png", "image/jpeg", "image/webp"];
if (!validTypes.includes(file.type)) {
setUploadError("Only PNG, JPEG, and WebP images are allowed.");
return;
}
if (file.size > 5 * 1024 * 1024) {
setUploadError("Image must be under 5MB.");
return;
}
const handleUploadImage = useCallback(
async (file: File): Promise<{ success: boolean; imageUrl?: string; error?: string }> => {
const validTypes = ["image/png", "image/jpeg", "image/webp"];
if (!validTypes.includes(file.type)) {
return { success: false, error: "Only PNG, JPEG, and WebP images are allowed." };
}
if (file.size > 5 * 1024 * 1024) {
return { success: false, error: "Image must be under 5MB." };
}
setUploadError(null);
setUploading(true);
const resizedBuffer = await resizeImage(file, 1200);
const resizedFile = new File([resizedBuffer], file.name, { type: "image/jpeg" });
const resizedBuffer = await resizeImage(file, 1200);
const resizedFile = new File([resizedBuffer], file.name, { type: "image/jpeg" });
const productIdForUpload = editingProduct ? editingProduct.id : "__NEW__";
const result = await uploadProductImage(productIdForUpload, resizedFile);
setUploading(false);
if (result.success) {
setPendingImageUrl(result.imageUrl);
setImagePreview(result.imageUrl);
setFormData({ ...formData, image_url: result.imageUrl });
} else {
setUploadError(result.error ?? "Upload failed.");
}
}
const productIdForUpload = editingProduct ? editingProduct.id : "__NEW__";
const result = await uploadProductImage(productIdForUpload, resizedFile);
if (result.success) {
return { success: true, imageUrl: result.imageUrl };
}
return { success: false, error: result.error };
},
[editingProduct]
);
const openAddModal = useCallback(() => {
setEditingProduct(null);
setFormData({
name: "",
description: "",
price: "",
type: "pickup",
active: true,
image_url: "",
is_taxable: true,
});
setImagePreview(null);
setPendingImageUrl(null);
setUploadError(null);
setError(null);
setShowModal(true);
}, []);
const openEditModal = useCallback((product: Product) => {
setEditingProduct(product);
setFormData({
name: product.name,
description: product.description || "",
price: String(product.price),
type: product.type,
active: product.active,
image_url: product.image_url || "",
is_taxable: product.is_taxable,
});
setImagePreview(product.image_url || null);
setPendingImageUrl(null);
setUploadError(null);
setError(null);
setShowModal(true);
}, []);
const closeModal = useCallback(() => {
setShowModal(false);
setEditingProduct(null);
setImagePreview(null);
setPendingImageUrl(null);
setUploadError(null);
setError(null);
}, []);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setSaving(true);
setIsLoading(true);
const price = parseFloat(formData.price);
if (isNaN(price) || price < 0) {
setError("Please enter a valid price");
setSaving(false);
setIsLoading(false);
return;
}
if (!formData.name.trim()) {
setError("Product name is required");
setSaving(false);
setIsLoading(false);
return;
}
try {
const imageUrl = pendingImageUrl || formData.image_url || null;
let result;
if (editingProduct) {
// Edits: scope to the product's own brand. The page-level brandId
// prop can be undefined for platform_admins viewing all brands, but
// the product record always carries its own brand_id.
const productBrandId = editingProduct.brand_id;
if (!productBrandId) {
setError("This product is missing a brand assignment");
setSaving(false);
setIsLoading(false);
return;
const handleModalSubmit = useCallback(
async (values: ProductFormValues): Promise<{ success: boolean; error?: string }> => {
setIsLoading(true);
try {
const price = parseFloat(values.price);
if (isNaN(price) || price < 0) {
return { success: false, error: "Please enter a valid price" };
}
result = await updateProduct(editingProduct.id, productBrandId, {
name: formData.name.trim(),
description: formData.description.trim(),
price,
type: formData.type,
active: formData.active,
image_url: imageUrl,
is_taxable: formData.is_taxable,
});
} else {
// Creates: require the page-level brandId prop (no product to pull from).
if (!brandId) {
setError("Brand ID is required");
setSaving(false);
setIsLoading(false);
return;
if (!values.name.trim()) {
return { success: false, error: "Product name is required" };
}
result = await createProduct(brandId, {
name: formData.name.trim(),
description: formData.description.trim(),
price,
type: formData.type,
active: formData.active,
image_url: imageUrl,
is_taxable: formData.is_taxable,
});
}
if (!result.success) {
setError(result.error ?? "Failed to save product");
showError("Failed to save product", result.error ?? "Please try again");
setSaving(false);
// Platform admins pick a brand in the modal; everyone else is locked.
const effectiveBrandId = isPlatformAdmin ? values.brand_id : brandId;
if (!effectiveBrandId) {
return { success: false, error: "Please choose a brand for this product." };
}
let result;
if (editingProduct) {
result = await updateProduct(editingProduct.id, effectiveBrandId, {
name: values.name.trim(),
description: values.description.trim(),
price,
type: values.type,
active: values.active,
image_url: values.image_url,
is_taxable: values.is_taxable,
});
} else {
result = await createProduct(effectiveBrandId, {
name: values.name.trim(),
description: values.description.trim(),
price,
type: values.type,
active: values.active,
image_url: values.image_url,
is_taxable: values.is_taxable,
});
}
if (!result.success) {
showError("Failed to save product", result.error ?? "Please try again");
return { success: false, error: result.error };
}
showSuccess(
editingProduct ? "Product updated" : "Product created",
`${values.name} has been saved`
);
startTransition(() => router.refresh());
return { success: true };
} catch {
return { success: false, error: "Network error. Please try again." };
} finally {
setIsLoading(false);
return;
}
showSuccess(editingProduct ? "Product updated" : "Product created", `${formData.name} has been saved`);
closeModal();
setIsLoading(false);
startTransition(() => router.refresh());
} catch {
setError("Network error. Please try again.");
showError("Network error", "Please check your connection and try again");
setSaving(false);
setIsLoading(false);
}
};
},
[editingProduct, brandId, isPlatformAdmin, router, showError, showSuccess]
);
const handleDelete = async (productId: string) => {
setDeletingId(productId);
@@ -409,203 +331,36 @@ export default function ProductsClient({ products, brandId }: { products: Produc
/>
)}
{/* Modal */}
{showModal && (
<GlassModal
title={editingProduct ? "Edit Product" : "Add Product"}
subtitle={editingProduct ? `Editing ${editingProduct.name}` : "Create a new product"}
onClose={closeModal}
>
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<div className="rounded-xl bg-red-50 border border-red-200 px-4 py-3 text-sm text-red-600 flex items-start gap-3">
<svg className="h-5 w-5 shrink-0 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
{error}
</div>
)}
<div>
<label className="block text-xs font-semibold text-stone-700 mb-1.5">
Name <span className="text-red-500">*</span>
</label>
<input
type="text"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
placeholder="Product name"
className={`w-full rounded-xl border px-3 py-2.5 text-sm text-[var(--admin-text-primary)] outline-none focus:ring-2 focus:ring-[var(--admin-accent)]/20 placeholder:text-[var(--admin-text-muted)] transition-colors ${
error && !formData.name.trim()
? "border-red-400 bg-red-50"
: "border-[var(--admin-border)] bg-white focus:border-[var(--admin-accent)]"
}`}
required
/>
</div>
<div>
<label className="block text-xs font-semibold text-stone-700 mb-1.5">Description</label>
<textarea
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
placeholder="Product description"
rows={2}
className="w-full rounded-xl border border-[var(--admin-border)] bg-white px-3 py-2.5 text-sm text-[var(--admin-text-primary)] outline-none focus:border-[var(--admin-accent)] focus:ring-2 focus:ring-[var(--admin-accent)]/20 placeholder:text-[var(--admin-text-muted)] resize-none"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-xs font-semibold text-stone-700 mb-1.5">
Price <span className="text-red-500">*</span>
</label>
<div className="relative">
<span className="absolute left-3 top-1/2 -translate-y-1/2 text-stone-400 text-sm">$</span>
<input
type="number"
step="0.01"
min="0"
value={formData.price}
onChange={(e) => setFormData({ ...formData, price: e.target.value })}
placeholder="0.00"
className={`w-full rounded-xl border pl-8 pr-3 py-2.5 text-sm text-[var(--admin-text-primary)] outline-none focus:ring-2 focus:ring-[var(--admin-accent)]/20 ${
error && (!formData.price || parseFloat(formData.price) < 0)
? "border-red-400 bg-red-50"
: "border-[var(--admin-border)] bg-white focus:border-[var(--admin-accent)]"
}`}
required
/>
</div>
</div>
<div>
<label className="block text-xs font-semibold text-stone-700 mb-1.5">Type</label>
<select
value={formData.type}
onChange={(e) => setFormData({ ...formData, type: e.target.value })}
className="w-full rounded-xl border border-[var(--admin-border)] bg-white px-3 py-2.5 text-sm text-[var(--admin-text-primary)] outline-none focus:border-[var(--admin-accent)] focus:ring-2 focus:ring-[var(--admin-accent)]/20"
>
<option value="pickup">Pickup</option>
<option value="wholesale">Wholesale</option>
<option value="subscription">Subscription</option>
</select>
</div>
</div>
{/* Image Upload */}
<div>
<label className="block text-xs font-semibold text-stone-700 mb-1.5">Product Image</label>
<p className="text-[10px] text-stone-500 mb-2">JPG, PNG, WebP · 1200px max width · max 5MB</p>
<div
onDragOver={(e) => e.preventDefault()}
onDrop={(e) => {
e.preventDefault();
const file = e.dataTransfer.files[0];
if (file) handleFileSelect(file);
}}
onClick={() => !uploading && fileInputRef.current?.click()}
className={`
flex flex-col items-center justify-center gap-2 rounded-xl border-2 border-dashed p-6 cursor-pointer transition-colors
${uploadError ? "border-red-400" : "border-[var(--admin-border)] hover:border-[var(--admin-accent)] hover:bg-[var(--admin-accent)]/5"}
${uploading ? "opacity-50 pointer-events-none" : ""}
`}
>
{uploading ? (
<>
<div className="h-5 w-5 rounded-full border-2 border-[var(--admin-accent)] border-t-transparent animate-spin" />
<span className="text-sm text-stone-500">Uploading...</span>
</>
) : imagePreview ? (
<div className="relative">
<div className="relative h-32 sm:h-40 w-auto">
<Image src={imagePreview} alt="Product preview" fill style={{ objectFit: "contain" }} className="rounded-lg" />
</div>
<span className="block text-center text-xs text-stone-500 mt-2">Click or drop to replace</span>
</div>
) : (
<>
{Icons.upload("h-8 w-8 text-stone-400")}
<span className="text-sm text-stone-500">Drag & drop or click to upload</span>
</>
)}
<input
ref={fileInputRef}
type="file"
accept="image/png,image/jpeg,image/webp"
className="hidden"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) handleFileSelect(file);
e.target.value = "";
}}
/>
</div>
{uploadError && (
<p className="mt-1 text-xs text-red-500">{uploadError}</p>
)}
{(imagePreview || formData.image_url) && (
<button
type="button"
onClick={() => {
setImagePreview(null);
setPendingImageUrl(null);
setFormData({ ...formData, image_url: "" });
}}
className="mt-2 text-xs text-red-500 hover:underline"
>
Remove image
</button>
)}
</div>
<div className="flex items-center gap-6">
<label className="flex items-center gap-3 cursor-pointer">
<input
type="checkbox"
checked={formData.active}
onChange={(e) => setFormData({ ...formData, active: e.target.checked })}
className="h-4 w-4 rounded border-[var(--admin-border)] text-[var(--admin-accent)] focus:ring-2 focus:ring-[var(--admin-accent)]/30 focus:ring-offset-1 cursor-pointer"
/>
<span className="text-sm font-medium text-stone-700">Active</span>
</label>
<label className="flex items-center gap-3 cursor-pointer">
<input
type="checkbox"
checked={formData.is_taxable}
onChange={(e) => setFormData({ ...formData, is_taxable: e.target.checked })}
className="h-4 w-4 rounded border-[var(--admin-border)] text-[var(--admin-accent)] focus:ring-2 focus:ring-[var(--admin-accent)]/30 focus:ring-offset-1 cursor-pointer"
/>
<span className="text-sm font-medium text-stone-700">Taxable</span>
</label>
</div>
<div className="flex justify-end gap-3 pt-4 border-t border-stone-100">
<AdminButton
type="button"
variant="secondary"
onClick={closeModal}
>
Cancel
</AdminButton>
<AdminButton
type="submit"
variant="primary"
isLoading={saving}
disabled={!formData.name.trim() || !formData.price}
>
{editingProduct ? "Save Changes" : "Create Product"}
</AdminButton>
</div>
</form>
</GlassModal>
)}
{/* Modal — Atelier des Récoltes (editorial product form) */}
<ProductFormModal
open={showModal}
mode={editingProduct ? "edit" : "add"}
onClose={closeModal}
onSubmit={handleModalSubmit}
onUploadImage={handleUploadImage}
brands={brands}
lockBrand={!isPlatformAdmin}
lockedBrandId={brandId ?? ""}
initial={
editingProduct
? {
name: editingProduct.name,
description: editingProduct.description || "",
price: String(editingProduct.price),
type: (editingProduct.type as "pickup" | "wholesale" | "subscription") ?? "pickup",
brand_id: editingProduct.brand_id,
active: editingProduct.active,
is_taxable: editingProduct.is_taxable,
}
: undefined
}
initialImageUrl={editingProduct?.image_url ?? null}
/>
</div>
);
}
// ── Table View ─────────────────────────────────────────────────────────────────
function TableView({
@@ -625,8 +380,51 @@ function TableView({
onDeleteCancel: () => void;
deletingId: string | null;
}) {
// Track the position of the open row's three-dots button so the popup can be
// rendered via portal at body level (escapes any overflow:hidden ancestors
// and any table-row stacking-context quirks).
const [menuPos, setMenuPos] = useState<{ top: number; left: number; width: number } | null>(null);
const [mounted, setMounted] = useState(false);
const buttonRefs = useRef<Record<string, HTMLButtonElement | null>>({});
useEffect(() => {
setMounted(true);
}, []);
useEffect(() => {
if (!deleteConfirm) {
setMenuPos(null);
return;
}
const btn = buttonRefs.current[deleteConfirm];
if (btn) {
const rect = btn.getBoundingClientRect();
setMenuPos({ top: rect.bottom + 4, left: rect.right, width: rect.width });
}
}, [deleteConfirm]);
// Reposition on scroll/resize so the popup stays anchored to its button.
useEffect(() => {
if (!deleteConfirm) return;
const updatePos = () => {
const btn = buttonRefs.current[deleteConfirm];
if (btn) {
const rect = btn.getBoundingClientRect();
setMenuPos({ top: rect.bottom + 4, left: rect.right, width: rect.width });
}
};
window.addEventListener("scroll", updatePos, true);
window.addEventListener("resize", updatePos);
return () => {
window.removeEventListener("scroll", updatePos, true);
window.removeEventListener("resize", updatePos);
};
}, [deleteConfirm]);
const openProduct = deleteConfirm ? products.find((p) => p.id === deleteConfirm) : null;
return (
<div className="overflow-hidden rounded-xl border border-[var(--admin-border)] bg-white">
<div className="overflow-visible rounded-xl border border-[var(--admin-border)] bg-white">
<table className="w-full text-sm">
<thead className="bg-stone-50">
<tr>
@@ -710,44 +508,15 @@ function TableView({
Edit
</AdminButton>
<button
ref={(el) => { buttonRefs.current[product.id] = el; }}
onClick={() => onDelete(product.id)}
className="rounded-lg px-2 py-1.5 text-xs text-[var(--admin-text-muted)] hover:text-red-600 hover:bg-red-50 transition-colors"
aria-label="Product actions"
>
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M12 5v.01M12 12v.01M12 19v.01M12 6a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2z" />
</svg>
</button>
{deleteConfirm === product.id && (
<>
<div className="fixed inset-0 z-30" onClick={onDeleteCancel} />
<div className="absolute right-0 top-full mt-1 z-40 w-72 rounded-xl bg-white border border-[var(--admin-border)] shadow-xl p-4">
<p className="text-sm font-semibold text-stone-900">
Delete &quot;{product.name}&quot;?
</p>
<p className="mt-1 text-xs text-stone-500">
This will remove the product. If attached to orders, it will be hidden.
</p>
<div className="mt-3 flex gap-2">
<button
onClick={onDeleteCancel}
className="flex-1 rounded-lg border border-[var(--admin-border)] bg-white px-3 py-2 text-xs font-semibold text-stone-700 hover:bg-stone-50"
>
Cancel
</button>
<AdminButton
onClick={() => onDeleteConfirm(product.id)}
disabled={deletingId === product.id}
variant="danger"
size="sm"
className="flex-1"
>
{deletingId === product.id ? "..." : "Delete"}
</AdminButton>
</div>
</div>
</>
)}
</div>
</td>
</tr>
@@ -755,6 +524,50 @@ function TableView({
)}
</tbody>
</table>
{/* Delete confirmation popup — rendered via portal at body level with
position: fixed so it sits above all table rows and escapes the
overflow-visible container. */}
{mounted && deleteConfirm && openProduct && menuPos &&
createPortal(
<>
<div
className="fixed inset-0 z-[60]"
onClick={onDeleteCancel}
/>
<div
role="dialog"
aria-label="Confirm delete"
className="fixed z-[70] w-72 rounded-xl bg-white border border-[var(--admin-border)] shadow-xl p-4"
style={{ top: menuPos.top, left: menuPos.left, transform: "translateX(-100%)" }}
>
<p className="text-sm font-semibold text-stone-900">
Delete &quot;{openProduct.name}&quot;?
</p>
<p className="mt-1 text-xs text-stone-500">
This will remove the product. If attached to orders, it will be hidden.
</p>
<div className="mt-3 flex gap-2">
<button
onClick={onDeleteCancel}
className="flex-1 rounded-lg border border-[var(--admin-border)] bg-white px-3 py-2 text-xs font-semibold text-stone-700 hover:bg-stone-50"
>
Cancel
</button>
<AdminButton
onClick={() => onDeleteConfirm(openProduct.id)}
disabled={deletingId === openProduct.id}
variant="danger"
size="sm"
className="flex-1"
>
{deletingId === openProduct.id ? "..." : "Delete"}
</AdminButton>
</div>
</div>
</>,
document.body
)}
</div>
);
}