/* AI Co-pilot panel — omnipresent, contextual to current screen */

const CopilotPanel = ({ position, currentScreen, currentEntity, onAction, onClose }) => {
  const [tab, setTab] = React.useState("suggestions");
  const [chatInput, setChatInput] = React.useState("");
  const [chatMessages, setChatMessages] = React.useState([
    { role: "ai", text: "สวัสดีครับ ผมเห็นวันนี้ ROAS รวมพอร์ตอยู่ที่ 2.93 — ดีกว่าเป้า 2.5 ครับ มีอะไรให้ช่วยมั้ย?" },
  ]);
  const [thinking, setThinking] = React.useState(false);

  const suggestions = React.useMemo(() => {
    const all = window.MOCK.aiInbox.filter(i => i.status === "PROPOSED");
    if (currentEntity?.type === "campaign") {
      return all.filter(i => i.entity === currentEntity.id || !i.entity).slice(0, 4);
    }
    return all.slice(0, 4);
  }, [currentEntity]);

  const handleSend = () => {
    if (!chatInput.trim()) return;
    const msg = chatInput;
    setChatMessages(m => [...m, { role: "user", text: msg }]);
    setChatInput("");
    setThinking(true);
    setTimeout(() => {
      let reply = "รับทราบครับ กำลังวิเคราะห์ข้อมูลให้";
      const low = msg.toLowerCase();
      if (low.includes("roas") || msg.includes("ผลงาน")) {
        reply = "พอร์ตนี้ ROAS เฉลี่ย 7 วัน = 2.93 · กำไรสุทธิ ฿58,200\n\n📈 Top: Silver Jewelry (5.40) · Lace Collection (4.18)\n📉 ต้องดูแล: Linen Wide-leg (1.18)\n\nต้องการให้ผมโยกงบจากแคมเปญ Linen ไปลงทุนใน Lace เพิ่มมั้ยครับ?";
      } else if (msg.includes("สร้าง") || low.includes("create")) {
        reply = "ผมแนะนำสร้างแคมเปญใหม่จาก winner: 'Reel · ลูกไม้บานสะพรั่ง' (ROAS 4.18)\n\n• Audience: Lookalike 1% ของลูกค้า 90 วัน\n• งบเริ่มต้น: ฿800/วัน\n• Placement: IG Reels + Stories (เหมือนตัวเดิม)\n\nให้ผมร่างให้ดูมั้ยครับ?";
      } else if (msg.includes("ปิด") || msg.includes("pause")) {
        reply = "เห็น Linen Wide-leg Pants ROAS 1.18 ติดต่อกัน 14 วันครับ — ถ้าปิดตอนนี้จะประหยัด ฿500/วัน และโยกได้ไปแคมเปญที่ ROAS > 3\n\nต้องการให้ผมปิดเลยมั้ยครับ?";
      }
      setChatMessages(m => [...m, { role: "ai", text: reply }]);
      setThinking(false);
    }, 1200);
  };

  const containerStyle = position === "right"
    ? { position: "fixed", top: 0, right: 0, bottom: 0, width: 380, borderLeft: "1px solid var(--border)", zIndex: 50 }
    : position === "bottom"
    ? { position: "fixed", left: 240, right: 0, bottom: 0, height: 320, borderTop: "1px solid var(--border)", zIndex: 50 }
    : { position: "fixed", right: 24, bottom: 24, width: 420, height: 560, borderRadius: 16, boxShadow: "0 20px 60px rgba(15, 23, 42, 0.18)", border: "1px solid var(--border)", zIndex: 50 };

  return (
    <div className="copilot" style={{ ...containerStyle, background: "var(--panel)", display: "flex", flexDirection: "column", overflow: "hidden" }}>
      <div className="copilot-head">
        <div className="copilot-brand">
          <div className="copilot-orb">
            <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>
          <span style={{ fontWeight: 600, fontSize: 13 }}>Wandee AI</span>
          <span className="dot-status" style={{ background: "var(--success)" }}></span>
          <span style={{ fontSize: 11, color: "var(--ink-faint)" }}>วิเคราะห์ ณ 14:32</span>
        </div>
        <button className="icon-btn" onClick={onClose} aria-label="close">
          <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="copilot-tabs">
        {[
          { k: "suggestions", l: "แนะนำ", n: suggestions.length },
          { k: "chat", l: "แชท", n: null },
          { k: "actions", l: "ประวัติ", n: null },
        ].map(t => (
          <button key={t.k} className={`tab ${tab === t.k ? "active" : ""}`} onClick={() => setTab(t.k)}>
            {t.l}
            {t.n != null && <span className="tab-badge">{t.n}</span>}
          </button>
        ))}
      </div>

      <div className="copilot-body" style={{ flex: 1, overflowY: "auto" }}>
        {tab === "suggestions" && (
          <div style={{ padding: "12px 16px" }}>
            {currentEntity && (
              <div className="context-chip">
                <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="12" r="6"/></svg>
                กำลังดู: {currentEntity.name}
              </div>
            )}
            {suggestions.length === 0 && (
              <div style={{ padding: 24, textAlign: "center", color: "var(--ink-faint)", fontSize: 13 }}>
                ทุกอย่างดูดี ไม่มีคำแนะนำเร่งด่วนครับ
              </div>
            )}
            {suggestions.map(s => (
              <div key={s.id} className={`ai-card severity-${s.severity}`}>
                <div className="ai-card-head">
                  <span className={`ai-pill kind-${s.kind.toLowerCase()}`}>{s.kind}</span>
                  <span style={{ fontSize: 10, color: "var(--ink-faint)" }}>{s.createdAt}</span>
                </div>
                <div className="ai-card-title">{s.title}</div>
                <div className="ai-card-body">{s.body}</div>
                <div className="ai-card-actions">
                  <button className="btn-primary-sm" onClick={() => onAction(s, "apply")}>
                    {s.proposedAction.type === "BUDGET_INCREASE" && `เพิ่มงบเป็น ฿${s.proposedAction.to}`}
                    {s.proposedAction.type === "CREATIVE_REFRESH" && "เปลี่ยน creative"}
                    {s.proposedAction.type === "PAUSE_AND_REALLOCATE" && "หยุด + โยกงบ"}
                    {s.proposedAction.type === "CREATE_AUDIENCE" && "สร้าง audience"}
                    {s.proposedAction.type === "BUDGET_CAP_REVIEW" && "ตรวจสอบงบ"}
                  </button>
                  <button className="btn-ghost-sm" onClick={() => onAction(s, "dismiss")}>ผ่าน</button>
                  <button className="btn-ghost-sm" onClick={() => onAction(s, "snooze")}>เลื่อน</button>
                </div>
                <div className="ai-confidence">
                  <span>ความมั่นใจ {Math.round(s.confidence * 100)}%</span>
                  <div className="ai-conf-bar"><div style={{ width: `${s.confidence * 100}%` }}></div></div>
                </div>
              </div>
            ))}
          </div>
        )}

        {tab === "chat" && (
          <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
            <div style={{ flex: 1, overflowY: "auto", padding: "12px 16px" }}>
              {chatMessages.map((m, i) => (
                <div key={i} className={`chat-msg ${m.role}`}>
                  {m.role === "ai" && (
                    <div className="chat-avatar">
                      <svg viewBox="0 0 24 24" width="11" height="11"><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 ${m.role}`}>{m.text}</div>
                </div>
              ))}
              {thinking && (
                <div className="chat-msg ai">
                  <div className="chat-avatar">
                    <svg viewBox="0 0 24 24" width="11" height="11"><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"><span></span><span></span><span></span></div>
                </div>
              )}
            </div>
            <div className="chat-input-row">
              <input
                value={chatInput}
                onChange={(e) => setChatInput(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && handleSend()}
                placeholder="ถามอะไรก็ได้ เช่น 'แคมเปญไหน ROAS แย่ที่สุด'"
              />
              <button className="btn-icon-primary" onClick={handleSend} aria-label="send">
                <svg width="14" height="14" 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 className="chat-quick">
              {["สรุปผลวันนี้", "แคมเปญไหนควรปิด", "ร่างแคมเปญใหม่", "เทียบ ROAS 7 วัน vs ก่อนหน้า"].map(q => (
                <button key={q} className="quick-chip" onClick={() => { setChatInput(q); setTimeout(handleSend, 50); }}>{q}</button>
              ))}
            </div>
          </div>
        )}

        {tab === "actions" && (
          <div style={{ padding: "12px 16px" }}>
            <div className="action-log-item">
              <span className="action-time">14:18</span>
              <span className="action-text"><b>AI</b> ปรับงบ Songkran Sale +18% (฿1,500 → ฿1,770)</span>
            </div>
            <div className="action-log-item">
              <span className="action-time">12:42</span>
              <span className="action-text"><b>AI</b> ส่ง CAPI Purchase event 14 รายการ</span>
            </div>
            <div className="action-log-item">
              <span className="action-time">เมื่อวาน</span>
              <span className="action-text"><b>คุณ</b> approve "Refresh creative · ผ้าฝ้าย"</span>
            </div>
            <div className="action-log-item">
              <span className="action-time">3 วันก่อน</span>
              <span className="action-text"><b>AI</b> ปิด Boho Dress · IG Reels Test (ROAS 0.84)</span>
            </div>
            <div className="action-log-item">
              <span className="action-time">4 วันก่อน</span>
              <span className="action-text"><b>AI</b> duplicate ad set as3 → as3-copy ทดสอบ audience ใหม่</span>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

window.CopilotPanel = CopilotPanel;
