// Social — AI Studio (split from social.jsx).
// SfStudio, SfConvert, SfIdea, SfPlan, SfScript + shared btn/input consts.


// ── AI Studio (idea / weekly plan / script) ──
function SfStudio({ onToast, onSendToPrompter }) {
  const [sub, setSub] = useState('convert');
  const STABS = [
    { id: 'convert', label: '🔁 แปลงจากลิงก์ IG' },
    { id: 'idea', label: '💡 คิดไอเดียคอนเทนต์' },
    { id: 'plan', label: '🗓️ วางแผนโพสต์รายสัปดาห์' },
    { id: 'script', label: '🎬 เขียนสคริปต์' },
  ];
  return (
    <div className="flex flex-col gap-4">
      <div className="flex items-center gap-1.5 flex-wrap">
        {STABS.map(s => (
          <button key={s.id} onClick={() => setSub(s.id)}
            className={`px-3 py-2 rounded-lg text-[13px] font-semibold transition-all ${sub === s.id ? 'bg-brand-50 text-brand-700' : 'bg-white border border-ink-100 text-ink-600 hover:bg-ink-50'}`}>{s.label}</button>
        ))}
      </div>
      {sub === 'convert' && <SfConvert onToast={onToast} onSendToPrompter={onSendToPrompter} />}
      {sub === 'idea' && <SfIdea onToast={onToast} />}
      {sub === 'plan' && <SfPlan onToast={onToast} />}
      {sub === 'script' && <SfScript onToast={onToast} onSendToPrompter={onSendToPrompter} />}
    </div>
  );
}

// Parse an Instagram post/reel shortcode from a pasted URL.
function _igShortcode(url) {
  const m = (url || '').match(/instagram\.com\/(?:reel|reels|p|tv)\/([A-Za-z0-9_-]+)/i);
  return m ? m[1] : null;
}

// ── Convert from an IG link → our own content ──
// Realistic flow: paste the link (we embed the reel so you can watch it),
// paste the spoken words / caption (browser can't transcribe IG directly),
// then turn it into our own hook + script + caption. Uses the AI when
// available; otherwise reframes the pasted text with a template.
const SF_HIST_KEY = 'sf_convert_history';
function _sfLoadHist() { try { return JSON.parse(localStorage.getItem(SF_HIST_KEY) || '[]'); } catch { return []; } }
function _sfSaveHist(list) { try { localStorage.setItem(SF_HIST_KEY, JSON.stringify(list.slice(0, 30))); } catch {} }

function SfConvert({ onToast, onSendToPrompter }) {
  const [link, setLink] = useState('');
  const [src, setSrc] = useState('');         // pasted caption / transcript
  const [biz, setBiz] = useState('โค้ชธุรกิจ & ที่ปรึกษาการตลาดสำหรับ SME');
  const [tone, setTone] = useState('เป็นกันเอง จริงใจ มีตัวเลขจริง');
  const [cta, setCta] = useState('ทักแชทรับ checklist ฟรี');
  const [state, setState] = useState({ loading: false, doc: null });
  const [fetching, setFetching] = useState(false);
  const [stt, setStt] = useState('');  // '', 'link', 'file'
  const [history, setHistory] = useState(_sfLoadHist);
  const fileRef = React.useRef(null);
  const code = _igShortcode(link);
  const embed = code ? `https://www.instagram.com/reel/${code}/embed` : null;

  const saveItem = (doc) => setHistory(h => {
    const item = { id: Date.now(), ts: Date.now(), link, transcript: src, biz, tone, cta, doc };
    const next = [item, ...h].slice(0, 30);
    _sfSaveHist(next);
    return next;
  });
  const restore = (it) => {
    setLink(it.link || ''); setSrc(it.transcript || '');
    if (it.biz) setBiz(it.biz); if (it.tone) setTone(it.tone); if (it.cta) setCta(it.cta);
    setState({ loading: false, doc: it.doc || null });
    onToast('โหลดบันทึกแล้ว');
  };
  const delItem = (id) => setHistory(h => { const next = h.filter(x => x.id !== id); _sfSaveHist(next); return next; });

  const autoFetch = async () => {
    if (!code) { onToast('วางลิงก์ IG ที่ถูกต้องก่อน'); return; }
    setFetching(true);
    try {
      const d = await _sfFetchIgCaption(link);
      if (d && d.caption) { setSrc(d.caption); onToast('ดึงแคปชันสำเร็จ'); }
      else { onToast(d && d.error ? 'ดึงอัตโนมัติไม่ได้ — วางเอง' : 'ไม่พบแคปชัน'); }
    } catch { onToast('ดึงอัตโนมัติไม่ได้ — วางแคปชันเอง'); }
    finally { setFetching(false); }
  };
  const appendTranscript = (t) => setSrc(p => (p.trim() ? p.trim() + '\n' : '') + t);
  const transcribeLink = async () => {
    if (!code) { onToast('วางลิงก์ IG ที่ถูกต้องก่อน'); return; }
    setStt('link');
    try { const d = await _sfTranscribe({ igUrl: link }); if (d?.transcript) { appendTranscript(d.transcript); onToast('ถอดเสียงสำเร็จ'); } else onToast('ไม่พบเสียงพูด'); }
    catch (e) { onToast('ดึงจากลิงก์ไม่ได้ — ลองอัปโหลดไฟล์'); }
    finally { setStt(''); }
  };
  const transcribeFile = async (e) => {
    const f = e.target.files && e.target.files[0]; if (!f) return;
    setStt('file');
    try {
      const fd = new FormData(); fd.append('file', f, f.name);
      const d = await _sfTranscribe(fd);
      if (d?.transcript) { appendTranscript(d.transcript); onToast('ถอดเสียงจากไฟล์สำเร็จ'); } else onToast('ไม่พบเสียงพูด');
    } catch (err) { onToast('ถอดเสียงไม่ได้: ' + (err.message || '')); }
    finally { setStt(''); if (fileRef.current) fileRef.current.value = ''; }
  };

  const fallback = () => ({
    original: {
      summary: (src.trim().split('\n').filter(Boolean)[0] || 'เนื้อหาต้นฉบับ').slice(0, 120),
      points: src.trim().split(/\n+/).filter(Boolean).slice(0, 5),
    },
    ours: {
      hook: 'เวอร์ชันของเรา — ' + (src.trim().split('\n').filter(Boolean)[0] || 'หยุดเลื่อนก่อน!').slice(0, 70),
      script: [
        { stage: 'Hook', line: 'เปิดด้วยปัญหาที่กลุ่มเป้าหมายเจอจริง (อิงจากคลิปต้นฉบับ)' },
        { stage: 'เนื้อหา', line: src.trim().split(/\n+/).filter(Boolean).slice(0, 3).join(' / ') || 'เล่า 3 ประเด็นหลักด้วยมุมของเรา + ตัวอย่างจริง' },
        { stage: 'CTA', line: cta },
      ],
      caption: `${(src.trim().split('\n').filter(Boolean)[0] || '').slice(0, 80)}\n\nปรับมุมในแบบของ ${biz} · โทน: ${tone}\n👉 ${cta}`,
      hashtags: ['#คอนเทนต์', '#การตลาด', '#SME', '#โค้ชธุรกิจ'],
    },
  });

  const gen = async () => {
    if (!src.trim()) { onToast('วางคำพูด/แคปชันจากคลิปก่อน'); return; }
    setState({ loading: true, doc: null });
    const prompt = `นี่คือเนื้อหา/คำพูดจากคลิป Instagram ของคนอื่น:\n"""${src}"""\nช่วย (1) สรุปแก่นของคลิปต้นฉบับเป็น bullet สั้น ๆ และ (2) แปลงเป็นคอนเทนต์เวอร์ชันของเราเอง (ห้ามลอกคำต่อคำ) สำหรับธุรกิจ: ${biz} โทน: ${tone} CTA: ${cta}.
JSON {"original":{"summary":"","points":[""]},"ours":{"hook":"","script":[{"stage":"","line":""}],"caption":"","hashtags":[""]}}`;
    try { const d = await _sfAskJSON(prompt); setState({ loading: false, doc: d }); saveItem(d); onToast('แปลงคอนเทนต์สำเร็จ — บันทึกแล้ว'); }
    catch { await new Promise(r => setTimeout(r, 500)); const d = fallback(); setState({ loading: false, doc: d }); saveItem(d); onToast('แปลงแบบตัวอย่าง (ยังไม่ได้เติมเครดิต AI) — บันทึกแล้ว'); }
  };
  const copy = () => {
    const d = state.doc; if (!d) return;
    const t = (d.ours?.script || []).map(b => `[${b.stage}] ${b.line}`).join('\n') + '\n\n' + (d.ours?.caption || '');
    try { navigator.clipboard.writeText(t); } catch {}
    onToast('คัดลอกคอนเทนต์ของเราแล้ว');
  };
  const toPrompter = () => {
    const d = state.doc; if (!d || !onSendToPrompter) return;
    const text = (d.ours?.hook ? d.ours.hook + '\n\n' : '') + (d.ours?.script || []).map(b => b.line).filter(Boolean).join('\n\n');
    onSendToPrompter(text);
  };

  const Step = ({ n, title, hint }) => (
    <div className="flex items-center gap-2">
      <span className="w-6 h-6 rounded-full bg-brand-600 text-white text-[12px] font-bold inline-flex items-center justify-center flex-shrink-0">{n}</span>
      <div className="leading-tight">
        <div className="text-[13.5px] font-bold text-ink-800">{title}</div>
        {hint && <div className="text-[10.5px] text-ink-400">{hint}</div>}
      </div>
    </div>
  );

  return (
    <div className="flex flex-col gap-4">
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <SfFormCard>
          {/* STEP 1 — paste link */}
          <Step n="1" title="วางลิงก์คลิป Instagram" hint="คัดลอกลิงก์ reel/โพสต์มาวาง" />
          <div className="flex gap-1.5 mt-2">
            <input className={`${_inp} flex-1`} value={link} onChange={e => setLink(e.target.value)} placeholder="https://www.instagram.com/reel/..." inputMode="url" />
            <button onClick={autoFetch} disabled={fetching} title="ดึงแคปชัน" className="px-3 rounded-lg text-[12px] font-semibold bg-ink-100 text-ink-700 hover:bg-ink-200 whitespace-nowrap disabled:opacity-50">{fetching ? '…' : '⬇︎ แคปชัน'}</button>
          </div>
          {embed ? (
            <div className="rounded-xl overflow-hidden border border-ink-200 bg-ink-900 mt-2" style={{ aspectRatio: '9/12' }}>
              <iframe src={embed} title="ig" className="w-full h-full" frameBorder="0" scrolling="no" allowTransparency={true} />
            </div>
          ) : (
            <div className="rounded-xl border border-dashed border-ink-200 p-5 text-center text-[11px] text-ink-400 mt-2">📎 วางลิงก์ด้านบนเพื่อแสดงคลิป</div>
          )}

          {/* STEP 2 — get the words */}
          <div className="border-t border-ink-100 pt-3 mt-1">
            <Step n="2" title="ดึงคำพูดในคลิป" hint="ถอดเสียงอัตโนมัติ หรือพิมพ์/วางเอง" />
            <div className="flex items-center gap-1.5 flex-wrap mt-2">
              <button onClick={transcribeLink} disabled={!!stt} className="px-3 py-2 rounded-lg text-[12.5px] font-semibold bg-purple-600 text-white hover:bg-purple-700 disabled:opacity-60 inline-flex items-center gap-1.5">
                {stt === 'link' ? <><span className="w-3.5 h-3.5 border-2 border-white/40 border-t-white rounded-full animate-spin" />กำลังถอด…</> : <>🎙️ ถอดเสียงจากลิงก์</>}
              </button>
              <button onClick={() => fileRef.current && fileRef.current.click()} disabled={!!stt} className="px-3 py-2 rounded-lg text-[12.5px] font-semibold bg-ink-100 text-ink-700 hover:bg-ink-200 disabled:opacity-60 inline-flex items-center gap-1.5">
                {stt === 'file' ? <><span className="w-3.5 h-3.5 border-2 border-ink-300 border-t-ink-600 rounded-full animate-spin" />กำลังถอด…</> : <>⬆︎ อัปโหลดวิดีโอ/เสียง</>}
              </button>
              <input ref={fileRef} type="file" accept="video/*,audio/*" className="hidden" onChange={transcribeFile} />
            </div>
            {stt && (
              <div className="mt-2 rounded-lg bg-purple-50 border border-purple-100 px-3 py-2.5 flex items-center gap-2.5">
                <span className="w-4 h-4 border-2 border-purple-300 border-t-purple-600 rounded-full animate-spin flex-shrink-0" />
                <div className="text-[12px] text-purple-700 leading-snug">{stt === 'link' ? 'กำลังโหลดคลิปจาก IG แล้วถอดเสียง…' : 'กำลังถอดเสียงจากไฟล์…'}<div className="text-[10px] text-purple-400">อาจใช้เวลา ~15–30 วินาที กรุณารอสักครู่</div></div>
              </div>
            )}
            <textarea className={`${_inp} h-auto resize-none mt-2`} rows={5} value={src} onChange={e => setSrc(e.target.value)}
              placeholder="คำพูด/แคปชันจากคลิปจะมาแสดงที่นี่ — แก้ไขได้ก่อนแปลง" />
            <div className="text-[10px] text-ink-400 mt-1">ถ้าถอดจากลิงก์ไม่ได้ (โพสต์รูป/คลิปส่วนตัว) ให้โหลดคลิปแล้วกดอัปโหลด · รองรับ ≤24MB</div>
          </div>

          {/* STEP 3 — make it ours */}
          <div className="border-t border-ink-100 pt-3 mt-1">
            <Step n="3" title="ปรับให้เป็นสไตล์ของเรา" />
            <div className="mt-2 space-y-2">
              <SfField label="ธุรกิจของเรา"><input className={_inp} value={biz} onChange={e => setBiz(e.target.value)} /></SfField>
              <div className="grid grid-cols-2 gap-2">
                <SfField label="โทน"><input className={_inp} value={tone} onChange={e => setTone(e.target.value)} /></SfField>
                <SfField label="CTA"><input className={_inp} value={cta} onChange={e => setCta(e.target.value)} /></SfField>
              </div>
            </div>
            <button className={`${_genBtn} mt-3`} disabled={state.loading} onClick={gen}><Icon name="sparkles" className="w-4 h-4" />แปลงเป็นคอนเทนต์ของเรา</button>
            <div className="text-[10px] text-ink-400 mt-1.5">ถอดเสียงด้วย Whisper · แปลงคอนเทนต์ด้วย Claude · ผลลัพธ์บันทึกอัตโนมัติด้านล่าง</div>
          </div>
        </SfFormCard>

        <div>
          {state.loading ? <SfLoading label="กำลังแปลงคอนเทนต์…" />
            : !state.doc ? <SfEmpty ico="🔁" ttl="ยังไม่มีผลลัพธ์" sub="ทำตามขั้นตอน 1-2-3 แล้วกด แปลงเป็นคอนเทนต์ของเรา" />
            : (
              <div className="space-y-3">
                <Card pad={false}>
                  <div className="px-4 py-2.5 border-b border-ink-100 text-[12px] font-bold text-ink-500 uppercase tracking-wide">เนื้อหาต้นฉบับ (สรุป)</div>
                  <div className="p-4">
                    <div className="text-[13px] text-ink-700">{state.doc.original?.summary}</div>
                    <ul className="mt-2 space-y-1">{(state.doc.original?.points || []).map((p, i) => <li key={i} className="text-[12px] text-ink-500 flex gap-1.5"><span className="text-ink-300">•</span>{p}</li>)}</ul>
                  </div>
                </Card>
                <Card pad={false}>
                  <div className="px-4 py-2.5 border-b border-ink-100 flex items-center justify-between">
                    <span className="text-[12px] font-bold uppercase tracking-wide" style={{ color: '#4F46E5' }}>เวอร์ชันของเรา</span>
                    <div className="flex items-center gap-1.5">
                      <button onClick={copy} className="text-xs font-medium text-ink-600 hover:text-ink-900 px-2.5 h-7 rounded-lg bg-ink-50">📋 คัดลอก</button>
                      <button onClick={toPrompter} className="text-xs font-semibold text-white px-2.5 h-7 rounded-lg bg-gradient-to-r from-purple-600 to-brand-600">📱 เทเลพรอมป์เตอร์</button>
                    </div>
                  </div>
                  <div className="p-4 space-y-3">
                    <div><div className="text-[10px] font-bold text-ink-400">HOOK</div><div className="text-[14px] font-bold text-ink-900 mt-0.5">{state.doc.ours?.hook}</div></div>
                    <div className="space-y-1.5">
                      {(state.doc.ours?.script || []).map((b, i) => (
                        <div key={i} className="flex gap-2"><span className="text-[10px] font-bold px-1.5 py-0.5 rounded bg-purple-50 text-purple-600 flex-shrink-0 h-fit">{b.stage}</span><span className="text-[13px] text-ink-700">{b.line}</span></div>
                      ))}
                    </div>
                    {state.doc.ours?.caption && (
                      <div className="pt-2 border-t border-ink-100"><div className="text-[10px] font-bold text-ink-400 mb-1">CAPTION</div><div className="text-[13px] text-ink-700 whitespace-pre-wrap leading-relaxed">{state.doc.ours.caption}</div>
                        <div className="flex flex-wrap gap-1 mt-2">{(state.doc.ours.hashtags || []).map((h, i) => <span key={i} className="text-[11px] text-brand-600">{h}</span>)}</div></div>
                    )}
                  </div>
                </Card>
              </div>
            )}
        </div>
      </div>

      {/* History */}
      <Card pad={false}>
        <div className="px-4 py-2.5 border-b border-ink-100 flex items-center justify-between">
          <span className="text-[13px] font-bold text-ink-700">📁 บันทึกที่ผ่านมา {history.length > 0 && <span className="text-ink-400 font-normal">({history.length})</span>}</span>
          {history.length > 0 && <button onClick={() => { if (confirm('ลบบันทึกทั้งหมด?')) { setHistory([]); _sfSaveHist([]); } }} className="text-[11px] text-rose-500 hover:text-rose-700">ลบทั้งหมด</button>}
        </div>
        {history.length === 0 ? (
          <div className="p-6 text-center text-[12px] text-ink-400">ยังไม่มีบันทึก — เมื่อแปลงคอนเทนต์แล้วจะถูกเก็บไว้ที่นี่ให้กลับมาดูได้</div>
        ) : (
          <div className="divide-y divide-ink-50">
            {history.map(it => {
              const title = it.doc?.ours?.hook || (it.transcript || '').split('\n').filter(Boolean)[0] || '(ไม่มีหัวข้อ)';
              const when = new Date(it.ts).toLocaleString('th-TH', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
              return (
                <div key={it.id} className="px-4 py-3 flex items-center gap-3 hover:bg-ink-50/50">
                  <div className="flex-1 min-w-0">
                    <div className="text-[13px] font-semibold text-ink-800 truncate">{title}</div>
                    <div className="text-[11px] text-ink-400">{when}{it.link ? ' · ' + it.link.replace(/^https?:\/\/(www\.)?/, '').slice(0, 36) : ''}</div>
                  </div>
                  <button onClick={() => restore(it)} className="text-[12px] font-semibold text-brand-600 hover:text-brand-700 px-2.5 py-1 rounded-lg bg-brand-50 flex-shrink-0">เปิด</button>
                  <button onClick={() => delItem(it.id)} title="ลบ" className="text-ink-300 hover:text-rose-500 px-1.5 flex-shrink-0">✕</button>
                </div>
              );
            })}
          </div>
        )}
      </Card>
    </div>
  );
}

const _segBtn = (active) => `px-3 h-9 text-[12px] font-semibold rounded-md transition-all ${active ? 'bg-white text-ink-900 shadow-sm' : 'text-ink-500'}`;
const _genBtn = 'w-full h-10 rounded-lg bg-gradient-to-r from-purple-600 to-brand-600 text-white text-sm font-semibold inline-flex items-center justify-center gap-1.5 hover:opacity-90 disabled:opacity-50';
const _inp = 'w-full h-9 px-3 text-sm border border-ink-200 rounded-lg outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-500/15';

function SfFormCard({ children }) { return <Card><div className="space-y-3">{children}</div></Card>; }
function SfField({ label, children }) { return <div><label className="block text-[11px] font-semibold text-ink-600 mb-1">{label}</label>{children}</div>; }

function SfIdea({ onToast }) {
  const [biz, setBiz] = useState('โค้ชธุรกิจ & ที่ปรึกษาการตลาดสำหรับ SME');
  const [tone, setTone] = useState('เป็นกันเอง จริงใจ ใช้ภาษาคนทั่วไป มีตัวเลขจริง');
  const [goal, setGoal] = useState('เพิ่มผู้ติดตาม');
  const [plat, setPlat] = useState('TikTok');
  const [state, setState] = useState({ loading: false, ideas: null });
  const gen = async () => {
    setState({ loading: true, ideas: null });
    const prompt = `สร้างไอเดียคอนเทนต์ 5 ชิ้นสำหรับ ธุรกิจ: ${biz} เป้าหมาย: ${goal} แพลตฟอร์ม: ${plat} โทน: ${tone}. แต่ละไอเดีย: hook, angle, format. JSON {"ideas":[{"hook":"","angle":"","format":""}]}`;
    try { const d = await _sfAskJSON(prompt); setState({ loading: false, ideas: d.ideas || SF_FALLBACK_IDEAS }); onToast('สร้างไอเดียสำเร็จ'); }
    catch { await new Promise(r => setTimeout(r, 500)); setState({ loading: false, ideas: SF_FALLBACK_IDEAS }); onToast('แสดงตัวอย่างไอเดีย'); }
  };
  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
      <SfFormCard>
        <SfField label="ธุรกิจ / สินค้า"><input className={_inp} value={biz} onChange={e => setBiz(e.target.value)} /></SfField>
        <SfField label="เป้าหมายของคอนเทนต์"><div className="flex bg-ink-100 rounded-lg p-0.5">{['เพิ่มผู้ติดตาม', 'สร้างลีด', 'ปิดการขาย'].map(g => <button key={g} onClick={() => setGoal(g)} className={_segBtn(goal === g)}>{g}</button>)}</div></SfField>
        <SfField label="แพลตฟอร์มหลัก"><div className="flex bg-ink-100 rounded-lg p-0.5">{['TikTok', 'Instagram', 'Facebook'].map(p => <button key={p} onClick={() => setPlat(p)} className={_segBtn(plat === p)}>{p}</button>)}</div></SfField>
        <SfField label="โทน / สไตล์"><input className={_inp} value={tone} onChange={e => setTone(e.target.value)} /></SfField>
        <button className={_genBtn} disabled={state.loading} onClick={gen}><Icon name="sparkles" className="w-4 h-4" />สร้างไอเดีย 5 ชิ้น</button>
        <div className="text-[10px] text-ink-400">ผลลัพธ์สร้างด้วย AI — ปรับแก้ได้ก่อนนำไปใช้</div>
      </SfFormCard>
      <div>
        {state.loading ? <SfLoading label="กำลังคิดไอเดียคอนเทนต์…" />
          : !state.ideas ? <SfEmpty ico="💡" ttl="ยังไม่มีไอเดีย" sub="กรอกข้อมูลธุรกิจแล้วกด สร้างไอเดีย" />
          : (
            <div className="space-y-2.5">
              {state.ideas.map((it, i) => (
                <Card key={i} pad={false}><div className="p-3.5">
                  <div className="flex items-start gap-2">
                    <span className="w-6 h-6 rounded-md bg-brand-500 text-white text-[11px] font-bold flex items-center justify-center flex-shrink-0">{i + 1}</span>
                    <div className="flex-1 min-w-0"><div className="text-[13.5px] font-bold text-ink-900">{it.hook}</div><div className="text-[12px] text-ink-600 mt-1">{it.angle}</div></div>
                    <span className="text-[10px] font-semibold px-2 py-0.5 rounded bg-purple-50 text-purple-600 flex-shrink-0">{it.format}</span>
                  </div>
                  <div className="flex gap-2 mt-2.5"><button onClick={() => onToast('บันทึกไอเดียแล้ว')} className="text-[11px] font-medium text-ink-500 hover:text-ink-800">🔖 บันทึก</button></div>
                </div></Card>
              ))}
            </div>
          )}
      </div>
    </div>
  );
}

function SfPlan({ onToast }) {
  const [goal, setGoal] = useState('เพิ่มลีดคอร์ส 6 Weeks ก่อนเปิดรอบใหม่');
  const [freq, setFreq] = useState('5');
  const [state, setState] = useState({ loading: false, plan: null });
  const gen = async () => {
    setState({ loading: true, plan: null });
    const prompt = `จัดตารางโพสต์ ${freq} โพสต์ใน 1 สัปดาห์ เป้าหมาย: ${goal}. JSON {"plan":[{"day":"","topic":"","format":"","platform":"","goal":""}]}`;
    try { const d = await _sfAskJSON(prompt); setState({ loading: false, plan: d.plan || SF_FALLBACK_PLAN }); onToast('สร้างแผนสำเร็จ'); }
    catch { await new Promise(r => setTimeout(r, 500)); setState({ loading: false, plan: SF_FALLBACK_PLAN }); onToast('แสดงตัวอย่างแผน'); }
  };
  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
      <SfFormCard>
        <SfField label="เป้าหมายสัปดาห์นี้"><input className={_inp} value={goal} onChange={e => setGoal(e.target.value)} /></SfField>
        <SfField label="จำนวนโพสต์ / สัปดาห์"><div className="flex bg-ink-100 rounded-lg p-0.5">{['3', '5', '7'].map(f => <button key={f} onClick={() => setFreq(f)} className={_segBtn(freq === f)}>{f}</button>)}</div></SfField>
        <button className={_genBtn} disabled={state.loading} onClick={gen}><Icon name="sparkles" className="w-4 h-4" />สร้างแผนรายสัปดาห์</button>
        <div className="text-[10px] text-ink-400">ได้แผนแล้วกด ส่งเข้าปฏิทิน เพื่อจองคิวโพสต์</div>
      </SfFormCard>
      <div>
        {state.loading ? <SfLoading label="กำลังจัดตารางโพสต์…" />
          : !state.plan ? <SfEmpty ico="🗓️" ttl="ยังไม่มีแผน" sub="ระบุเป้าหมายและความถี่ ระบบจะจัดตารางให้" />
          : (
            <Card pad={false}>
              <div className="px-4 py-3 border-b border-ink-100 flex items-center justify-between">
                <div className="text-sm font-semibold text-ink-900">แผนโพสต์รายสัปดาห์ · {state.plan.length} โพสต์</div>
                <button onClick={() => onToast('ส่งแผนเข้าปฏิทินแล้ว')} className="text-xs font-semibold text-brand-600">ส่งเข้าปฏิทิน →</button>
              </div>
              <div className="divide-y divide-ink-50">
                {state.plan.map((p, i) => (
                  <div key={i} className="flex items-center gap-3 px-4 py-2.5">
                    <div className="w-12 text-[12px] font-bold text-ink-700 flex-shrink-0">{p.day}</div>
                    <div className="flex-1 min-w-0"><div className="text-[13px] font-semibold text-ink-900 truncate">{p.topic}</div><div className="text-[11px] text-ink-400">🎯 {p.goal}</div></div>
                    <div className="flex flex-col items-end gap-1 flex-shrink-0"><span className="text-[10px] font-medium px-2 py-0.5 rounded bg-ink-100 text-ink-600">{p.format}</span><span className="text-[10px] text-ink-500">{p.platform}</span></div>
                  </div>
                ))}
              </div>
            </Card>
          )}
      </div>
    </div>
  );
}

function SfScript({ onToast, onSendToPrompter }) {
  const [topic, setTopic] = useState('3 ความผิดพลาดที่ทำให้ร้านอาหารเจ๊ง ทั้งที่ขายดี');
  const [fmt, setFmt] = useState('Reel / TikTok 45 วิ');
  const [cta, setCta] = useState('ทักแชทรับ checklist ฟรี');
  const [state, setState] = useState({ loading: false, doc: null });
  const stageColors = ['#4F46E5', '#EF4444', '#F59E0B', '#10B981', '#0EA5E9', '#8B5CF6'];
  const gen = async () => {
    setState({ loading: true, doc: null });
    const prompt = `เขียนสคริปต์ หัวข้อ: ${topic} รูปแบบ: ${fmt} CTA: ${cta}. JSON {"title":"","blocks":[{"stage":"","time":"","line":"","direction":""}],"caption":"","hashtags":[]}`;
    try { const d = await _sfAskJSON(prompt); setState({ loading: false, doc: d }); onToast('เขียนสคริปต์สำเร็จ'); }
    catch { await new Promise(r => setTimeout(r, 500)); setState({ loading: false, doc: SF_FALLBACK_SCRIPT }); onToast('แสดงตัวอย่างสคริปต์'); }
  };
  const copy = () => {
    const d = state.doc; if (!d) return;
    const text = (d.blocks || []).map(b => `[${b.stage} ${b.time}]\n${b.line}`).join('\n\n') + '\n\n' + (d.caption || '');
    try { navigator.clipboard.writeText(text); } catch {}
    onToast('คัดลอกสคริปต์แล้ว');
  };
  // Spoken-only text for the teleprompter (drop stage/timestamp/direction).
  const toPrompter = () => {
    const d = state.doc; if (!d || !onSendToPrompter) return;
    const text = (d.title ? d.title + '\n\n' : '') + (d.blocks || []).map(b => b.line).filter(Boolean).join('\n\n');
    onSendToPrompter(text);
  };
  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
      <SfFormCard>
        <SfField label="หัวข้อ / ไอเดียคอนเทนต์"><textarea className={`${_inp} h-auto resize-none`} rows={3} value={topic} onChange={e => setTopic(e.target.value)} /></SfField>
        <SfField label="รูปแบบ"><div className="flex bg-ink-100 rounded-lg p-0.5">{['Reel / TikTok 45 วิ', 'YouTube 5 นาที'].map(f => <button key={f} onClick={() => setFmt(f)} className={_segBtn(fmt === f)}>{f}</button>)}</div></SfField>
        <SfField label="เป้าหมายปลายทาง (CTA)"><input className={_inp} value={cta} onChange={e => setCta(e.target.value)} /></SfField>
        <button className={_genBtn} disabled={state.loading} onClick={gen}><Icon name="sparkles" className="w-4 h-4" />เขียนสคริปต์</button>
        <div className="text-[10px] text-ink-400">สคริปต์แบ่งเป็น Hook · เนื้อหา · CTA พร้อม timestamp</div>
      </SfFormCard>
      <div>
        {state.loading ? <SfLoading label="กำลังเขียนสคริปต์…" />
          : !state.doc ? <SfEmpty ico="🎬" ttl="ยังไม่มีสคริปต์" sub="ใส่หัวข้อแล้วกด เขียนสคริปต์" />
          : (
            <Card pad={false}>
              <div className="px-4 py-3 border-b border-ink-100"><div className="text-sm font-bold text-ink-900">{state.doc.title}</div>
                <div className="flex gap-1.5 mt-1"><span className="text-[10px] px-2 py-0.5 rounded bg-ink-100 text-ink-600">{fmt}</span><span className="text-[10px] px-2 py-0.5 rounded bg-ink-100 text-ink-600">{(state.doc.blocks || []).length} ช่วง</span></div></div>
              <div className="divide-y divide-ink-50">
                {(state.doc.blocks || []).map((b, i) => (
                  <div key={i} className="flex gap-3 px-4 py-2.5">
                    <div className="w-20 flex-shrink-0"><div className="text-[12px] font-bold text-ink-900">{b.stage}</div><div className="text-[10px] text-ink-400 num">{b.time}</div><div className="w-8 h-1 rounded mt-1" style={{ background: stageColors[i % stageColors.length] }} /></div>
                    <div className="min-w-0"><div className="text-[13px] text-ink-800 leading-relaxed">{b.line}</div>{b.direction && <div className="text-[11px] text-ink-400 mt-1">🎬 {b.direction}</div>}</div>
                  </div>
                ))}
              </div>
              {state.doc.caption && (
                <div className="px-4 py-3 border-t border-ink-100">
                  <div className="text-[11px] font-bold text-ink-400 mb-1">CAPTION</div>
                  <div className="text-[13px] text-ink-700 leading-relaxed">{state.doc.caption}</div>
                  <div className="flex flex-wrap gap-1 mt-2">{(state.doc.hashtags || []).map((h, i) => <span key={i} className="text-[11px] text-brand-600">{h}</span>)}</div>
                </div>
              )}
              <div className="px-4 py-3 border-t border-ink-100 flex justify-end gap-2">
                <button onClick={copy} className="text-xs font-medium text-ink-600 hover:text-ink-900 px-3 h-8 rounded-lg bg-ink-50">📋 คัดลอก</button>
                <button onClick={toPrompter} className="text-xs font-semibold text-white px-3 h-8 rounded-lg bg-gradient-to-r from-purple-600 to-brand-600 inline-flex items-center gap-1.5">📱 ส่งไปเทเลพรอมป์เตอร์</button>
              </div>
            </Card>
          )}
      </div>
    </div>
  );
}
