/* educator-eventhost.jsx — live Event / Webinar hosting room with communication.
   Launched from an event's "Go live" button. Fullscreen portal (educator app). */

const HOST_POOL = [
  { name: "Aisha Karim", co: "Accenture" }, { name: "Mara de Vries", co: "VH Group" },
  { name: "Pieter Smit", co: "ING Bank" }, { name: "Lisa Janssen", co: "KPMG" },
  { name: "Tom van Berg", co: "Shell" }, { name: "Sophie Müller", co: "Deloitte" },
  { name: "Daan Visser", co: "Rabobank" }, { name: "Luca Bianchi", co: "Philips" },
  { name: "Noor El Amrani", co: "ASML" }, { name: "Jens Mulder", co: "Booking.com" },
  { name: "Femke Bos", co: "Ahold" }, { name: "Ravi Patel", co: "TomTom" }];

const HOST_CHAT_SEED = [
  { t: "Good morning everyone! Excited for today 👋" },
  { t: "Can everyone see the slides okay?" },
  { t: "Yes, all clear from here" },
  { t: "Will the recording be shared afterwards?" },
  { t: "Great example — that really clarifies it" },
  { t: "Quick q: does this apply to agile projects too?" },
  { t: "☕ taking a coffee, back in 2" },
  { t: "The case study is super relevant to our team" },
  { t: "+1 to Pieter's question" },
  { t: "Loving the interactive bits 🔥" }];

const HOST_QA_SEED = [
  { q: "How do we handle stakeholders who actively resist the project?", votes: 7, by: "Pieter Smit" },
  { q: "Is the power/interest grid in the exam?", votes: 4, by: "Lisa Janssen" },
  { q: "Can you recommend a tool for stakeholder mapping?", votes: 2, by: "Tom van Berg" }];

function initials(n) { return n.split(" ").map(w => w[0]).slice(0, 2).join("").toUpperCase(); }

function EventHostRoom({ ev, onClose }) {
  const base = (ev.participants && ev.participants.length ? ev.participants : HOST_POOL.slice(0, Math.min(ev.registered || 10, HOST_POOL.length)));
  const [elapsed, setElapsed] = useState(0);
  const [tab, setTab] = useState("chat");
  const [attendees, setAttendees] = useState(() => base.slice(0, 4).map((p, i) => ({ ...p, present: true, hand: false })));
  const [messages, setMessages] = useState([{ name: "You (host)", text: "Welcome everyone — we'll start in a moment!", me: true, time: "00:00" }]);
  const [chatInput, setChatInput] = useState("");
  const [questions, setQuestions] = useState(HOST_QA_SEED);
  const [qInput, setQInput] = useState("");
  const [mic, setMic] = useState(true);
  const [cam, setCam] = useState(true);
  const [sharing, setSharing] = useState(true);
  const [reactions, setReactions] = useState([]);
  const [aiBusy, setAiBusy] = useState(false);
  const [agendaIdx, setAgendaIdx] = useState(1);
  const chatRef = React.useRef(null);
  const tickRef = React.useRef(0);

  const AGENDA = [
    { t: "Welcome & introductions", d: "20 min" },
    { t: "Module: " + ev.course + " core concepts", d: "60 min" },
    { t: "Interactive: Kahoot quiz", d: "15 min" },
    { t: "☕ Break", d: "15 min" },
    { t: "Case study workshop", d: "45 min" },
    { t: "Wrap-up & Q&A", d: "20 min" }];

  function fmt(s) { return String(Math.floor(s / 60)).padStart(2, "0") + ":" + String(s % 60).padStart(2, "0"); }

  useEffect(() => { const t = setInterval(() => setElapsed(e => e + 1), 1000); return () => clearInterval(t); }, []);

  // simulate attendees joining + chat messages + hand raises
  useEffect(() => {
    const t = setInterval(() => {
      tickRef.current++;
      const tk = tickRef.current;
      // join more attendees early on
      setAttendees(prev => {
        if (prev.length < base.length && tk % 2 === 0) {
          const next = base[prev.length];
          if (next) { pushSys(next.name.split(" ")[0] + " joined"); return [...prev, { ...next, present: true, hand: false }]; }
        }
        // random hand raise toggle
        if (tk % 5 === 0 && prev.length) {
          const i = Math.floor(Math.random() * prev.length);
          return prev.map((a, ai) => ai === i ? { ...a, hand: !a.hand } : a);
        }
        return prev;
      });
      // incoming chat
      if (tk % 3 === 0) {
        setAttendees(cur => {
          const who = cur[Math.floor(Math.random() * cur.length)];
          const seed = HOST_CHAT_SEED[(tk / 3 | 0) % HOST_CHAT_SEED.length];
          if (who) setMessages(m => [...m, { name: who.name, text: seed.t, time: fmt(tickRef.current) }]);
          return cur;
        });
      }
    }, 3500);
    return () => clearInterval(t);
  }, []);

  useEffect(() => { if (chatRef.current) chatRef.current.scrollTop = chatRef.current.scrollHeight; }, [messages]);

  function pushSys(text) { setMessages(m => [...m, { sys: true, text, time: fmt(tickRef.current) }]); }
  function send() {
    if (!chatInput.trim()) return;
    setMessages(m => [...m, { name: "You (host)", text: chatInput.trim(), me: true, time: fmt(elapsed) }]);
    setChatInput("");
  }
  function askQ() { if (!qInput.trim()) return; setQuestions(q => [{ q: qInput.trim(), votes: 0, by: "You" }, ...q]); setQInput(""); }
  function vote(i) { setQuestions(q => q.map((x, xi) => xi === i ? { ...x, votes: x.votes + 1 } : x)); }
  function react(emoji) {
    const id = Date.now() + Math.random();
    setReactions(r => [...r, { id, emoji, left: 20 + Math.random() * 60 }]);
    setTimeout(() => setReactions(r => r.filter(x => x.id !== id)), 2600);
  }
  async function aiDraft() {
    const top = [...questions].sort((a, b) => b.votes - a.votes)[0];
    if (!top) return;
    if (!window.claude || !window.claude.complete) { setChatInput("Great question — let's cover that next."); return; }
    setAiBusy(true);
    try {
      const out = await window.claude.complete('You are a trainer hosting a "' + ev.course + '" session. A participant asked: "' + top.q + '". Draft a concise, friendly reply (max 2 sentences) the host can post in chat.');
      setChatInput((out || "").trim().replace(/^"|"$/g, ""));
      setTab("chat");
    } catch (e) { setChatInput("Great question — let's cover that next."); }
    setAiBusy(false);
  }

  const present = attendees.filter(a => a.present).length;
  const hands = attendees.filter(a => a.hand).length;

  const ctrlBtn = (label, on, set, dotOn = "#26d07c", dotOff = "#e0506a") => (
    <button onClick={() => set(v => !v)} style={{ display: "flex", alignItems: "center", gap: 8, padding: "9px 15px", borderRadius: 10, border: "1px solid #24364f", background: on ? "rgba(255,255,255,.06)" : "rgba(224,80,106,.14)", color: "#cdddf0", fontFamily: "var(--body)", fontSize: 13, fontWeight: 600, cursor: "pointer" }}>
      <span style={{ width: 8, height: 8, borderRadius: "50%", background: on ? dotOn : dotOff }} />{label}
    </button>
  );

  const TABS = [["chat", "Chat", messages.filter(m => !m.me && !m.sys).length], ["people", "People", present], ["qa", "Q&A", questions.length]];

  return ReactDOM.createPortal(
    <div style={{ position: "fixed", inset: 0, zIndex: 800, background: "#070f1c", display: "flex", flexDirection: "column", fontFamily: "var(--body)" }}>
      {/* TOP BAR */}
      <div style={{ height: 56, flex: "none", background: "#0a1322", borderBottom: "1px solid #1b2c46", display: "flex", alignItems: "center", gap: 14, padding: "0 18px" }}>
        <span title="Gesimuleerde live-sessie — publiek, chat, reacties en mic/camera zijn een demo" style={{ display: "inline-flex", alignItems: "center", gap: 7, background: "rgba(224,80,106,.16)", border: "1px solid rgba(224,80,106,.4)", color: "#ff6b81", fontSize: 12, fontWeight: 800, letterSpacing: ".06em", padding: "5px 12px", borderRadius: 999 }}>
          <span style={{ width: 8, height: 8, borderRadius: "50%", background: "#ff4d63", animation: "hostPulse 1.4s infinite" }} />LIVE · DEMO
        </span>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 700, fontSize: 14.5, color: "#eaf1fb", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{ev.title}</div>
          <div style={{ fontSize: 11.5, color: "#5f7aa0" }}>{ev.course} · {ev.trainer}</div>
        </div>
        <div style={{ flex: 1 }} />
        <div style={{ display: "flex", alignItems: "center", gap: 6, background: "rgba(255,255,255,.06)", borderRadius: 8, padding: "5px 12px" }}>
          <Icon name="clock" size={14} style={{ color: "#3bc1ce" }} /><span style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 14, color: "#3bc1ce" }}>{fmt(elapsed)}</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 6, background: "rgba(255,255,255,.06)", borderRadius: 8, padding: "5px 12px", color: "#cdddf0", fontSize: 13, fontWeight: 700 }}>
          <Icon name="users" size={14} style={{ color: "#94bfe6" }} />{present}
        </div>
        <button onClick={onClose} style={{ display: "flex", alignItems: "center", gap: 7, padding: "8px 16px", borderRadius: 9, background: "#e0506a", color: "#fff", border: "none", cursor: "pointer", fontFamily: "var(--body)", fontWeight: 700, fontSize: 13 }}>End event</button>
      </div>

      {/* BODY */}
      <div style={{ flex: 1, display: "flex", minHeight: 0 }}>
        {/* STAGE + agenda */}
        <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", padding: 18, gap: 14 }}>
          {/* stage */}
          <div style={{ flex: 1, position: "relative", borderRadius: 16, overflow: "hidden", background: "linear-gradient(150deg,#11233e,#0a1322)", border: "1px solid #1b2c46", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <div style={{ position: "absolute", inset: 0, backgroundImage: "radial-gradient(rgba(148,191,230,.10) 1.4px,transparent 1.5px)", backgroundSize: "26px 26px" }} />
            <div style={{ position: "relative", textAlign: "center", color: "#cdddf0" }}>
              <div style={{ width: 96, height: 96, borderRadius: "50%", background: "linear-gradient(135deg,#1281c4,#0a1322)", display: "grid", placeItems: "center", margin: "0 auto 16px", fontFamily: "var(--display)", fontWeight: 800, fontSize: 34, color: "#fff", border: "3px solid rgba(255,255,255,.12)" }}>{ev.ti}</div>
              <div style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 22, color: "#fff" }}>{ev.trainer}</div>
              <div style={{ fontSize: 13.5, color: "#7c97bd", marginTop: 4 }}>{sharing ? "🖥️ Sharing: " + AGENDA[agendaIdx].t : cam ? "Camera on" : "Presenting"}</div>
            </div>
            {/* live badges */}
            <div style={{ position: "absolute", top: 14, left: 14, display: "flex", gap: 8 }}>
              <span style={{ background: "rgba(7,15,28,.7)", border: "1px solid #24364f", borderRadius: 8, padding: "5px 11px", fontSize: 12, fontWeight: 700, color: "#cdddf0" }}>{sharing ? "Screen + speaker" : "Speaker view"}</span>
              {hands > 0 && <span style={{ background: "rgba(249,157,37,.18)", border: "1px solid rgba(249,157,37,.4)", borderRadius: 8, padding: "5px 11px", fontSize: 12, fontWeight: 700, color: "#f9b54f" }}>✋ {hands} raised</span>}
            </div>
            {/* floating reactions */}
            {reactions.map(r => <div key={r.id} style={{ position: "absolute", bottom: 20, left: r.left + "%", fontSize: 34, animation: "hostFloat 2.6s ease-out forwards", pointerEvents: "none" }}>{r.emoji}</div>)}
          </div>

          {/* control bar */}
          <div style={{ flex: "none", display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
            {ctrlBtn(mic ? "Mic on" : "Mic off", mic, setMic)}
            {ctrlBtn(cam ? "Camera on" : "Camera off", cam, setCam)}
            {ctrlBtn(sharing ? "Sharing" : "Share screen", sharing, setSharing, "#3bc1ce")}
            <div style={{ width: 1, height: 26, background: "#24364f" }} />
            {["👏", "👍", "❤️", "🎉", "😂"].map(e => <button key={e} onClick={() => react(e)} style={{ width: 38, height: 38, borderRadius: 10, border: "1px solid #24364f", background: "rgba(255,255,255,.05)", cursor: "pointer", fontSize: 17 }}>{e}</button>)}
            <div style={{ flex: 1 }} />
            <button onClick={() => { pushSys("Host launched a Kahoot quiz ⚡"); setAgendaIdx(2); }} style={{ display: "flex", alignItems: "center", gap: 7, padding: "9px 16px", borderRadius: 10, border: "none", background: "#f99d25", color: "#231f20", fontFamily: "var(--display)", fontWeight: 800, fontSize: 13, cursor: "pointer" }}><Icon name="bolt" size={14} />Launch Kahoot</button>
          </div>
        </div>

        {/* RIGHT RAIL — communication */}
        <div style={{ width: 320, flex: "none", background: "#0b1626", borderLeft: "1px solid #1b2c46", display: "flex", flexDirection: "column" }}>
          {/* agenda strip */}
          <div style={{ padding: "12px 14px", borderBottom: "1px solid #1b2c46" }}>
            <div style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: ".1em", textTransform: "uppercase", color: "#5f7aa0", marginBottom: 8 }}>Run of show</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              {AGENDA.map((a, i) => (
                <button key={i} onClick={() => setAgendaIdx(i)} style={{ display: "flex", alignItems: "center", gap: 9, padding: "6px 8px", borderRadius: 7, border: "none", background: i === agendaIdx ? "rgba(18,129,196,.18)" : "transparent", cursor: "pointer", textAlign: "left" }}>
                  <span style={{ width: 7, height: 7, borderRadius: "50%", flexShrink: 0, background: i < agendaIdx ? "#26d07c" : i === agendaIdx ? "#3bc1ce" : "#34465f" }} />
                  <span style={{ flex: 1, fontSize: 12.5, fontWeight: i === agendaIdx ? 700 : 500, color: i === agendaIdx ? "#eaf1fb" : "#8aa3c4", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.t}</span>
                  <span style={{ fontSize: 11, color: "#5f7aa0", flexShrink: 0 }}>{a.d}</span>
                </button>
              ))}
            </div>
          </div>

          {/* tabs */}
          <div style={{ display: "flex", borderBottom: "1px solid #1b2c46", flex: "none" }}>
            {TABS.map(([id, lbl, n]) => (
              <button key={id} onClick={() => setTab(id)} style={{ flex: 1, padding: "11px 0", fontSize: 12.5, fontWeight: 700, border: "none", cursor: "pointer", color: tab === id ? "#fff" : "#5f7aa0", background: tab === id ? "rgba(255,255,255,.05)" : "none", borderBottom: tab === id ? "2px solid #f99d25" : "2px solid transparent" }}>{lbl} <span style={{ fontSize: 11, opacity: .7 }}>{n}</span></button>
            ))}
          </div>

          {/* CHAT */}
          {tab === "chat" && (
            <div style={{ flex: 1, display: "flex", flexDirection: "column", minHeight: 0 }}>
              <div ref={chatRef} className="scroll" style={{ flex: 1, overflowY: "auto", padding: 12, display: "flex", flexDirection: "column", gap: 9 }}>
                {messages.map((m, i) => m.sys ? (
                  <div key={i} style={{ textAlign: "center", fontSize: 11.5, color: "#5f7aa0", padding: "2px 0" }}>{m.text}</div>
                ) : (
                  <div key={i} style={{ display: "flex", gap: 9, flexDirection: m.me ? "row-reverse" : "row" }}>
                    {!m.me && <div style={{ width: 28, height: 28, borderRadius: "50%", flexShrink: 0, background: "#1b3a5e", display: "grid", placeItems: "center", fontSize: 10.5, fontWeight: 800, color: "#94bfe6" }}>{initials(m.name)}</div>}
                    <div style={{ maxWidth: "78%" }}>
                      {!m.me && <div style={{ fontSize: 11, color: "#7c97bd", marginBottom: 2 }}>{m.name}</div>}
                      <div style={{ background: m.me ? "#1281c4" : "rgba(255,255,255,.06)", color: m.me ? "#fff" : "#dce8f7", borderRadius: 10, padding: "8px 11px", fontSize: 13, lineHeight: 1.45 }}>{m.text}</div>
                    </div>
                  </div>
                ))}
              </div>
              <div style={{ padding: 10, borderTop: "1px solid #1b2c46", display: "flex", gap: 7 }}>
                <input value={chatInput} onChange={e => setChatInput(e.target.value)} onKeyDown={e => e.key === "Enter" && send()} placeholder="Message everyone…" style={{ flex: 1, background: "rgba(255,255,255,.06)", border: "1px solid #24364f", borderRadius: 9, color: "#dce8f7", fontSize: 13, padding: "9px 11px", outline: "none", fontFamily: "var(--body)" }} />
                <button onClick={send} style={{ background: "#1281c4", color: "#fff", border: "none", borderRadius: 9, padding: "0 13px", cursor: "pointer" }}><Icon name="arrowR" size={15} /></button>
              </div>
            </div>
          )}

          {/* PEOPLE */}
          {tab === "people" && (
            <div className="scroll" style={{ flex: 1, overflowY: "auto", padding: 12, display: "flex", flexDirection: "column", gap: 6 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "8px 10px", borderRadius: 9, background: "rgba(18,129,196,.12)" }}>
                <div style={{ width: 30, height: 30, borderRadius: "50%", background: "#1281c4", display: "grid", placeItems: "center", fontSize: 11, fontWeight: 800, color: "#fff" }}>{ev.ti}</div>
                <div style={{ flex: 1 }}><div style={{ fontSize: 13, fontWeight: 700, color: "#eaf1fb" }}>{ev.trainer}</div><div style={{ fontSize: 11, color: "#7c97bd" }}>Host</div></div>
                <span style={{ fontSize: 14 }}>{mic ? "🎤" : "🔇"}</span>
              </div>
              {attendees.map((a, i) => (
                <div key={i} style={{ display: "flex", alignItems: "center", gap: 9, padding: "8px 10px", borderRadius: 9 }}>
                  <div style={{ width: 30, height: 30, borderRadius: "50%", background: "#1b3a5e", display: "grid", placeItems: "center", fontSize: 11, fontWeight: 800, color: "#94bfe6", position: "relative" }}>{initials(a.name)}<span style={{ position: "absolute", right: -1, bottom: -1, width: 9, height: 9, borderRadius: "50%", background: "#26d07c", border: "2px solid #0b1626" }} /></div>
                  <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 13, fontWeight: 600, color: "#dce8f7", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.name}</div><div style={{ fontSize: 11, color: "#5f7aa0" }}>{a.co}</div></div>
                  {a.hand && <span style={{ fontSize: 15 }}>✋</span>}
                </div>
              ))}
            </div>
          )}

          {/* Q&A */}
          {tab === "qa" && (
            <div style={{ flex: 1, display: "flex", flexDirection: "column", minHeight: 0 }}>
              <div className="scroll" style={{ flex: 1, overflowY: "auto", padding: 12, display: "flex", flexDirection: "column", gap: 9 }}>
                {[...questions].map((q, i) => ({ q, i })).sort((a, b) => b.q.votes - a.q.votes).map(({ q, i }) => (
                  <div key={i} style={{ display: "flex", gap: 10, background: "rgba(255,255,255,.05)", border: "1px solid #1b2c46", borderRadius: 10, padding: "10px 11px" }}>
                    <button onClick={() => vote(i)} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 1, background: "none", border: "none", cursor: "pointer", color: "#94bfe6", flexShrink: 0 }}>
                      <span style={{ fontSize: 12 }}>▲</span><span style={{ fontFamily: "var(--display)", fontWeight: 800, fontSize: 14, color: "#cdddf0" }}>{q.votes}</span>
                    </button>
                    <div style={{ minWidth: 0 }}><div style={{ fontSize: 13, color: "#dce8f7", lineHeight: 1.4 }}>{q.q}</div><div style={{ fontSize: 11, color: "#5f7aa0", marginTop: 3 }}>{q.by}</div></div>
                  </div>
                ))}
              </div>
              <div style={{ padding: 10, borderTop: "1px solid #1b2c46", display: "flex", flexDirection: "column", gap: 7 }}>
                <button onClick={aiDraft} disabled={aiBusy} style={{ fontSize: 12, fontWeight: 700, color: "#3bc1ce", background: "rgba(59,193,206,.1)", border: "1px solid rgba(59,193,206,.3)", borderRadius: 8, padding: "8px 0", cursor: aiBusy ? "default" : "pointer" }}>{aiBusy ? "✨ Drafting…" : "✨ AI: draft reply to top question"}</button>
                <div style={{ display: "flex", gap: 7 }}>
                  <input value={qInput} onChange={e => setQInput(e.target.value)} onKeyDown={e => e.key === "Enter" && askQ()} placeholder="Post a question…" style={{ flex: 1, background: "rgba(255,255,255,.06)", border: "1px solid #24364f", borderRadius: 9, color: "#dce8f7", fontSize: 13, padding: "9px 11px", outline: "none", fontFamily: "var(--body)" }} />
                  <button onClick={askQ} style={{ background: "#1281c4", color: "#fff", border: "none", borderRadius: 9, padding: "0 13px", cursor: "pointer" }}><Icon name="arrowR" size={15} /></button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      <style>{"@keyframes hostPulse{0%,100%{opacity:1}50%{opacity:.3}}@keyframes hostFloat{0%{transform:translateY(0) scale(.6);opacity:0}20%{opacity:1;transform:translateY(-20px) scale(1.1)}100%{transform:translateY(-240px) scale(1);opacity:0}}"}</style>
    </div>, document.body);
}

Object.assign(window, { EventHostRoom });
