function addStyle(css) {
  const s = document.createElement("style");
  s.textContent = css;
  document.head.appendChild(s);
}
addStyle(`
#chatContainer {
  position:fixed;bottom:20px;right:20px;width:200px;height:20px;
  display:flex;align-items:center;background:#fff;
  border:1px solid #ccc;box-shadow:0 2px 8px rgba(0,0,0,0.15);
  resize:both;overflow:hidden;border-radius:6px;z-index:999;
}
#chatContainer #dragHandle {
  width:20px;height:20px;color:#fff;
  display:flex;align-items:center;justify-content:center;
  cursor:move;font-size:12px;margin-left:4px;
}
#dragHandle{

  cursor: move;

}
#chatContainer #chatInput {
  flex:1;padding:4px;font-size:14px;border:none;outline:none;
}
#chatContainer #chatBtn {
  padding:4px 4px;margin-right:4px;background:#007bff;
  color:#fff;border:none;cursor:pointer;font-size:14px;
}
.panel {
  position:fixed;min-width:200px;top:40%;left:40%;
  background:#fff;border:1px solid #ccc;padding:2px;
  border-radius:8px;box-shadow:0 4px 12px rgba(0,0,0,0.2);
  animation:fadein .3s ease;z-index:1000;
}
@keyframes fadein {
  from {opacity:0;transform:scale(0.8);}
  to {opacity:1;transform:scale(1);}
}
.panel.closing {
  opacity:0;transform:scale(0.8);transition:all 0.3s ease;
}
.panel-footer {text-align:right;margin-top:8px;}
.panel-footer button {
  width:24px;height:24px;background:#d33;border:none;
  border-radius:50%;cursor:pointer;
}
#chatBtn{
border-radius:40%;
}
`);
function XcreatePanel({ id, body, footerButton = [""] }) {
  const old = document.getElementById(id);
  if (old) old.remove();
  const p = document.createElement("div");
  p.className = "panel";
  p.id = id;
  p.innerHTML = `
    <div>${body}</div>
    <div class="panel-footer">
      ${footerButton.map((b) => `<button onclick="closePanel('${id}')">${b}</button>`).join("")}
    </div>`;
  document.body.appendChild(p);
}
function closePanel(id) {
  const el = document.getElementById(id);
  if (!el) return;
  el.classList.add("closing");
  setTimeout(() => el.remove(), 300);
}
document.addEventListener("keydown", (e) => {
  if (e.key === "Escape") {
    const panels = document.querySelectorAll(".panel");
    if (panels.length) {
      const top = panels[panels.length - 1];
      top.classList.add("closing");
      setTimeout(() => top.remove(), 300);
    }
  }
});
function createChatBox() {
  if (document.getElementById("chatContainer")) return;
  const box = document.createElement("div");
  box.id = "chatContainer";
  box.innerHTML = `
    <div id="dragHandle">🟢</div>
    <input id="chatInput" placeholder="..." />

  `;
  document.body.appendChild(box);

  let drag = false,
    offset = [0, 0];
  box.querySelector("#dragHandle").onmousedown = (e) => {
    drag = true;
    offset = [e.clientX - box.offsetLeft, e.clientY - box.offsetTop];
    document.onmousemove = (e) => {
      if (drag) {
        box.style.left = e.clientX - offset[0] + "px";
        box.style.top = e.clientY - offset[1] + "px";
        box.style.right = "auto";
        box.style.bottom = "auto";
      }
    };
    document.onmouseup = () => (drag = false);
  };

  box.querySelector("#chatInput").onkeydown = (e) => {
    if (e.key === "Enter") chat();
  };
}
const dialogTree = {
  start: {
    text: "How are you?",
    buttons: [
      { label: "ok", goto: "ok_reply" },
      { label: "no", goto: "no_reply" },
    ],
  },
  ok_reply: {
    text: "Great to hear! 😊",
  },
  no_reply: {
    text: "Oh no, what happened?",
    buttons: [
      { label: "sick", goto: "sick_reply" },
      { label: "busy", goto: "busy_reply" },
    ],
  },
  sick_reply: {
    text: "🤒 Hope you feel better soon!",
  },
  busy_reply: {
    text: "Busy with what?",
    buttons: [
      { label: "work", goto: "busy_work" },
      { label: "family", goto: "busy_family" },
    ],
  },
  busy_work: {
    text: "💼 Keep grinding!",
  },
  busy_family: {
    text: "👨‍👩‍👧‍👦 Family is important.",
  },
};

const botRules = [
  {
    keywords: ["time"],
    reply: "🕒 Time now is <b>{{time}}</b>",
  },
  {
    keywords: ["date"],
    reply: "📅 Today is <b>{{date}}</b>",
  },
  {
    keywords: ["who", "your name"],
    reply: "🤖 I'm a simple bot in vanilla JavaScript.",
  },
  {
    keywords: ["help"],
    reply: "Try typing: <br>• what time<br>• what date<br>• who are you",
  },
  {
    keywords: ["dialog", "how are you"],
    dialog: "start",
  },
];

function getBotReply(input) {
  const val = input.toLowerCase();
  for (const rule of botRules) {
    if (rule.keywords.some((k) => val.includes(k))) {
      if (rule.dialog) {
        showDialog(rule.dialog);
        return null; // Don't return a panel reply
      }
      return rule.reply
        .replace("{{time}}", new Date().toLocaleTimeString())
        .replace("{{date}}", new Date().toLocaleDateString());
    }
  }
  return "🤖 I don't understand.";
}
function showDialog(key) {
  const node = dialogTree[key];
  if (!node) return;

  const id = "panel_" + Date.now();
  const buttonsHTML = (node.buttons || [])
    .map((b) => {
      return `<button onclick="showDialog('${b.goto}')">${b.label}</button>`;
    })
    .join(" ");
  createPanel("panel_d", "T1", "btt", 300, 200, {
    onlyBody: true,
    radius: true,
    bodyContent: buttonsHTML,
  });
}

function chat() {
  const input = document.getElementById("chatInput");
  const val = input.value.trim();
  input.value = "";
  if (!val) return;

  const reply = getBotReply(val);
  //createPanel({ id: "panel_" + Date.now(), body: reply ,});
  createPanel("panel_" + Date.now(), "T1", "btt", 300, 200, {
    onlyBody: true,
    radius: true,
    bodyContent: reply,
  });
}
