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 (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--section-gap)', maxWidth: 1120 }} className="fade-up">
      <ViewHeader title="สร้างคอนเทนต์ Ads" en="Create Ad Content" sub="อัปโหลดรูปสินค้า → AI เขียนเนื้อหา → สร้าง Caption & Prompt → พรีวิวโพสต์จริง" />

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)', gap: 'var(--gap)', alignItems: 'start' }} className="create-row">

        {/* ——— LEFT: Editor ——— */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--gap)' }}>

          {/* Step 1: Upload product */}
          <div className="card">
            <div className="card-head">
              <h3 className="card-title"><IconImage size={16} style={{ color: 'var(--accent)' }} /> อัปโหลดรูปสินค้า <span className="eyebrow" style={{ marginLeft: 4 }}>STEP 1 · PRODUCT IMAGE</span></h3>
              {productImg && <button onClick={() => { setProductImg(null); setSlots(s => s.map(x => ({ ...x, url: null }))); }} className="chip" style={{ cursor: 'pointer', fontSize: 11 }}>ลบรูป ×</button>}
            </div>
            <div style={{ padding: 'var(--pad-card)' }}>
              {productImg ? (
                <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
                  <img src={productImg} alt="product" style={{ width: 90, height: 90, objectFit: 'cover', borderRadius: 'var(--radius-sm)', border: '2px solid var(--accent)', flexShrink: 0 }} />
                  <div>
                    <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--pos)', display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}><IconCheckCircle size={16} /> อัปโหลดสำเร็จ</div>
                    <p style={{ margin: 0, fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.55 }}>รูปสินค้านี้จะถูกใช้เป็นอ้างอิงในทุก slot รูปภาพ และแสดงในพรีวิวโพสต์</p>
                    <label style={{ marginTop: 10, display: 'inline-flex', alignItems: 'center', gap: 6, cursor: 'pointer', fontSize: 12.5, fontWeight: 600, color: 'var(--accent-strong)' }}>
                      <IconUpload size={13} /> เปลี่ยนรูป
                      <input type="file" accept="image/*" style={{ display: 'none' }} onChange={(e) => e.target.files[0] && handleProductFile(e.target.files[0])} />
                    </label>
                  </div>
                </div>
              ) : (
                <label
                  style={{
                    display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                    gap: 12, padding: '28px 24px', borderRadius: 'var(--radius-sm)', cursor: 'pointer',
                    border: `2px dashed ${dragOver ? 'var(--accent)' : 'var(--border-2)'}`,
                    background: dragOver ? 'var(--accent-soft)' : 'var(--surface-2)',
                    transition: 'all .15s', textAlign: 'center',
                  }}
                  onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
                  onDragLeave={() => setDragOver(false)}
                  onDrop={(e) => { e.preventDefault(); setDragOver(false); e.dataTransfer.files[0] && handleProductFile(e.dataTransfer.files[0]); }}
                >
                  <div style={{ width: 44, height: 44, borderRadius: 'var(--radius-sm)', background: 'var(--accent-soft)', color: 'var(--accent-strong)', display: 'grid', placeItems: 'center' }}>
                    <IconUpload size={22} />
                  </div>
                  <div>
                    <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--ink)', marginBottom: 4 }}>ลากหรือคลิกเพื่ออัปโหลดรูปสินค้า</div>
                    <div className="eyebrow">PNG · JPG · WEBP — ใช้เป็น reference สำหรับ AI สร้างรูป</div>
                  </div>
                  <input type="file" accept="image/*" style={{ display: 'none' }} ref={fileRef} onChange={(e) => e.target.files[0] && handleProductFile(e.target.files[0])} />
                </label>
              )}
            </div>
          </div>

          {/* Step 2: Product info + AI context */}
          <div className="card">
            <div className="card-head"><h3 className="card-title">ข้อมูลสินค้า & โปรโมชั่น <span className="eyebrow" style={{ marginLeft: 4 }}>STEP 2</span></h3></div>
            <div style={{ padding: 'var(--pad-card)', display: 'flex', flexDirection: 'column', gap: 18 }}>
              <Labeled label="ชื่อสินค้า" en="TITLE">
                <input className="field" value={title} onChange={(e) => { setTitle(e.target.value); setContextErr(''); setGenErr(''); }} placeholder="เช่น: ครีมกันแดดเนื้อบางเบา SPF50+" />
              </Labeled>

              <div>
                <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 8, marginBottom: 8 }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                    <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>เนื้อหา & โปรโมชั่น</span>
                    <span className="eyebrow">CONTEXT</span>
                  </div>
                  <button className="btn" onClick={handleGenContext} disabled={ctxLoading || !title.trim()} style={{ padding: '6px 12px', fontSize: 12, background: 'var(--surface-3)', color: 'var(--ink)', border: '1px solid var(--border-2)', gap: 6, borderRadius: 'var(--radius-sm)' }}>
                    {ctxLoading ? <IconRefresh size={13} className="spin" style={{ color: 'var(--accent)' }} /> : <IconSpark size={13} style={{ color: 'var(--accent)' }} />}
                    {ctxLoading ? 'AI กำลังคิด…' : 'ให้ AI คิดให้'}
                  </button>
                </div>
                {contextErr && (
                  <div style={{ display:'flex', gap:8, alignItems:'flex-start', padding:'9px 12px', borderRadius:'var(--radius-sm)', background:'var(--neg-soft)', border:'1px solid var(--neg)', marginTop:4 }}>
                    <IconWarn size={14} style={{ color:'var(--neg)', flexShrink:0, marginTop:1 }} />
                    <span style={{ fontSize:12.5, color:'var(--neg)' }}>{contextErr} — <span style={{ textDecoration:'underline', cursor:'pointer' }} onClick={() => {/* navigate settings */}}>ตั้งค่า AI</span></span>
                  </div>
                )}
                <textarea className="field" style={{ height: 108, resize: 'none', lineHeight: 1.6 }} value={context}
                  onChange={(e) => setContext(e.target.value)}
                  placeholder="เช่น: สูตรใหม่ไม่อุดตันรูขุมขน โปรลด 30% ส่งฟรีทั่วประเทศ…  หรือกด 'ให้ AI คิดให้' →" />
              </div>

              <button className="btn btn-primary" style={{ justifyContent: 'center' }} onClick={generate} disabled={loading || !title.trim() || !context.trim()}>
                {loading ? <IconRefresh size={17} className="spin" /> : <IconSpark size={17} />}
                {loading ? 'AI กำลังประมวลผล…' : 'ให้ AI เขียน Caption & Prompt'}
              </button>
              {genErr && (
                <div style={{ display:'flex', gap:8, alignItems:'flex-start', padding:'10px 14px', borderRadius:'var(--radius-sm)', background:'var(--neg-soft)', border:'1px solid var(--neg)' }}>
                  <IconWarn size={15} style={{ color:'var(--neg)', flexShrink:0, marginTop:1 }} />
                  <span style={{ fontSize:13, color:'var(--neg)', lineHeight:1.55 }}>{genErr}</span>
                </div>
              )}
            </div>
          </div>

          {/* Step 3: Image count + slots */}
          {captions.length > 0 && (
            <div className="card fade-up">
              <div className="card-head">
                <h3 className="card-title"><IconSliders size={16} style={{ color: 'var(--accent)' }} /> จำนวนและ Prompt รูปภาพ <span className="eyebrow" style={{ marginLeft: 4 }}>STEP 3 · AI IMAGE ASSETS</span></h3>
              </div>
              <div style={{ padding: 'var(--pad-card)', display: 'flex', flexDirection: 'column', gap: 20 }}>

                {/* Count picker */}
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', marginBottom: 10 }}>เลือกจำนวนรูปในโพสต์ (Carousel)</div>
                  <div style={{ display: 'flex', gap: 8 }}>
                    {[1, 2, 3, 4, 5].map(n => (
                      <button key={n} onClick={() => setCount(n)} style={{
                        flex: 1, padding: '14px 0', borderRadius: 'var(--radius-sm)', cursor: 'pointer',
                        border: `1.5px solid ${imageCount === n ? 'var(--accent)' : 'var(--border)'}`,
                        background: imageCount === n ? 'var(--accent-soft)' : 'var(--surface)',
                        color: imageCount === n ? 'var(--accent-strong)' : 'var(--ink-2)', transition: 'all .15s',
                      }}>
                        <div className="mono" style={{ fontSize: 20, fontWeight: 600 }}>{n}</div>
                        <div className="eyebrow" style={{ marginTop: 2 }}>{n === 1 ? 'SINGLE' : 'PHOTOS'}</div>
                      </button>
                    ))}
                  </div>
                </div>

                {/* Slots */}
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  <div className="eyebrow" style={{ display: 'flex', alignItems: 'center', gap: 6 }}><IconSliders size={13} /> ตั้งค่าแต่ละรูป</div>
                  {slots.map((slot, i) => (
                    <div key={slot.id} style={{ background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 'var(--radius-sm)', padding: 14, display: 'flex', gap: 12 }}>
                      {/* thumbnail */}
                      <div style={{ width: 60, height: 60, borderRadius: 'var(--radius-sm)', background: 'var(--surface-3)', overflow: 'hidden', flexShrink: 0, border: '1px solid var(--border)', display: 'grid', placeItems: 'center', position: 'relative' }}>
                        {slot.url
                          ? <img src={slot.url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                          : <span className="mono" style={{ fontSize: 11, color: 'var(--ink-4)' }}>{i + 1}</span>
                        }
                        {slot.gen && <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.45)', display: 'grid', placeItems: 'center' }}><IconRefresh size={18} className="spin" style={{ color: '#fff' }} /></div>}
                      </div>

                      {/* prompt + actions */}
                      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 8, minWidth: 0 }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <span className="chip">รูปที่ {i + 1}</span>
                          <div style={{ display: 'flex', gap: 6 }}>
                            <button onClick={() => copyText(slot.prompt)} className="chip" style={{ cursor: 'pointer', gap: 4 }}><IconCopy size={11} /> Copy</button>
                            <label className="chip" style={{ cursor: 'pointer', gap: 4, color: 'var(--accent-strong)' }}>
                              <IconUpload size={11} /> อัปโหลด
                              <input type="file" accept="image/*" style={{ display: 'none' }} onChange={(e) => { if (e.target.files[0]) { const u = URL.createObjectURL(e.target.files[0]); setSlots(s => s.map(x => x.id === slot.id ? { ...x, url: u } : x)); }}} />
                            </label>
                          </div>
                        </div>
                        <textarea value={slot.prompt} onChange={(e) => setSlots(s => s.map(x => x.id === slot.id ? { ...x, prompt: e.target.value } : x))}
                          className="field mono" style={{ height: 52, resize: 'none', fontSize: 11.5, lineHeight: 1.5 }} placeholder="English prompt for AI image generation…" />
                        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                          <button className="btn btn-ink" style={{ padding: '7px 12px', fontSize: 12 }} onClick={() => genImage(slot.id)} disabled={slot.gen || !slot.prompt.trim()}>
                            {slot.gen ? <IconRefresh size={13} className="spin" /> : <IconSpark size={13} />} สร้างรูปนี้
                          </button>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}
        </div>

        {/* ——— RIGHT: Preview ——— */}
        <div style={{ position: 'sticky', top: 0 }}>
          {captions.length === 0 ? (
            <div className="card" style={{ minHeight: 480, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', padding: 40, gap: 16 }}>
              {productImg
                ? <img src={productImg} alt="" style={{ width: 100, height: 100, objectFit: 'cover', borderRadius: 'var(--radius)', border: '2px solid var(--accent)', marginBottom: 4 }} />
                : <div style={{ width: 60, height: 60, borderRadius: '50%', background: 'var(--accent-soft)', color: 'var(--accent-strong)', display: 'grid', placeItems: 'center' }}><IconSend size={26} /></div>
              }
              <p style={{ margin: 0, fontSize: 14, fontWeight: 700, color: 'var(--ink-2)', maxWidth: 280, lineHeight: 1.5 }}>
                {productImg ? 'รูปสินค้าพร้อมแล้ว! ' : ''}
                กรอกชื่อสินค้า แล้วกด <span style={{ color: 'var(--accent-strong)' }}>ให้ AI เขียน</span>
              </p>
              <div className="eyebrow" style={{ maxWidth: 300, lineHeight: 1.7 }}>AI จะสร้าง PROMPT รูปภาพ · เขียน CAPTION · พรีวิวโพสต์ · และนำรูปสินค้าของคุณใส่ในโฆษณา</div>
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }} className="fade-up">
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div className="eyebrow" style={{ display: 'flex', alignItems: 'center', gap: 6 }}><IconCheckCircle size={15} style={{ color: 'var(--pos)' }} /> LIVE AD PREVIEW</div>
                <button onClick={() => copyText(captions[activeCaption])} className="chip" style={{ cursor: 'pointer', gap: 5 }}><IconCopy size={12} /> Copy Caption</button>
              </div>
              <div style={{ display: 'flex', gap: 7, flexWrap: 'wrap' }}>
                {captions.map((_, i) => (
                  <button key={i} onClick={() => setActiveCaption(i)} className="chip" style={{ cursor: 'pointer', background: activeCaption === i ? 'var(--ink)' : 'var(--surface-3)', color: activeCaption === i ? 'var(--surface)' : 'var(--ink-2)', border: 'none' }}>Caption {i + 1}</button>
                ))}
              </div>
              <FbPreview title={title || 'Your Brand Page'} caption={captions[activeCaption]} count={imageCount} slots={slots} productImg={productImg} />
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
