399 lines
15 KiB
TypeScript
399 lines
15 KiB
TypeScript
'use client';
|
|
|
|
import React, { useState, useEffect } from 'react';
|
|
import { supabase } from '@/lib/supabase';
|
|
import { NewsletterCampaign } from '@/types/newsletter';
|
|
import { DEFAULT_CAMPAIGN } from '@/lib/defaultCampaign';
|
|
import { NameDialog } from './NameDialog';
|
|
import {
|
|
FolderOpen,
|
|
Plus,
|
|
Copy,
|
|
Trash2,
|
|
X,
|
|
ExternalLink,
|
|
Clock,
|
|
CheckCircle2,
|
|
Layers,
|
|
Search,
|
|
Sparkles,
|
|
Pencil
|
|
} from 'lucide-react';
|
|
|
|
interface SavedCampaignsModalProps {
|
|
isOpen: boolean;
|
|
onClose: () => void;
|
|
currentCampaign: NewsletterCampaign;
|
|
onLoadCampaign: (campaign: NewsletterCampaign) => void;
|
|
onSaveCurrentAsCopy: (newTitle: string) => Promise<void>;
|
|
onRenameCurrent: (title: string) => void;
|
|
}
|
|
|
|
export const SavedCampaignsModal: React.FC<SavedCampaignsModalProps> = ({
|
|
isOpen,
|
|
onClose,
|
|
currentCampaign,
|
|
onLoadCampaign,
|
|
onSaveCurrentAsCopy,
|
|
onRenameCurrent
|
|
}) => {
|
|
const [campaigns, setCampaigns] = useState<any[]>([]);
|
|
const [loading, setLoading] = useState(false);
|
|
const [search, setSearch] = useState('');
|
|
const [isCreatingNew, setIsCreatingNew] = useState(false);
|
|
const [newTitle, setNewTitle] = useState('');
|
|
// okno na názov: premenovanie alebo duplikovanie vybraného newslettera
|
|
const [nameAction, setNameAction] = useState<{ kind: 'rename' | 'duplicate'; camp: { id: string; title: string; data?: unknown } } | null>(null);
|
|
|
|
const fetchCampaigns = async () => {
|
|
setLoading(true);
|
|
try {
|
|
const { data, error } = await supabase
|
|
.from('templates')
|
|
.select('*')
|
|
.order('updated_at', { ascending: false });
|
|
|
|
if (error) throw error;
|
|
setCampaigns(data || []);
|
|
} catch (err: any) {
|
|
console.error('Error fetching campaigns:', err);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
if (isOpen) {
|
|
fetchCampaigns();
|
|
setIsCreatingNew(false);
|
|
setNewTitle('');
|
|
}
|
|
}, [isOpen]);
|
|
|
|
if (!isOpen) return null;
|
|
|
|
const handleRename = async (camp: { id: string }, title: string) => {
|
|
try {
|
|
const { error } = await supabase.from('templates').update({ title }).eq('id', camp.id);
|
|
if (error) throw error;
|
|
setCampaigns((prev) => prev.map((c) => (c.id === camp.id ? { ...c, title } : c)));
|
|
if (camp.id === currentCampaign.id) onRenameCurrent(title);
|
|
setNameAction(null);
|
|
} catch (err) {
|
|
alert(`Chyba pri premenovaní: ${(err as Error).message}`);
|
|
}
|
|
};
|
|
|
|
const handleDuplicate = async (camp: any, clonedTitle: string) => {
|
|
try {
|
|
const { data, error } = await supabase
|
|
.from('templates')
|
|
.insert([
|
|
{
|
|
title: clonedTitle,
|
|
status: 'draft',
|
|
data: camp.data
|
|
}
|
|
])
|
|
.select();
|
|
|
|
if (error) throw error;
|
|
if (data && data[0]) {
|
|
await fetchCampaigns();
|
|
onLoadCampaign({
|
|
id: data[0].id,
|
|
title: data[0].title,
|
|
preheader: data[0].data?.preheader || '',
|
|
status: 'draft',
|
|
modules: data[0].data?.modules || []
|
|
});
|
|
setNameAction(null);
|
|
onClose();
|
|
}
|
|
} catch (err: any) {
|
|
alert(`Chyba pri duplikovaní: ${err.message}`);
|
|
}
|
|
};
|
|
|
|
const handleDelete = async (id: string, title: string) => {
|
|
if (!confirm(`Naozaj chcete vymazať newsletter "${title}"?`)) return;
|
|
|
|
try {
|
|
const { error } = await supabase.from('templates').delete().eq('id', id);
|
|
if (error) throw error;
|
|
setCampaigns((prev) => prev.filter((c) => c.id !== id));
|
|
if (currentCampaign.id === id) {
|
|
// Ak sme vymazali práve otvorený, resetneme ID
|
|
onLoadCampaign({ ...currentCampaign, id: '' });
|
|
}
|
|
} catch (err: any) {
|
|
alert(`Chyba pri mazaní: ${err.message}`);
|
|
}
|
|
};
|
|
|
|
const handleCreateNew = async () => {
|
|
const title = newTitle.trim() || `COOP Newsletter - ${new Date().toLocaleDateString('sk-SK')}`;
|
|
try {
|
|
const { data, error } = await supabase
|
|
.from('templates')
|
|
.insert([
|
|
{
|
|
title,
|
|
status: 'draft',
|
|
data: {
|
|
preheader: DEFAULT_CAMPAIGN.preheader,
|
|
modules: JSON.parse(JSON.stringify(DEFAULT_CAMPAIGN.modules))
|
|
}
|
|
}
|
|
])
|
|
.select();
|
|
|
|
if (error) throw error;
|
|
if (data && data[0]) {
|
|
onLoadCampaign({
|
|
id: data[0].id,
|
|
title: data[0].title,
|
|
preheader: data[0].data?.preheader || '',
|
|
status: 'draft',
|
|
modules: data[0].data?.modules || []
|
|
});
|
|
onClose();
|
|
}
|
|
} catch (err: any) {
|
|
alert(`Chyba pri vytváraní: ${err.message}`);
|
|
}
|
|
};
|
|
|
|
const handleSaveCurrentCopy = async () => {
|
|
const title = newTitle.trim() || `Kópia - ${currentCampaign.title}`;
|
|
await onSaveCurrentAsCopy(title);
|
|
await fetchCampaigns();
|
|
setIsCreatingNew(false);
|
|
setNewTitle('');
|
|
onClose();
|
|
};
|
|
|
|
const filtered = campaigns.filter((c) =>
|
|
(c.title || '').toLowerCase().includes(search.toLowerCase())
|
|
);
|
|
|
|
return (
|
|
<div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-4">
|
|
<div className="bg-white rounded-3xl shadow-2xl max-w-4xl w-full max-h-[85vh] flex flex-col overflow-hidden border border-gray-100">
|
|
{/* Horná lišta */}
|
|
<div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between bg-slate-50">
|
|
<div className="flex items-center gap-3">
|
|
<div className="w-10 h-10 rounded-2xl bg-red-100 flex items-center justify-center text-red-600">
|
|
<FolderOpen className="w-5 h-5" />
|
|
</div>
|
|
<div>
|
|
<h2 className="text-base font-bold text-gray-900">Moje Newslettre</h2>
|
|
<p className="text-xs text-gray-500">Spravujte, otvárajte a duplikujte uložené šablóny e-mailov</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-2">
|
|
<button
|
|
onClick={() => setIsCreatingNew((prev) => !prev)}
|
|
className="px-3.5 py-2 text-xs font-bold bg-[#e2001a] hover:bg-[#b80015] text-white rounded-xl flex items-center gap-1.5 shadow-sm transition-all"
|
|
>
|
|
<Plus className="w-4 h-4" />
|
|
<span>Nový newsletter</span>
|
|
</button>
|
|
<button
|
|
onClick={onClose}
|
|
className="w-9 h-9 rounded-xl hover:bg-gray-200 text-gray-400 hover:text-gray-700 flex items-center justify-center transition-colors"
|
|
>
|
|
<X className="w-5 h-5" />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Panel na vytvorenie / uloženie kópie */}
|
|
{isCreatingNew && (
|
|
<div className="p-4 bg-red-50/50 border-b border-red-100 flex flex-col sm:flex-row items-center gap-3">
|
|
<div className="flex-1 w-full">
|
|
<input
|
|
type="text"
|
|
value={newTitle}
|
|
onChange={(e) => setNewTitle(e.target.value)}
|
|
placeholder="Zadajte názov nového newslettera (napr. Kampaň Veľká Noc 2026)"
|
|
className="w-full text-xs border border-gray-300 rounded-xl p-2.5 bg-white font-medium focus:ring-2 focus:ring-red-500 focus:outline-none"
|
|
autoFocus
|
|
/>
|
|
</div>
|
|
<div className="flex items-center gap-2 w-full sm:w-auto">
|
|
<button
|
|
onClick={handleCreateNew}
|
|
className="flex-1 sm:flex-initial px-3.5 py-2 text-xs font-bold bg-slate-900 hover:bg-black text-white rounded-xl whitespace-nowrap"
|
|
>
|
|
Vytvoriť čistý z predlohy
|
|
</button>
|
|
<button
|
|
onClick={handleSaveCurrentCopy}
|
|
className="flex-1 sm:flex-initial px-3.5 py-2 text-xs font-bold bg-[#003399] hover:bg-blue-900 text-white rounded-xl whitespace-nowrap"
|
|
>
|
|
Uložiť aktuálny ako kópiu
|
|
</button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{/* Vyhľadávanie */}
|
|
<div className="p-4 border-b border-gray-100 bg-white">
|
|
<div className="relative">
|
|
<Search className="w-4 h-4 text-gray-400 absolute left-3 top-3" />
|
|
<input
|
|
type="text"
|
|
value={search}
|
|
onChange={(e) => setSearch(e.target.value)}
|
|
placeholder="Vyhľadávať medzi uloženými newslettrami..."
|
|
className="w-full pl-9 pr-4 py-2 text-xs border border-gray-200 rounded-xl bg-gray-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-red-500"
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Zoznam kampaní */}
|
|
<div className="flex-1 overflow-y-auto p-4 space-y-3 bg-slate-50/50">
|
|
{loading ? (
|
|
<div className="py-12 text-center text-sm text-gray-400">Načítavam uložené newslettre...</div>
|
|
) : filtered.length === 0 ? (
|
|
<div className="py-12 text-center text-gray-400 space-y-2">
|
|
<Sparkles className="w-8 h-8 text-gray-300 mx-auto" />
|
|
<p className="text-sm font-semibold text-gray-600">Nenašli sa žiadne uložené newslettre</p>
|
|
<p className="text-xs text-gray-400">Vytvorte nový kliknutím na tlačidlo vyššie.</p>
|
|
</div>
|
|
) : (
|
|
filtered.map((camp) => {
|
|
const isCurrent = camp.id === currentCampaign.id;
|
|
const moduleCount = camp.data?.modules?.length || 0;
|
|
const isExported = camp.status === 'exported' || !!camp.brevo_campaign_id;
|
|
const updatedDate = camp.updated_at
|
|
? new Date(camp.updated_at).toLocaleString('sk-SK', {
|
|
day: 'numeric',
|
|
month: 'numeric',
|
|
year: 'numeric',
|
|
hour: '2-digit',
|
|
minute: '2-digit'
|
|
})
|
|
: 'Neznámy dátum';
|
|
|
|
return (
|
|
<div
|
|
key={camp.id}
|
|
className={`p-4 rounded-2xl border transition-all flex flex-col sm:flex-row sm:items-center justify-between gap-3 ${
|
|
isCurrent
|
|
? 'bg-red-50/50 border-red-300 ring-2 ring-red-500/10'
|
|
: 'bg-white border-gray-200 hover:border-gray-300 hover:shadow-sm'
|
|
}`}
|
|
>
|
|
<div className="space-y-1">
|
|
<div className="flex items-center gap-2">
|
|
<span className="text-sm font-bold text-gray-900">{camp.title}</span>
|
|
{isCurrent && (
|
|
<span className="text-[10px] font-bold bg-red-600 text-white px-2 py-0.5 rounded-full uppercase tracking-wider">
|
|
Práve otvorený
|
|
</span>
|
|
)}
|
|
{isExported && (
|
|
<span className="text-[10px] font-bold bg-emerald-100 text-emerald-800 px-2 py-0.5 rounded-full flex items-center gap-1">
|
|
<CheckCircle2 className="w-3 h-3 text-emerald-600" /> Vytvorené v Brevo
|
|
</span>
|
|
)}
|
|
</div>
|
|
|
|
<div className="flex items-center gap-4 text-xs text-gray-500">
|
|
<span className="flex items-center gap-1">
|
|
<Clock className="w-3.5 h-3.5 text-gray-400" /> {updatedDate}
|
|
</span>
|
|
<span className="flex items-center gap-1">
|
|
<Layers className="w-3.5 h-3.5 text-gray-400" /> {moduleCount} modulov
|
|
</span>
|
|
{camp.brevo_campaign_id && (
|
|
<a
|
|
href="https://app.brevo.com/campaigns"
|
|
target="_blank"
|
|
rel="noopener noreferrer"
|
|
className="text-blue-600 hover:underline flex items-center gap-1 font-semibold"
|
|
onClick={(e) => e.stopPropagation()}
|
|
>
|
|
<span>Brevo #{camp.brevo_campaign_id}</span>
|
|
<ExternalLink className="w-3 h-3" />
|
|
</a>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
{/* Akčné tlačidlá */}
|
|
<div className="flex items-center gap-2 pt-2 sm:pt-0">
|
|
<button
|
|
onClick={() => {
|
|
onLoadCampaign({
|
|
id: camp.id,
|
|
title: camp.title,
|
|
preheader: camp.data?.preheader || '',
|
|
status: camp.status || 'draft',
|
|
brevoCampaignId: camp.brevo_campaign_id,
|
|
modules: camp.data?.modules || []
|
|
});
|
|
onClose();
|
|
}}
|
|
className="px-3 py-1.5 text-xs font-bold bg-slate-900 hover:bg-black text-white rounded-xl transition-colors"
|
|
>
|
|
{isCurrent ? 'Pokračovať v úprave' : 'Otvoriť'}
|
|
</button>
|
|
|
|
<button
|
|
onClick={() => setNameAction({ kind: 'duplicate', camp })}
|
|
className="px-3 py-1.5 text-xs font-bold bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl flex items-center gap-1 transition-colors"
|
|
title="Vytvoriť kópiu"
|
|
>
|
|
<Copy className="w-3.5 h-3.5" />
|
|
<span>Duplikovať</span>
|
|
</button>
|
|
|
|
<button
|
|
onClick={() => setNameAction({ kind: 'rename', camp })}
|
|
className="p-2 text-gray-400 hover:text-gray-900 hover:bg-gray-100 rounded-xl transition-colors"
|
|
title="Premenovať"
|
|
>
|
|
<Pencil className="w-4 h-4" />
|
|
</button>
|
|
|
|
<button
|
|
onClick={() => handleDelete(camp.id, camp.title)}
|
|
className="p-2 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-xl transition-colors"
|
|
title="Vymazať"
|
|
>
|
|
<Trash2 className="w-4 h-4" />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
);
|
|
})
|
|
)}
|
|
</div>
|
|
|
|
{/* Pätička */}
|
|
<div className="px-6 py-3.5 border-t border-gray-100 bg-white flex items-center justify-between text-xs text-gray-500">
|
|
<span>Celkovo uložených: {campaigns.length} newsletterov</span>
|
|
<button
|
|
onClick={onClose}
|
|
className="px-4 py-1.5 font-bold text-gray-600 hover:bg-gray-100 rounded-xl transition-colors"
|
|
>
|
|
Zatvoriť
|
|
</button>
|
|
</div>
|
|
</div>
|
|
<NameDialog
|
|
open={!!nameAction}
|
|
title={nameAction?.kind === 'rename' ? 'Premenovať newsletter' : 'Duplikovať newsletter'}
|
|
initial={nameAction?.camp.title || ''}
|
|
confirmText={nameAction?.kind === 'rename' ? 'Uložiť názov' : 'Vytvoriť kópiu'}
|
|
onConfirm={(title) => (nameAction?.kind === 'rename' ? handleRename(nameAction.camp, title) : handleDuplicate(nameAction!.camp, title))}
|
|
onCancel={() => setNameAction(null)}
|
|
/>
|
|
</div>
|
|
);
|
|
};
|