function CreateAdView() { const [title, setTitle] = useState(''); const [context, setContext] = useState(''); const [loading, setLoading] = useState(false); const [ctxLoading, setCtxLoading] = useState(false); const [captions, setCaptions] = useState([]); const [activeCaption, setActiveCaption] = useState(0); const [imageCount, setImageCount] = useState(1); const [slots, setSlots] = useState([{ id: 's1', prompt: '', url: null, gen: false }]); const [productImg, setProductImg] = useState(null); const [dragOver, setDragOver] = useState(false); const [contextErr, setContextErr] = useState(''); const [genErr, setGenErr] = useState(''); const fileRef = useRef(null); const handleProductFile = (file) => { if (!file || !file.type.startsWith('image/')) return; const url = URL.createObjectURL(file); setProductImg(url); // propagate into any existing slots setSlots(s => s.map(x => ({ ...x, url: url }))); }; const handleGenContext = async () => { if (!title.trim() || ctxLoading) return; setCtxLoading(true); try { const text = await aiGenContext(title); setContext(text); } catch(e) { if (e.code === 'NO_KEY') setContextErr('ตั้งค่า AI API Key ใน Settings เพื่อใช้ฟีเจอร์นี้'); else setContextErr('เกิดข้อผิดพลาด: ' + e.message); } setCtxLoading(false); }; const generate = async () => { if (!title.trim() || !context.trim() || loading) return; setLoading(true); try { const [caps, imgPrompt] = await Promise.all([ aiGenCaptions(title, context), aiGenImagePrompt(title, context), ]); setCaptions(Array.isArray(caps) ? caps : CAPTIONS); setActiveCaption(0); setSlots(buildSlots(imageCount, imgPrompt || IMAGE_PROMPT)); } catch(e) { setGenErr(e.code === 'NO_KEY' ? 'ตั้งค่า AI API Key ใน Settings เพื่อใช้ฟีเจอร์นี้' : 'เกิดข้อผิดพลาด: ' + e.message); } setLoading(false); }; const buildSlots = (n, prompt) => Array.from({ length: n }).map((_, i) => ({ id: `s${i}`, prompt: (slots[i] && slots[i].prompt) || prompt, url: productImg || (slots[i] && slots[i].url) || null, gen: false, })); const setCount = (n) => { setImageCount(n); setSlots(Array.from({ length: n }).map((_, i) => ({ id: `s${i}`, prompt: (slots[i] && slots[i].prompt) || (captions.length ? IMAGE_PROMPT : ''), url: productImg || (slots[i] && slots[i].url) || null, gen: false, }))); }; const genImage = (id) => { setSlots(s => s.map(x => x.id === id ? { ...x, gen: true } : x)); const result = productImg || 'https://images.unsplash.com/photo-1556228720-195a672e8a03?auto=format&fit=crop&w=800&q=80'; setTimeout(() => setSlots(s => s.map(x => x.id === id ? { ...x, gen: false, url: result } : x)), 1500); }; const copyText = (txt) => { navigator.clipboard && navigator.clipboard.writeText(txt); }; return (
รูปสินค้านี้จะถูกใช้เป็นอ้างอิงในทุก slot รูปภาพ และแสดงในพรีวิวโพสต์
{productImg ? 'รูปสินค้าพร้อมแล้ว! ' : ''} กรอกชื่อสินค้า แล้วกด ให้ AI เขียน