/* ================ SCREENS 2 ================ */

/* ================ AI INBOX ================ */
const AIInbox = ({ onAction }) => {
  const [filter, setFilter] = React.useState("PROPOSED");
  const items = window.MOCK.aiInbox.filter(i => filter === "ALL" || i.status === filter);

  return (
    <div className="screen">
      <div className="screen-head">
        <div>
          <div className="breadcrumb">Wandee</div>
          <h1 className="page-title">AI Inbox</h1>
          <p className="page-sub">คำแนะนำ การวิเคราะห์ และ action ที่ AI เสนอ — มี {items.filter(i => i.status === "PROPOSED").length} รายการรออนุมัติ</p>
        </div>
        <div className="head-actions">
          <div className="seg">
            <button className={filter === "PROPOSED" ? "active" : ""} onClick={() => setFilter("PROPOSED")}>รออนุมัติ</button>
            <button className={filter === "APPLIED" ? "active" : ""} onClick={() => setFilter("APPLIED")}>ทำแล้ว</button>
            <button className={filter === "ALL" ? "active" : ""} onClick={() => setFilter("ALL")}>ทั้งหมด</button>
          </div>
        </div>
      </div>

      <div className="inbox-grid">
        {items.map(i => (
          <div key={i.id} className={`inbox-card severity-${i.severity}`}>
            <div className="inbox-card-head">
              <div className={`inbox-icon kind-${i.kind.toLowerCase()}`}>
                {i.kind === "WINNER" && <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2L15 9L22 10L17 15L18 22L12 19L6 22L7 15L2 10L9 9Z"/></svg>}
                {i.kind === "FATIGUE" && <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="12" r="10"/><path d="M8 14C9 12 11 12 12 14C13 16 15 16 16 14" stroke="white" fill="none" strokeWidth="2"/></svg>}
                {i.kind === "AT_RISK" && <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2L22 20H2Z"/></svg>}
                {i.kind === "OPPORTUNITY" && <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2L13.5 8.5L20 10L13.5 11.5L12 18L10.5 11.5L4 10L10.5 8.5Z"/></svg>}
                {i.kind === "ANOMALY" && <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M4 18L8 10L13 14L20 6" stroke="white" strokeWidth="2" fill="none"/></svg>}
                {i.kind === "DONE" && <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M4 12L10 18L20 6" stroke="white" strokeWidth="3" fill="none"/></svg>}
              </div>
              <div className="inbox-meta">
                <span className="kind">{i.kind.replace("_", " ")}</span>
                <span className="muted small">{i.createdAt}</span>
              </div>
              {i.status === "PROPOSED" && <span className="status-tag proposed">รออนุมัติ</span>}
              {i.status === "APPLIED" && <span className="status-tag applied">ทำแล้ว</span>}
            </div>
            <h3 className="inbox-title">{i.title}</h3>
            <p className="inbox-body">{i.body}</p>
            <div className="inbox-meter">
              <span className="muted small">ความมั่นใจ {Math.round(i.confidence * 100)}%</span>
              <div className="ai-conf-bar"><div style={{ width: `${i.confidence * 100}%` }}></div></div>
            </div>
            {i.status === "PROPOSED" && (
              <div className="inbox-actions">
                <button className="btn-primary-sm" onClick={() => onAction(i, "apply")}>
                  ✓ อนุมัติ
                </button>
                <button className="btn-ghost-sm" onClick={() => onAction(i, "dismiss")}>ผ่าน</button>
                <button className="btn-ghost-sm">รายละเอียด</button>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
};

/* ================ AI CHAT ================ */
const AIChat = () => {
  const [messages, setMessages] = React.useState([
    { role: "ai", text: "สวัสดีครับ ผมคือ Wandee AI ผมเข้าถึงข้อมูลทุกแคมเปญและออเดอร์ของคุณได้ พิมพ์อะไรก็ได้ เช่น 'สรุปผล 7 วันที่ผ่านมา' หรือ 'ปิดแคมเปญ Linen ให้หน่อย'", time: "14:32" },
  ]);
  const [input, setInput] = React.useState("");
  const [thinking, setThinking] = React.useState(false);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });
  }, [messages, thinking]);

  const send = (text) => {
    const t = (text ?? input).trim();
    if (!t) return;
    const time = new Date().toLocaleTimeString("th-TH", { hour: "2-digit", minute: "2-digit" });
    setMessages(m => [...m, { role: "user", text: t, time }]);
    setInput("");
    setThinking(true);
    setTimeout(() => {
      const low = t.toLowerCase();
      let reply = { role: "ai", text: "", time, kind: "text" };
      if (t.includes("สรุป") || low.includes("summar")) {
        reply.text = "สรุปผล 7 วันที่ผ่านมา · Wandee";
        reply.kind = "summary";
      } else if (t.includes("ปิด") && t.includes("Linen")) {
        reply.text = "เข้าใจครับ — Linen Wide-leg Pants · Summer (ROAS 1.18) · งบ ฿500/วัน\n\nหลังจากปิด ผมจะ:\n1. หยุดทันที (ทุก ad set: as5)\n2. โอนงบ ฿500/วันไปที่ pool campaign budget\n3. สร้าง ai_action สำหรับ rollback ได้\n\nยืนยันการปิดมั้ยครับ?";
        reply.kind = "confirm-pause";
      } else if (t.includes("ร่าง") || t.includes("สร้าง")) {
        reply.text = "ดีครับ — ผมจะร่างจาก winner ตอนนี้ของพอร์ต";
        reply.kind = "draft-campaign";
      } else if (t.includes("ROAS") || t.includes("ผลงาน")) {
        reply.text = "Portfolio ROAS · 7 วัน";
        reply.kind = "roas-table";
      } else {
        reply.text = "ผมเข้าใจคำถามแล้วครับ กำลังประมวลผล...";
      }
      setMessages(m => [...m, reply]);
      setThinking(false);
    }, 1100);
  };

  const renderRich = (m) => {
    if (m.kind === "summary") {
      const k = window.MOCK.kpi;
      return (
        <div className="rich-card">
          <div className="rich-title">{m.text}</div>
          <div className="rich-row">
            <div><span className="muted">รายได้</span><strong>{window.fmt.money(k.revenuePeriod)}</strong></div>
            <div><span className="muted">Spend</span><strong>{window.fmt.money(k.spendPeriod)}</strong></div>
            <div><span className="muted">ROAS</span><strong className="pos">{k.roas.toFixed(2)}×</strong></div>
            <div><span className="muted">กำไรสุทธิ</span><strong className="pos">{window.fmt.money(k.profitPeriod)}</strong></div>
          </div>
          <div className="rich-list">
            <div><span className="muted">📈 Top performer:</span> Silver Jewelry (ROAS 5.40)</div>
            <div><span className="muted">⚠️ ต้องดูแล:</span> Linen Wide-leg (ROAS 1.18)</div>
            <div><span className="muted">💡 AI พบ:</span> 1,284 ลูกค้าซื้อซ้ำที่ยังไม่ได้ retarget</div>
          </div>
        </div>
      );
    }
    if (m.kind === "confirm-pause") {
      return (
        <div>
          <div style={{ whiteSpace: "pre-line" }}>{m.text}</div>
          <div className="confirm-row">
            <button className="btn-danger-sm">ยืนยันปิด</button>
            <button className="btn-ghost-sm">ยกเลิก</button>
          </div>
        </div>
      );
    }
    if (m.kind === "draft-campaign") {
      return (
        <div className="rich-card">
          <div className="rich-title">{m.text}</div>
          <div className="draft-block">
            <div className="muted small">CAMPAIGN</div>
            <div><strong>Lace Collection · Expansion</strong></div>
            <div>Objective: OUTCOME_SALES · Budget: ฿800/วัน</div>
          </div>
          <div className="draft-block">
            <div className="muted small">AD SET</div>
            <div><strong>หญิง 22-38 · IG-first (Lookalike 1%)</strong></div>
            <div>Seed: ลูกค้าซื้อ ≥2 ครั้ง 90 วัน · Placement: IG Reels + Stories</div>
          </div>
          <div className="draft-block">
            <div className="muted small">AD CREATIVE (ดัดแปลงจาก winner)</div>
            <div><strong>Reel 15s · ลูกไม้บาน v2</strong></div>
            <div>Hook ใหม่: "ลูกไม้ลายดอกผกาเกษร · จำกัด 80 ชิ้น"</div>
          </div>
          <div className="confirm-row">
            <button className="btn-primary-sm">เปิด Builder ดูเต็ม</button>
            <button className="btn-ghost-sm">ขอเวอร์ชันอื่น</button>
          </div>
        </div>
      );
    }
    if (m.kind === "roas-table") {
      return (
        <div className="rich-card">
          <div className="rich-title">{m.text}</div>
          <table className="mini-table">
            <thead><tr><th>Campaign</th><th>Spend</th><th>ROAS</th></tr></thead>
            <tbody>
              {window.MOCK.campaigns.slice().sort((a, b) => b.roas - a.roas).map(c => (
                <tr key={c.id}>
                  <td>{c.name}</td>
                  <td>{window.fmt.money(c.spendPeriod)}</td>
                  <td><span className={`roas-pill ${c.roas >= 3 ? "good" : c.roas >= 2 ? "ok" : c.roas >= 1.5 ? "warn" : "bad"}`}>{c.roas.toFixed(2)}×</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    }
    return <div style={{ whiteSpace: "pre-line" }}>{m.text}</div>;
  };

  return (
    <div className="screen chat-screen">
      <div className="screen-head">
        <div>
          <div className="breadcrumb">Wandee</div>
          <h1 className="page-title">AI Chat</h1>
        </div>
      </div>

      <div className="chat-page" ref={scrollRef}>
        {messages.map((m, i) => (
          <div key={i} className={`chat-msg ${m.role} large`}>
            {m.role === "ai" && (
              <div className="chat-avatar large">
                <svg viewBox="0 0 24 24" width="14" height="14"><path d="M12 2L13.5 8.5L20 10L13.5 11.5L12 18L10.5 11.5L4 10L10.5 8.5Z" fill="currentColor"/></svg>
              </div>
            )}
            <div className="chat-bubble-wrap">
              <div className={`chat-bubble ${m.role} large`}>{renderRich(m)}</div>
              <div className="muted small" style={{ marginTop: 4 }}>{m.time}</div>
            </div>
          </div>
        ))}
        {thinking && (
          <div className="chat-msg ai large">
            <div className="chat-avatar large">
              <svg viewBox="0 0 24 24" width="14" height="14"><path d="M12 2L13.5 8.5L20 10L13.5 11.5L12 18L10.5 11.5L4 10L10.5 8.5Z" fill="currentColor"/></svg>
            </div>
            <div className="chat-bubble ai thinking large"><span></span><span></span><span></span></div>
          </div>
        )}
      </div>

      <div className="chat-composer">
        <div className="chat-quick" style={{ marginBottom: 8 }}>
          {["สรุปผล 7 วันที่ผ่านมา", "Portfolio ROAS", "ปิดแคมเปญ Linen", "ร่างแคมเปญใหม่จาก winner"].map(q => (
            <button key={q} className="quick-chip" onClick={() => send(q)}>{q}</button>
          ))}
        </div>
        <div className="chat-input-row large">
          <input value={input} onChange={(e) => setInput(e.target.value)} onKeyDown={(e) => e.key === "Enter" && send()} placeholder="พิมพ์คำสั่งหรือคำถาม..." />
          <button className="btn-icon-primary" onClick={() => send()}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M5 12L19 12M13 6L19 12L13 18"/></svg>
          </button>
        </div>
      </div>
    </div>
  );
};

/* ================ ORDERS & ATTRIBUTION ================ */
const OrdersAttribution = () => {
  const orders = window.MOCK.orders;
  const ads = window.MOCK.ads;
  const totalRev = orders.reduce((s, o) => s + o.total, 0);
  const adRev = orders.filter(o => o.adId).reduce((s, o) => s + o.total, 0);
  const organic = orders.filter(o => !o.adId).reduce((s, o) => s + o.total, 0);

  const byAd = {};
  orders.filter(o => o.adId).forEach(o => {
    if (!byAd[o.adId]) byAd[o.adId] = { rev: 0, count: 0 };
    byAd[o.adId].rev += o.total;
    byAd[o.adId].count += 1;
  });

  return (
    <div className="screen">
      <div className="screen-head">
        <div>
          <div className="breadcrumb">Wandee</div>
          <h1 className="page-title">Orders × Attribution</h1>
          <p className="page-sub">ออเดอร์จาก Strapi เชื่อมโยงกับแอดที่ทำให้เกิด — ข้อมูลที่ Facebook ไม่มี</p>
        </div>
      </div>

      <div className="attr-summary">
        <div className="attr-bar">
          <div className="bar-segment ad" style={{ width: `${(adRev / totalRev) * 100}%` }}>
            <span>จากแอด ({((adRev / totalRev) * 100).toFixed(0)}%)</span>
            <strong>{window.fmt.money(adRev)}</strong>
          </div>
          <div className="bar-segment organic" style={{ width: `${(organic / totalRev) * 100}%` }}>
            <span>Organic ({((organic / totalRev) * 100).toFixed(0)}%)</span>
            <strong>{window.fmt.money(organic)}</strong>
          </div>
        </div>
        <div className="attr-stats">
          <div><span className="muted">Total Orders (วันนี้-เมื่อวาน)</span><strong>{orders.length}</strong></div>
          <div><span className="muted">Revenue</span><strong>{window.fmt.money(totalRev)}</strong></div>
          <div><span className="muted">AOV</span><strong>{window.fmt.money(totalRev / orders.length)}</strong></div>
          <div><span className="muted">Multi-touch</span><strong>{orders.filter(o => o.touches > 1).length} orders</strong></div>
        </div>
      </div>

      <div className="two-pane">
        <div className="pane">
          <h3>Orders ล่าสุด</h3>
          <table className="data-table compact">
            <thead>
              <tr>
                <th>Order</th><th>เวลา</th><th>ลูกค้า</th><th>สินค้า</th><th className="right">Total</th><th>ช่องทาง</th><th>Ad</th><th>Touches</th>
              </tr>
            </thead>
            <tbody>
              {orders.map(o => {
                const ad = ads.find(a => a.id === o.adId);
                return (
                  <tr key={o.id}>
                    <td className="mono">{o.code}</td>
                    <td className="muted small">{new Date(o.date).toLocaleString("th-TH", { hour: "2-digit", minute: "2-digit", day: "numeric", month: "short" })}</td>
                    <td>{o.customer}</td>
                    <td className="truncate" style={{ maxWidth: 200 }}>{o.items.join(", ")}</td>
                    <td className="right num">{window.fmt.money(o.total)}</td>
                    <td><span className={`channel-pill ch-${o.channel.replace(/\s/g, "-").toLowerCase()}`}>{o.channel}</span></td>
                    <td className="truncate" style={{ maxWidth: 180 }}>{ad ? ad.name : <span className="muted">—</span>}</td>
                    <td>{o.touches === 0 ? <span className="muted">—</span> : <span className="touch-pill">{o.touches}</span>}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        <div className="pane">
          <h3>Top Revenue โดยแอด</h3>
          {Object.entries(byAd).sort((a, b) => b[1].rev - a[1].rev).slice(0, 6).map(([adId, d]) => {
            const ad = ads.find(a => a.id === adId);
            return (
              <div key={adId} className="top-ad-row">
                <div className="top-ad-name">
                  <span className={`format-tag fmt-${ad?.format}`}>{ad?.format.replace("single_", "").toUpperCase()}</span>
                  <span>{ad?.name}</span>
                </div>
                <div className="top-ad-stats">
                  <span>{d.count} orders</span>
                  <strong>{window.fmt.money(d.rev)}</strong>
                </div>
                <div className="top-ad-bar" style={{ width: `${(d.rev / Math.max(...Object.values(byAd).map(b => b.rev))) * 100}%` }}></div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

/* ================ CREATIVE LIBRARY ================ */
const CreativeLibrary = () => {
  const [format, setFormat] = React.useState("ALL");
  const creatives = window.MOCK.creatives.filter(c => format === "ALL" || c.format === format);

  return (
    <div className="screen">
      <div className="screen-head">
        <div>
          <div className="breadcrumb">Wandee</div>
          <h1 className="page-title">Creative Library</h1>
        </div>
        <div className="head-actions">
          <div className="seg">
            <button className={format === "ALL" ? "active" : ""} onClick={() => setFormat("ALL")}>All</button>
            <button className={format === "video" ? "active" : ""} onClick={() => setFormat("video")}>Video</button>
            <button className={format === "carousel" ? "active" : ""} onClick={() => setFormat("carousel")}>Carousel</button>
            <button className={format === "single_image" ? "active" : ""} onClick={() => setFormat("single_image")}>Image</button>
          </div>
          <button className="btn-primary">+ Upload</button>
        </div>
      </div>

      <div className="creative-grid">
        {creatives.map(c => (
          <div key={c.id} className="creative-card">
            <div className={`creative-media media-${c.color}`}>
              {c.format === "video" && (
                <div className="play-overlay">
                  <svg width="32" height="32" viewBox="0 0 24 24" fill="white"><path d="M6 4L20 12L6 20Z"/></svg>
                </div>
              )}
              <span className="format-tag-overlay">{c.format.toUpperCase()}</span>
              <span className="media-placeholder-text">{c.name}</span>
            </div>
            <div className="creative-info">
              <div className="creative-name">{c.name}</div>
              <div className="creative-meta-row">
                <span className="muted small">CTA: {c.cta}</span>
                <span className={`perf-pill ${c.performance >= 4 ? "good" : c.performance >= 3 ? "ok" : "warn"}`}>★ {c.performance.toFixed(1)}</span>
              </div>
              <div className="creative-copy">{c.body}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

/* ================ CLIENT REPORT ================ */
const ClientReport = () => {
  const k = window.MOCK.kpi;
  return (
    <div className="screen report-screen">
      <div className="report-head">
        <div>
          <div className="muted small">REPORT · WEEK 19 · 6–12 พ.ค. 2026</div>
          <h1 style={{ fontSize: 36, margin: "8px 0", fontWeight: 600 }}>Wandee</h1>
          <p style={{ color: "var(--ink-soft)" }}>สรุปผลโฆษณาประจำสัปดาห์</p>
        </div>
        <div>
          <button className="btn-ghost">Share link</button>
          <button className="btn-primary">Download PDF</button>
        </div>
      </div>

      <div className="report-headline">
        <div className="rh-stat">
          <span>Total Revenue</span>
          <strong>{window.fmt.money(k.revenuePeriod)}</strong>
          <span className="pos">+18.4% vs สัปดาห์ก่อน</span>
        </div>
        <div className="rh-stat">
          <span>Ad Spend</span>
          <strong>{window.fmt.money(k.spendPeriod)}</strong>
          <span className="muted">vs target ฿35,000</span>
        </div>
        <div className="rh-stat hero">
          <span>True ROAS</span>
          <strong>{k.roas.toFixed(2)}×</strong>
          <span className="pos">+11.4%</span>
        </div>
        <div className="rh-stat">
          <span>กำไรสุทธิ</span>
          <strong>{window.fmt.money(k.profitPeriod)}</strong>
          <span className="pos">margin {k.profitMargin.toFixed(0)}%</span>
        </div>
      </div>

      <div className="report-section">
        <h2>ไฮไลต์ของสัปดาห์</h2>
        <div className="report-bullets">
          <div className="bullet good">
            <strong>🏆 Reel "ลูกไม้บานสะพรั่ง" คือ winner</strong>
            <p>ROAS 4.18× · 24 orders ใน 7 วัน · AI กำลัง scale งบ +50%</p>
          </div>
          <div className="bullet warn">
            <strong>⚠️ ผ้าฝ้ายย้อมคราม เริ่ม fatigue</strong>
            <p>Frequency 4.2 · แนะนำเปลี่ยน creative — refresh แล้ว 12 พ.ค.</p>
          </div>
          <div className="bullet ok">
            <strong>💍 ขายส่งเครื่องเงิน · ROAS สูงสุดในพอร์ต</strong>
            <p>ROAS 5.40× · LINE conversion ทำงานดี · งบยังเหลือ 38%</p>
          </div>
        </div>
      </div>

      <div className="report-section">
        <h2>แคมเปญทั้งหมด</h2>
        <table className="data-table">
          <thead><tr><th>Campaign</th><th className="right">Spend</th><th className="right">Revenue</th><th className="right">Orders</th><th className="right">ROAS</th></tr></thead>
          <tbody>
            {window.MOCK.campaigns.map(c => (
              <tr key={c.id}>
                <td>{c.name}</td>
                <td className="right num">{window.fmt.money(c.spendPeriod)}</td>
                <td className="right num">{window.fmt.money(c.revenuePeriod)}</td>
                <td className="right num">{c.ordersPeriod}</td>
                <td className="right num"><span className={`roas-pill ${c.roas >= 3 ? "good" : c.roas >= 2 ? "ok" : c.roas >= 1.5 ? "warn" : "bad"}`}>{c.roas.toFixed(2)}×</span></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="report-section">
        <h2>สิ่งที่ AI ทำให้สัปดาห์นี้</h2>
        <ul className="report-ai-list">
          <li>เพิ่มงบ Songkran Sale +18% ตามผลงาน (auto)</li>
          <li>ปิด Boho Dress · IG Reels Test (ROAS 0.84) — auto</li>
          <li>Duplicate Reel ลูกไม้ → audience ใหม่ (approved by คุณ)</li>
          <li>ส่ง CAPI Purchase 187 events เพื่อช่วย FB optimize</li>
          <li>ตรวจ audience overlap · พบ 38% ระหว่าง c1 กับ c4</li>
        </ul>
      </div>
    </div>
  );
};

/* ================ CAMPAIGN BUILDER ================ */
const CampaignBuilder = ({ onClose, onCreate }) => {
  const [step, setStep] = React.useState(0);
  const [draft, setDraft] = React.useState({
    name: "",
    objective: "OUTCOME_SALES",
    dailyBudget: 800,
    audience: "หญิง 25-45 · กทม+ปริมณฑล",
    placement: ["FB Feed", "IG Feed", "IG Stories"],
    ageMin: 25, ageMax: 45,
    creative: { format: "video", body: "", cta: "SHOP_NOW", color: "rose" },
    aiAssist: true,
  });

  const steps = ["แคมเปญ", "Ad Set + Audience", "Ad + Creative", "Review"];

  const update = (patch) => setDraft(d => ({ ...d, ...patch }));
  const updateCreative = (patch) => setDraft(d => ({ ...d, creative: { ...d.creative, ...patch } }));

  return (
    <div className="builder-overlay">
      <div className="builder">
        <div className="builder-head">
          <div>
            <h2 style={{ margin: 0 }}>สร้างแคมเปญใหม่</h2>
            <div className="muted small">Step {step + 1} of {steps.length} · {steps[step]}</div>
          </div>
          <button className="icon-btn" onClick={onClose}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6L18 18M6 18L18 6"/></svg>
          </button>
        </div>

        <div className="builder-stepper">
          {steps.map((s, i) => (
            <div key={s} className={`b-step ${i === step ? "active" : ""} ${i < step ? "done" : ""}`} onClick={() => i < step && setStep(i)}>
              <div className="b-step-dot">{i < step ? "✓" : i + 1}</div>
              <span>{s}</span>
            </div>
          ))}
        </div>

        <div className="builder-body">
          {step === 0 && (
            <div className="builder-form">
              <label>
                <span>ชื่อแคมเปญ</span>
                <input value={draft.name} onChange={(e) => update({ name: e.target.value })} placeholder="เช่น Songkran Sale · เดรสผ้าไหม" />
              </label>
              <label>
                <span>Objective</span>
                <div className="obj-grid">
                  {[
                    { k: "OUTCOME_SALES", l: "Sales", d: "เพิ่มยอดขาย" },
                    { k: "OUTCOME_LEADS", l: "Leads", d: "เก็บลูกค้าใหม่" },
                    { k: "OUTCOME_TRAFFIC", l: "Traffic", d: "นำคนเข้าเว็บ" },
                    { k: "OUTCOME_ENGAGEMENT", l: "Engagement", d: "เพิ่มการมีส่วนร่วม" },
                    { k: "OUTCOME_AWARENESS", l: "Awareness", d: "สร้างการรับรู้" },
                  ].map(o => (
                    <button key={o.k} className={`obj-card ${draft.objective === o.k ? "active" : ""}`} onClick={() => update({ objective: o.k })}>
                      <strong>{o.l}</strong>
                      <span className="muted small">{o.d}</span>
                    </button>
                  ))}
                </div>
              </label>
              <label>
                <span>งบรายวัน (Daily Budget)</span>
                <div className="budget-input">
                  <span>฿</span>
                  <input type="number" value={draft.dailyBudget} onChange={(e) => update({ dailyBudget: +e.target.value })} />
                  <span className="muted small">/ วัน</span>
                </div>
                <div className="budget-presets">
                  {[300, 500, 800, 1200, 2000].map(b => (
                    <button key={b} className={draft.dailyBudget === b ? "active" : ""} onClick={() => update({ dailyBudget: b })}>฿{b}</button>
                  ))}
                </div>
              </label>
              <div className="ai-helper-strip">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2L13.5 8.5L20 10L13.5 11.5L12 18L10.5 11.5L4 10L10.5 8.5Z"/></svg>
                <span>AI แนะนำ: จากผลงาน 30 วัน แคมเปญ Sales งบ ฿800/วัน ROAS เฉลี่ย 3.1×</span>
              </div>
            </div>
          )}

          {step === 1 && (
            <div className="builder-form">
              <label>
                <span>ชื่อ Ad Set</span>
                <input value={draft.audience} onChange={(e) => update({ audience: e.target.value })} />
              </label>
              <label>
                <span>อายุ</span>
                <div style={{ display: "flex", gap: 12 }}>
                  <input type="number" value={draft.ageMin} onChange={(e) => update({ ageMin: +e.target.value })} style={{ width: 80 }} />
                  <span style={{ alignSelf: "center" }}>—</span>
                  <input type="number" value={draft.ageMax} onChange={(e) => update({ ageMax: +e.target.value })} style={{ width: 80 }} />
                </div>
              </label>
              <label>
                <span>Placement</span>
                <div className="placement-grid">
                  {["FB Feed", "FB Stories", "IG Feed", "IG Stories", "IG Reels", "Messenger", "Audience Network"].map(p => (
                    <button key={p} className={`pill-toggle ${draft.placement.includes(p) ? "active" : ""}`} onClick={() => {
                      const has = draft.placement.includes(p);
                      update({ placement: has ? draft.placement.filter(x => x !== p) : [...draft.placement, p] });
                    }}>{p}</button>
                  ))}
                </div>
              </label>
              <div className="ai-helper-strip">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2L13.5 8.5L20 10L13.5 11.5L12 18L10.5 11.5L4 10L10.5 8.5Z"/></svg>
                <span>AI แนะนำ: ลูกค้าผ้าไทยส่วนใหญ่อายุ 25-45 · IG Reels + Stories = ROAS สูงสุด</span>
              </div>
              <div className="audience-est">
                <span>Estimated reach</span>
                <strong>2.1M – 2.6M</strong>
                <div className="audience-bar"><div style={{ width: "62%" }}></div></div>
                <span className="muted small">Audience size: <strong>กลาง</strong></span>
              </div>
            </div>
          )}

          {step === 2 && (
            <div className="builder-form">
              <label>
                <span>Format</span>
                <div className="format-row">
                  {["video", "carousel", "single_image"].map(f => (
                    <button key={f} className={`format-card ${draft.creative.format === f ? "active" : ""}`} onClick={() => updateCreative({ format: f })}>
                      <div className={`format-thumb media-${draft.creative.color}`}>
                        {f === "video" && <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M6 4L20 12L6 20Z"/></svg>}
                        {f === "carousel" && <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="6" width="6" height="12"/><rect x="11" y="6" width="6" height="12"/><rect x="19" y="6" width="2" height="12"/></svg>}
                        {f === "single_image" && <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="5" width="18" height="14"/></svg>}
                      </div>
                      <span>{f.replace("single_", "").replace("_", " ")}</span>
                    </button>
                  ))}
                </div>
              </label>
              <label>
                <span>Body copy</span>
                <textarea value={draft.creative.body} onChange={(e) => updateCreative({ body: e.target.value })} rows={3} placeholder="ผ้าไหมไทยทอมือ · สวยทุกองศา" />
                <button className="btn-ghost-sm" style={{ alignSelf: "flex-start", marginTop: 6 }}>
                  <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2L13.5 8.5L20 10L13.5 11.5L12 18L10.5 11.5L4 10L10.5 8.5Z"/></svg>
                  AI เขียนให้
                </button>
              </label>
              <label>
                <span>Call-to-Action</span>
                <select value={draft.creative.cta} onChange={(e) => updateCreative({ cta: e.target.value })}>
                  <option value="SHOP_NOW">SHOP NOW</option>
                  <option value="LEARN_MORE">LEARN MORE</option>
                  <option value="ORDER_NOW">ORDER NOW</option>
                  <option value="GET_QUOTE">GET QUOTE</option>
                  <option value="MESSAGE">MESSAGE</option>
                </select>
              </label>
            </div>
          )}

          {step === 3 && (
            <div className="builder-review">
              <div className="review-block">
                <div className="muted small">CAMPAIGN</div>
                <strong>{draft.name || "—"}</strong>
                <div>Objective: {draft.objective.replace("OUTCOME_", "")} · งบ ฿{draft.dailyBudget}/วัน</div>
              </div>
              <div className="review-block">
                <div className="muted small">AD SET · AUDIENCE</div>
                <strong>{draft.audience}</strong>
                <div>อายุ {draft.ageMin}–{draft.ageMax} · {draft.placement.join(", ")}</div>
              </div>
              <div className="review-block">
                <div className="muted small">AD · CREATIVE</div>
                <strong>{draft.creative.format.toUpperCase()} · CTA: {draft.creative.cta}</strong>
                <div>{draft.creative.body || "(ยังไม่ได้ใส่ copy)"}</div>
              </div>
              <div className="ai-helper-strip">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2L13.5 8.5L20 10L13.5 11.5L12 18L10.5 11.5L4 10L10.5 8.5Z"/></svg>
                <span>AI Forecast (30 วัน): Spend ฿24,000 · Revenue ~฿72,000 · ROAS 3.0× ± 0.5</span>
              </div>
            </div>
          )}
        </div>

        <div className="builder-foot">
          <button className="btn-ghost" onClick={onClose}>Cancel</button>
          <div style={{ display: "flex", gap: 8 }}>
            {step > 0 && <button className="btn-ghost" onClick={() => setStep(s => s - 1)}>← Back</button>}
            {step < 3 && <button className="btn-primary" onClick={() => setStep(s => s + 1)}>Next →</button>}
            {step === 3 && <button className="btn-primary" onClick={() => onCreate(draft)}>✓ Publish to Facebook</button>}
          </div>
        </div>
      </div>
    </div>
  );
};

window.AIInbox = AIInbox;
window.AIChat = AIChat;
window.OrdersAttribution = OrdersAttribution;
window.CreativeLibrary = CreativeLibrary;
window.ClientReport = ClientReport;
window.CampaignBuilder = CampaignBuilder;
