SkateSpots/src/pages/CreateShopPage.tsx
shakespeare.diy feddbaf5ef Add optional CLINK (noffer) self-custodial payments to Lab profiles + shops
Phase 1 CLINK integration (recognize & display only):
- types.ts: optional noffer field + isValidNoffer guard on SkateCoach,
  SkateFilmer, SkateEditor, SkatePhotographer, SkateShop; parsers read it
- NofferField: reusable opt-in input with live validation, added to all 4
  Become-* Lab forms and both Create/Edit shop forms
- ClinkPayButton: secondary "Pay via CLINK" action (QR + copy + nostr: deep
  link), rendered on CoachDetailPage and ShopDetailPage only when a valid
  noffer is present; never replaces the existing zap / Lightning Address flow
- useQRCodeScanner: classify scanned noffer1/ndebit1 CLINK codes
- NIP.md: document the noffer tag on Lab kinds + shops and a CLINK section

Co-authored-by: shakespeare.diy <assistant@shakespeare.diy>
2026-07-24 12:34:50 +07:00

518 lines
18 KiB
TypeScript

import { useState, useEffect } from 'react';
import { useSeoMeta } from '@unhead/react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import ngeohash from 'ngeohash';
import { Layout } from '@/components/Layout';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useUploadFile } from '@/hooks/useUploadFile';
import { useToast } from '@/hooks/useToast';
import { ShopBountyCard } from '@/components/ShopBountyCard';
import { LoginArea } from '@/components/auth/LoginArea';
import { SKATE_SHOP_KIND, isValidNoffer } from '@/lib/types';
import { NofferField } from '@/components/NofferField';
import {
Store,
Upload,
X,
Loader2,
ArrowLeft,
MapPin,
} from 'lucide-react';
import { Link } from 'react-router-dom';
export default function CreateShopPage() {
useSeoMeta({
title: 'Add a Skate Shop - SkateSpots',
description: 'Add your skate shop to the community.',
});
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const { user } = useCurrentUser();
const { mutateAsync: createEvent, isPending: isPublishing } = useNostrPublish();
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const { toast } = useToast();
// Form state
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [location, setLocation] = useState('');
const [latitude, setLatitude] = useState('');
const [longitude, setLongitude] = useState('');
const [phone, setPhone] = useState('');
const [email, setEmail] = useState('');
const [website, setWebsite] = useState('');
const [instagram, setInstagram] = useState('');
const [noffer, setNoffer] = useState('');
const [hours, setHours] = useState('');
const [images, setImages] = useState<string[]>([]);
const [isGettingLocation, setIsGettingLocation] = useState(false);
// Pre-fill coordinates from URL params (from map click)
useEffect(() => {
const lat = searchParams.get('lat');
const lng = searchParams.get('lng');
if (lat && lng) {
setLatitude(lat);
setLongitude(lng);
}
}, [searchParams]);
const getCurrentLocation = () => {
if (!navigator.geolocation) {
toast({
title: 'Geolocation not supported',
description: 'Your browser does not support geolocation.',
variant: 'destructive',
});
return;
}
setIsGettingLocation(true);
navigator.geolocation.getCurrentPosition(
(position) => {
setLatitude(position.coords.latitude.toFixed(6));
setLongitude(position.coords.longitude.toFixed(6));
setIsGettingLocation(false);
toast({
title: 'Location found',
description: 'Your current location has been set.',
});
},
(error) => {
setIsGettingLocation(false);
toast({
title: 'Location error',
description: error.message,
variant: 'destructive',
});
}
);
};
const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
if (!files || files.length === 0) return;
try {
const file = files[0];
const tags = await uploadFile(file);
const url = tags[0]?.[1];
if (url) {
setImages((prev) => [...prev, url]);
toast({
title: 'Image uploaded',
description: 'Your image has been uploaded successfully.',
});
}
} catch (error) {
toast({
title: 'Upload failed',
description: error instanceof Error ? error.message : 'Failed to upload image',
variant: 'destructive',
});
}
// Clear the input
e.target.value = '';
};
const removeImage = (url: string) => {
setImages((prev) => prev.filter((img) => img !== url));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!name.trim()) {
toast({
title: 'Shop name required',
description: 'Please enter a name for your shop.',
variant: 'destructive',
});
return;
}
if (!location.trim()) {
toast({
title: 'Address required',
description: 'Please enter your shop address.',
variant: 'destructive',
});
return;
}
if (!latitude || !longitude) {
toast({
title: 'Location required',
description: 'Please enter coordinates or use your current location.',
variant: 'destructive',
});
return;
}
const lat = parseFloat(latitude);
const lng = parseFloat(longitude);
if (isNaN(lat) || isNaN(lng) || lat < -90 || lat > 90 || lng < -180 || lng > 180) {
toast({
title: 'Invalid coordinates',
description: 'Please enter valid latitude (-90 to 90) and longitude (-180 to 180).',
variant: 'destructive',
});
return;
}
try {
// Generate geohash from coordinates (7 chars = ~153m precision)
const geohash = ngeohash.encode(lat, lng, 7);
// Create unique identifier for addressable event
const identifier = name
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 50) + '-' + Date.now().toString(36);
// Build tags according to NIP-15 and custom extensions
const tags: string[][] = [
['d', identifier], // Required for addressable events
['name', name.trim()],
['g', geohash],
['t', 'skateshop'], // Primary identifier for shop events
['lat', lat.toString()],
['lon', lng.toString()],
['location', location.trim()],
];
if (phone.trim()) {
tags.push(['phone', phone.trim()]);
}
if (email.trim()) {
tags.push(['email', email.trim()]);
}
if (website.trim()) {
tags.push(['website', website.trim()]);
}
if (instagram.trim()) {
tags.push(['instagram', instagram.trim()]);
}
if (hours.trim()) {
tags.push(['hours', hours.trim()]);
}
if (isValidNoffer(noffer.trim())) {
tags.push(['noffer', noffer.trim().toLowerCase()]);
}
for (const imageUrl of images) {
// Use imeta tag for NIP-92 compatibility
tags.push(['imeta', `url ${imageUrl}`, 'm image/jpeg']);
}
console.log('Publishing shop event:', {
kind: SKATE_SHOP_KIND,
tags,
content: description.trim()
});
await createEvent({
kind: SKATE_SHOP_KIND,
content: description.trim(),
tags,
});
toast({
title: '🎉 Shop added!',
description: 'Your skate shop is now on the map. Skaters can zap you to say thanks!',
});
// Navigate to shop detail using pubkey and identifier
navigate(`/shop/${user?.pubkey}/${identifier}`);
} catch (error) {
console.error('Failed to create shop:', error);
toast({
title: 'Failed to publish',
description: error instanceof Error ? error.message : 'Something went wrong. Check console for details.',
variant: 'destructive',
});
}
};
if (!user) {
return (
<Layout>
<div className="container px-4 py-8">
<Card className="max-w-xl mx-auto border-dashed">
<CardContent className="py-12 text-center">
<Store className="h-12 w-12 mx-auto mb-4 text-muted-foreground/50" />
<h2 className="text-xl font-bold mb-2">Login Required</h2>
<p className="text-muted-foreground mb-6">
You need to log in to add a skate shop.
</p>
<LoginArea className="justify-center" />
</CardContent>
</Card>
</div>
</Layout>
);
}
return (
<Layout>
<div className="container px-4 sm:px-6 py-6 sm:py-8 max-w-2xl">
<div className="mb-6">
<Link to="/map" className="inline-flex items-center text-gray-400 hover:text-white transition-colors mb-4">
<ArrowLeft className="h-4 w-4 mr-2" />
Back to Map
</Link>
<h1 className="text-3xl font-black uppercase neon-lime" style={{
fontFamily: 'Impact, "Arial Black", sans-serif'
}}>Add a Skate Shop</h1>
<p className="text-gray-400 mt-1">
List your shop on the map and connect with the community
</p>
</div>
<form onSubmit={handleSubmit}>
<Card className="bg-black/90 border-2 border-[#ccff00]/30">
<CardHeader>
<CardTitle className="text-[#ccff00] uppercase font-black">Shop Details</CardTitle>
<CardDescription className="text-gray-400">
Tell the community about your shop. All fields marked with * are required.
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{/* Shop Name */}
<div className="space-y-2">
<Label htmlFor="name">Shop Name *</Label>
<Input
id="name"
placeholder="e.g., Supreme Los Angeles"
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
</div>
{/* Description */}
<div className="space-y-2">
<Label htmlFor="description">Description</Label>
<Textarea
id="description"
placeholder="Tell people about your shop, what you sell, your specialty..."
value={description}
onChange={(e) => setDescription(e.target.value)}
rows={4}
/>
</div>
{/* Location Address */}
<div className="space-y-2">
<Label htmlFor="location">Shop Address *</Label>
<Input
id="location"
placeholder="e.g., 411 N Fairfax Ave, Los Angeles, CA 90036"
value={location}
onChange={(e) => setLocation(e.target.value)}
required
/>
</div>
{/* Coordinates */}
<div className="space-y-2">
<Label>Coordinates *</Label>
<div className="grid grid-cols-2 gap-4">
<div>
<Input
placeholder="Latitude (e.g., 34.0737)"
value={latitude}
onChange={(e) => setLatitude(e.target.value)}
required
/>
</div>
<div>
<Input
placeholder="Longitude (e.g., -118.3614)"
value={longitude}
onChange={(e) => setLongitude(e.target.value)}
required
/>
</div>
</div>
<Button
type="button"
variant="outline"
size="sm"
onClick={getCurrentLocation}
disabled={isGettingLocation}
className="mt-2"
>
{isGettingLocation ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Getting location...
</>
) : (
<>
<MapPin className="h-4 w-4 mr-2" />
Use my current location
</>
)}
</Button>
</div>
{/* Contact Information */}
<div className="space-y-3 p-4 rounded-lg border-2 border-[#ccff00]/30 bg-[#ccff00]/5">
<div className="flex items-center gap-2 mb-2">
<span className="text-2xl">📞</span>
<Label className="text-base font-bold text-[#ccff00]">Contact Information</Label>
</div>
<p className="text-sm text-gray-400 mb-3">
Help customers reach you (at least one contact method recommended)
</p>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="phone">Phone Number</Label>
<Input
id="phone"
type="tel"
placeholder="+1 234 567 8900"
value={phone}
onChange={(e) => setPhone(e.target.value)}
className="bg-black border-[#ccff00]/30"
/>
</div>
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
placeholder="shop@example.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="bg-black border-[#ccff00]/30"
/>
</div>
<div className="space-y-2">
<Label htmlFor="website">Website</Label>
<Input
id="website"
type="url"
placeholder="https://myshop.com"
value={website}
onChange={(e) => setWebsite(e.target.value)}
className="bg-black border-[#ccff00]/30"
/>
</div>
<div className="space-y-2">
<Label htmlFor="instagram">Instagram</Label>
<Input
id="instagram"
placeholder="@shopname"
value={instagram}
onChange={(e) => setInstagram(e.target.value)}
className="bg-black border-[#ccff00]/30"
/>
</div>
</div>
</div>
{/* Hours of Operation */}
<div className="space-y-2">
<Label htmlFor="hours">Hours of Operation</Label>
<Input
id="hours"
placeholder="e.g., Mon-Sat 10AM-8PM, Sun 12PM-6PM"
value={hours}
onChange={(e) => setHours(e.target.value)}
/>
</div>
{/* CLINK self-custodial payments (optional) */}
<NofferField value={noffer} onChange={setNoffer} />
{/* Images */}
<div className="space-y-2">
<Label>Shop Photos</Label>
<div className="grid grid-cols-3 gap-4">
{images.map((url) => (
<div key={url} className="relative aspect-video rounded-lg overflow-hidden bg-muted">
<img src={url} alt="Shop" className="w-full h-full object-cover" />
<button
type="button"
onClick={() => removeImage(url)}
className="absolute top-1 right-1 p-1 rounded-full bg-background/80 hover:bg-destructive hover:text-destructive-foreground transition-colors"
>
<X className="h-4 w-4" />
</button>
</div>
))}
<label className="aspect-video rounded-lg border-2 border-dashed flex flex-col items-center justify-center cursor-pointer hover:bg-muted/50 transition-colors">
<input
type="file"
accept="image/*"
className="hidden"
onChange={handleImageUpload}
disabled={isUploading}
/>
{isUploading ? (
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
) : (
<>
<Upload className="h-6 w-6 text-muted-foreground mb-1" />
<span className="text-xs text-muted-foreground">Upload</span>
</>
)}
</label>
</div>
</div>
{/* Quality Meter */}
<ShopBountyCard
hasName={!!name.trim()}
hasAddress={!!location.trim()}
hasCoordinates={!!latitude && !!longitude}
hasDescription={!!description.trim()}
hasPhone={!!phone.trim()}
hasWebsite={!!website.trim()}
hasHours={!!hours.trim()}
photoCount={images.length}
/>
{/* Submit */}
<Button
type="submit"
className="w-full bg-[#ccff00] text-black hover:bg-[#ccff00]/90 font-black uppercase"
disabled={isPublishing || isUploading}
>
{isPublishing ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Publishing...
</>
) : (
<>
<Store className="h-4 w-4 mr-2" />
Add Shop
</>
)}
</Button>
</CardContent>
</Card>
</form>
</div>
</Layout>
);
}