/* educator-events.jsx — Event Management (classroom · virtual webinars · hybrid) */

/* ── HOSTING PLATFORMS (for virtual / hybrid events) ── */
const PLATFORMS = {
  vanharen: { label: "Van Haren Live", short: "VH Live", color: "#1281c4", mono: "V", built: true,
    desc: "Built-in webinar room — chat, Q&A, polls & recording, no downloads." },
  zoom: { label: "Zoom Webinar", short: "Zoom", color: "#2D8CFF", mono: "Z",
    desc: "Connect your Zoom account. Up to 1,000 attendees." },
  teams: { label: "Microsoft Teams", short: "Teams", color: "#5059C9", mono: "T",
    desc: "Host as a Teams Live Event via your Microsoft 365 tenant." },
  meet: { label: "Google Meet", short: "Meet", color: "#1A8E5F", mono: "M",
    desc: "Generate a Google Meet link from Workspace." },
  webex: { label: "Cisco Webex", short: "Webex", color: "#0B7E8F", mono: "W",
    desc: "Webex Events with registration sync." }
};

function PlatformChip({ id, size = 22 }) {
  const p = PLATFORMS[id];if (!p) return null;
  const r = Math.round(size * 0.28);
  return <span style={{ width: size, height: size, borderRadius: r, background: p.color, color: "#fff", display: "grid", placeItems: "center", fontFamily: "var(--display)", fontWeight: 800, fontSize: size * 0.5, flexShrink: 0 }}>{p.mono}</span>;
}

const MODE_META = {
  physical: { label: "In-person", icon: "pin", color: "#0f6ca6" },
  virtual: { label: "Online webinar", icon: "video", color: "#7c3aed" },
  hybrid: { label: "Hybrid", icon: "globe", color: "#00838f" }
};

function ModeChip({ mode, platform }) {
  const m = MODE_META[mode] || MODE_META.physical;
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11.5, fontWeight: 700, padding: "3px 9px 3px 7px", borderRadius: 999, background: m.color + "14", color: m.color }}>
      <Icon name={m.icon} size={12.5} />{m.label}{mode !== "physical" && platform ? " · " + PLATFORMS[platform].short : ""}
    </span>);
}

function CopyBtn({ text, label }) {
  const [done, setDone] = useState(false);
  function copy(e) {
    e.stopPropagation();
    try {navigator.clipboard && navigator.clipboard.writeText(text);} catch (err) {}
    setDone(true);setTimeout(() => setDone(false), 1400);
  }
  return (
    <button onClick={copy} className="btn btn-ghost btn-sm" style={{ padding: label ? "6px 11px" : "6px 8px", flexShrink: 0, gap: 6, color: done ? "#2e7d32" : "var(--ink2)" }}>
      <Icon name={done ? "check" : "copy"} size={13} />{label ? done ? "Copied" : label : null}
    </button>);
}

/* ── DATA ── */
const PHYS_EVENTS = [
{ id: 1, title: "Pizza & Projects: Lessons from Failed Projects", type: "Pizza session", colorHex: "#f99d25",
  mode: "physical", price: "Free",
  regSlug: "pizza-projects-june", regPublished: true,
  start: "9 Jun", end: "9 Jun 2026", juneDays: [9], days: 1, time: "17:30–20:00",
  venue: "Van Haren Training Centre", city: "Amersfoort", room: "The Loft",
  capacity: 40, registered: 28, trainer: "Jonas Bakker", ti: "JB",
  status: "confirmed", lang: "Dutch",
  blurb: "An informal after-work session where three project leads share what went wrong on real projects — and what they'd do differently. Pizza and drinks on us.",
  materials: ["Slide highlights (after)"],
  catering: "Pizza, beer & soft drinks included",
  notes: "Come hungry. Doors at 17:15, first slice at 17:45.",
  participants: [
  { name: "Aisha Karim", co: "Accenture", email: "a.karim@accenture.com", status: "confirmed", present: null },
  { name: "Mara de Vries", co: "VH Group", email: "m.devries@vhg.nl", status: "confirmed", present: null },
  { name: "Pieter Smit", co: "ING Bank", email: "p.smit@ing.nl", status: "confirmed", present: null },
  { name: "Lisa Janssen", co: "KPMG", email: "l.janssen@kpmg.nl", status: "confirmed", present: null },
  { name: "Tom van Berg", co: "Shell", email: "t.vanberg@shell.com", status: "pending", present: null },
  { name: "Sophie Müller", co: "Deloitte", email: "s.muller@deloitte.com", status: "waitlist", present: null }]
},
{ id: 2, title: "Leadership Masterclass: Leading Without Authority", type: "Masterclass", colorHex: "#1281c4",
  start: "16 Jun", end: "16 Jun 2026", juneDays: [16], days: 1, time: "09:30–16:30",
  mode: "physical", price: "€245",
  regSlug: "leadership-masterclass-june", regPublished: true,
  venue: "NH Amsterdam Centre", city: "Amsterdam", room: "Conf. Room Rembrandt",
  capacity: 24, registered: 19, trainer: "Eva Groot", ti: "EG",
  status: "confirmed", lang: "English",
  blurb: "A one-day masterclass for project professionals on influencing stakeholders and leading teams you don't formally manage.",
  materials: ["Workbook", "Influence canvas", "Reading list"],
  catering: "Lunch & refreshments included",
  notes: "Bring a current stakeholder challenge to work on during the afternoon.",
  participants: [] },
{ id: 6, title: "Agile Stakeholder Management", type: "Webinar", colorHex: "#7c3aed",
  mode: "virtual", platform: "vanharen", joinUrl: "live.vanharen.net/r/agile-stakeholders",
  price: "€39", regSlug: "agile-stakeholder-management", regPublished: true,
  start: "11 Jun", end: "11 Jun 2026", juneDays: [11], days: 1, time: "13:00–14:30",
  venue: "Online", city: "Van Haren Live", room: "Webinar room",
  capacity: 250, registered: 168, trainer: "Eva Groot", ti: "EG",
  status: "confirmed", lang: "English",
  blurb: "A live 90-minute interactive webinar on mapping and managing stakeholders in agile projects — with breakout polls and a downloadable toolkit.",
  materials: ["Stakeholder mapping toolkit (PDF)", "Slide deck", "Recording (after)"],
  catering: "—",
  notes: "Joining link is sent automatically on registration and again 1 hour before start. Session is recorded.",
  participants: [] },
{ id: 3, title: "Women in Project Management — Meetup", type: "Meetup", colorHex: "#3bc1ce",
  mode: "physical", price: "Free",
  regSlug: "women-in-pm-meetup-june", regPublished: false,
  start: "24 Jun", end: "24 Jun 2026", juneDays: [24], days: 1, time: "18:00–20:30",
  venue: "Van Haren Training Centre", city: "Amersfoort", room: "Training Room B",
  capacity: 30, registered: 17, trainer: "Pieter van Dam", ti: "PD",
  status: "pending", lang: "Dutch",
  blurb: "A relaxed evening meetup connecting women working in and around project delivery — short talks, then open networking.",
  materials: [],
  catering: "Drinks & snacks",
  notes: "Minimum 12 attendees to confirm. Currently 17 registered.",
  participants: [] },
{ id: 7, title: "ITIL 4: What's New in 2026", type: "Webinar", colorHex: "#2D8CFF",
  mode: "virtual", platform: "zoom", joinUrl: "vanharen-group.zoom.us/w/8842019",
  price: "Free", regSlug: "itil4-whats-new-2026", regPublished: true,
  start: "18 Jun", end: "18 Jun 2026", juneDays: [18], days: 1, time: "11:00–12:00",
  venue: "Online", city: "Zoom Webinar", room: "—",
  capacity: 500, registered: 312, trainer: "Maria Santos", ti: "MS",
  status: "confirmed", lang: "English",
  blurb: "A free 60-minute lunch webinar walking through the latest ITIL 4 updates and what they mean for your service teams.",
  materials: ["Slides", "Recording (after)"],
  catering: "—",
  notes: "Hosted on Zoom Webinar. Registrants receive a unique join link by email.",
  participants: [] },
{ id: 4, title: "AI in Project Delivery — Hackathon", type: "Hackathon", colorHex: "#2e7d32",
  mode: "hybrid", platform: "teams", joinUrl: "teams.microsoft.com/l/meetup/ai-hackathon",
  price: "€95", regSlug: "ai-project-delivery-hackathon", regPublished: true,
  start: "1 Jul", end: "1 Jul 2026", juneDays: [], days: 1, time: "09:00–18:00",
  venue: "Seats2meet Utrecht", city: "Utrecht + online", room: "Innovation Hall",
  capacity: 60, registered: 54, trainer: "Maria Santos", ti: "MS",
  status: "confirmed", lang: "English",
  blurb: "A one-day hackathon where mixed teams prototype AI tools for everyday project work. Join in the room or online; demos and prizes at 17:00.",
  materials: ["Starter repo", "API credits", "Judging rubric"],
  catering: "Lunch, snacks & drinks included",
  notes: "Bring a laptop. Teams formed on the day; solo sign-ups welcome.",
  participants: [] },
{ id: 5, title: "Summer Drinks & Networking", type: "Drinks & networking", colorHex: "#e65100",
  mode: "physical", price: "Free",
  regSlug: "summer-drinks-july", regPublished: false,
  start: "8 Jul", end: "8 Jul 2026", juneDays: [], days: 1, time: "16:30–19:00",
  venue: "Spaces Amsterdam Zuid", city: "Amsterdam", room: "Rooftop terrace",
  capacity: 80, registered: 23, trainer: "Jonas Bakker", ti: "JB",
  status: "draft", lang: "English",
  blurb: "Wind down the season with the Van Haren community — drinks, bites and good company on the rooftop. Bring a colleague.",
  materials: [],
  catering: "Drinks & finger food",
  notes: "Not yet published. Registration opens 1 June 2026.",
  participants: [] }];


const EV_STATUS = {
  confirmed: { label: "Confirmed", bg: "#e8f5e9", color: "#2e7d32" },
  pending: { label: "Pending", bg: "#fff3e0", color: "#e65100" },
  full: { label: "Full", bg: "#e3f2fd", color: "#1565c0" },
  draft: { label: "Draft", bg: "#f5f5f5", color: "#616161" },
  cancelled: { label: "Cancelled", bg: "#ffebee", color: "#c62828" }
};

const VENUES = [
"Van Haren Training Centre, Amersfoort",
"NH Amsterdam Centre, Amsterdam",
"Seats2meet Utrecht, Utrecht",
"Spaces Amsterdam Zuid, Amsterdam"];


/* ── STATUS BADGE ── */
function EvBadge({ status }) {
  const s = EV_STATUS[status] || EV_STATUS.draft;
  return <span style={{ display: "inline-flex", alignItems: "center", fontSize: 11.5, fontWeight: 700, padding: "3px 9px", borderRadius: 999, background: s.bg, color: s.color }}>{s.label}</span>;
}

/* ── EVENT CARD ── */
function EventCard({ ev, selected, onSelect }) {
  const pct = Math.round(ev.registered / ev.capacity * 100);
  const barColor = pct >= 95 ? "#c62828" : pct >= 75 ? "#e65100" : "#2e7d32";
  return (
    <div onClick={() => onSelect(ev)} className="card" style={{ cursor: "pointer", borderLeft: `4px solid ${ev.colorHex}`, padding: 0, overflow: "hidden", transition: "box-shadow .15s, transform .15s", boxShadow: selected ? "0 0 0 2px " + ev.colorHex + ", 0 8px 24px rgba(0,0,0,.1)" : undefined, transform: selected ? "translateY(-1px)" : undefined }}>
      <div style={{ padding: "16px 18px 14px" }}>
        <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 10, marginBottom: 10 }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".1em", color: ev.colorHex, marginBottom: 4 }}>{ev.type}</div>
            <h3 style={{ fontSize: 16, fontWeight: 700, color: "var(--ink)", lineHeight: 1.2 }}>{ev.title}</h3>
          </div>
          <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 6, flexShrink: 0 }}>
            <EvBadge status={ev.status} />
            <ModeChip mode={ev.mode} platform={ev.platform} />
          </div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "var(--ink2)" }}>
            <Icon name="calendar" size={14} style={{ color: "var(--ink3)" }} />
            <span>{ev.start} – {ev.end} &nbsp;·&nbsp; {ev.days} day{ev.days > 1 ? "s" : ""} &nbsp;·&nbsp; {ev.time}</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "var(--ink2)" }}>
            <Icon name={ev.mode === "physical" ? "pin" : "video"} size={14} style={{ color: "var(--ink3)" }} />
            <span>{ev.mode === "virtual" ? PLATFORMS[ev.platform].label : ev.venue + ", " + ev.city + (ev.room && ev.room !== "—" ? "  ·  " + ev.room : "")}</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "var(--ink2)" }}>
            <Icon name="users" size={14} style={{ color: "var(--ink3)" }} />
            <div style={{ width: 26, height: 26, borderRadius: 7, background: ev.colorHex, display: "grid", placeItems: "center", color: "#fff", fontFamily: "var(--display)", fontWeight: 700, fontSize: 10, flexShrink: 0 }}>{ev.ti}</div>
            <span>{ev.trainer}</span>
            <span style={{ marginLeft: "auto", fontSize: 12, fontWeight: 700, color: pct >= 100 ? "#c62828" : pct >= 80 ? "#e65100" : "var(--ink2)" }}>{ev.registered}/{ev.capacity} {ev.mode === "physical" ? "spots" : "registered"}</span>
          </div>
        </div>
        <div style={{ marginTop: 12 }}>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11.5, fontWeight: 600, color: "var(--ink3)", marginBottom: 5 }}>
            <span>{ev.mode === "physical" ? "Capacity" : "Registrations"}</span><span>{pct}%</span>
          </div>
          <div className="bar"><i style={{ width: pct + "%", background: barColor }} /></div>
        </div>
      </div>
    </div>);

}

/* ── CALENDAR VIEW ── */
function EventCalendar({ events, onSelect }) {
  const days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
  const cells = [];
  for (let d = 1; d <= 30; d++) cells.push(d); // June 2026 starts Mon
  return (
    <div className="card" style={{ padding: 20 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 18 }}>
        <h3 style={{ fontSize: 17, fontWeight: 700 }}>June 2026</h3>
        <div style={{ display: "flex", gap: 8 }}>
          <span className="tag" style={{ opacity:.45, cursor:"not-allowed" }} title="Binnenkort">← May</span>
          <span className="tag" style={{ opacity:.45, cursor:"not-allowed" }} title="Binnenkort">Jul →</span>
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(7,1fr)", gap: 3 }}>
        {days.map((d) => <div key={d} style={{ textAlign: "center", fontSize: 11, fontWeight: 700, color: "var(--ink3)", padding: "4px 0", letterSpacing: ".04em" }}>{d}</div>)}
        {cells.map((day) => {
          const dayEvents = events.filter((ev) => ev.juneDays && ev.juneDays.includes(day));
          const isToday = day === 6; // simulated "today"
          return (
            <div key={day} style={{ minHeight: 60, borderRadius: 8, background: isToday ? "var(--vh-blue-50)" : "#fff", border: "1px solid var(--line)", padding: "4px 5px" }}>
              <div style={{ fontSize: 11.5, fontWeight: isToday ? 800 : 500, color: isToday ? "var(--blue)" : "var(--ink2)", marginBottom: 3 }}>{day}</div>
              {dayEvents.filter((e, i) => i === 0 || dayEvents[i - 1].id !== e.id).map((ev, i) =>
              <div key={i} onClick={() => onSelect(ev)} style={{ fontSize: 10, fontWeight: 700, color: "#fff", background: ev.colorHex, borderRadius: 4, padding: "2px 5px", marginBottom: 2, cursor: "pointer", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                  {ev.title.split(" ")[0]}
                </div>
              )}
            </div>);

        })}
      </div>
      <div style={{ marginTop: 16, display: "flex", flexWrap: "wrap", gap: 10 }}>
        {events.filter((ev) => ev.juneDays && ev.juneDays.length > 0).map((ev) =>
        <div key={ev.id} style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12 }}>
            <div style={{ width: 10, height: 10, borderRadius: 3, background: ev.colorHex, flexShrink: 0 }} />
            <span style={{ color: "var(--ink2)" }}>{ev.title}</span>
          </div>
        )}
      </div>
    </div>);

}

/* ── PARTICIPANTS TAB ── */
function ParticipantsTab({ ev }) {
  const [ps, setPs] = useState(ev.participants || []);
  function togglePresent(i, val) {
    setPs((prev) => {const n = [...prev];n[i] = { ...n[i], present: val };return n;});
  }
  if (!ps.length) return (
    <div style={{ textAlign: "center", padding: "40px 20px", color: "var(--ink3)" }}>
      <Icon name="users" size={32} style={{ margin: "0 auto 10px", display: "block", opacity: .3 }} />
      <p style={{ fontSize: 14 }}>No participants yet. Share the registration link to invite learners.</p>
      <button className="btn btn-pri btn-sm" style={{ marginTop: 14, opacity:.5, cursor:"not-allowed" }} disabled title="Binnenkort">Copy registration link</button>
    </div>);

  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
        <div style={{ fontSize: 13, color: "var(--ink2)" }}><b>{ps.filter((p) => p.status === "confirmed").length}</b> confirmed · <b>{ps.filter((p) => p.status === "waitlist").length}</b> waitlist</div>
        <button className="btn btn-pri btn-sm" disabled title="Binnenkort" style={{ opacity:.5, cursor:"not-allowed" }}><Icon name="share" size={13} />Invite</button>
      </div>
      <table className="tbl" style={{ width: "100%" }}>
        <thead><tr><th>Participant</th><th>Status</th><th style={{ textAlign: "right" }}>Attendance</th></tr></thead>
        <tbody>
          {ps.map((p, i) =>
          <tr key={i}>
              <td>
                <div style={{ fontWeight: 600, fontSize: 13.5, color: "var(--ink)" }}>{p.name}</div>
                <div style={{ fontSize: 12, color: "var(--ink3)" }}>{p.co} · {p.email}</div>
              </td>
              <td>
                <span style={{ fontSize: 11.5, fontWeight: 700, padding: "2px 8px", borderRadius: 999,
                background: p.status === "confirmed" ? "#e8f5e9" : p.status === "waitlist" ? "#fff3e0" : "#f5f5f5",
                color: p.status === "confirmed" ? "#2e7d32" : p.status === "waitlist" ? "#e65100" : "#616161" }}>
                  {p.status}
                </span>
              </td>
              <td style={{ textAlign: "right" }}>
                {p.present === null ?
              <div style={{ display: "flex", justifyContent: "flex-end", gap: 6 }}>
                    <button onClick={() => togglePresent(i, true)} className="btn btn-sm" style={{ fontSize: 12, background: "#e8f5e9", color: "#2e7d32", padding: "5px 10px" }}>✓ Present</button>
                    <button onClick={() => togglePresent(i, false)} className="btn btn-sm" style={{ fontSize: 12, background: "#ffebee", color: "#c62828", padding: "5px 10px" }}>✗ Absent</button>
                  </div> :

              <span style={{ fontSize: 13, fontWeight: 700, color: p.present ? "#2e7d32" : "#c62828", cursor: "pointer" }} onClick={() => togglePresent(i, null)}>
                    {p.present ? "✓ Present" : "✗ Absent"}
                  </span>
              }
              </td>
            </tr>
          )}
        </tbody>
      </table>
    </div>);

}

/* ── LOGISTICS TAB ── */
function LogisticsTab({ ev }) {
  const [checked, setChecked] = useState([]);
  function toggle(m) {setChecked((c) => c.includes(m) ? c.filter((x) => x !== m) : [...c, m]);}
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
      <div className="card" style={{ padding: 18 }}>
        <div className="eyebrow" style={{ marginBottom: 12 }}>Materials checklist</div>
        {ev.materials.map((m, i) =>
        <div key={i} onClick={() => toggle(m)} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 0", borderBottom: "1px solid var(--line-2)", cursor: "pointer" }}>
            <div style={{ width: 20, height: 20, borderRadius: 6, border: `2px solid ${checked.includes(m) ? "#1281c4" : "var(--line)"}`, background: checked.includes(m) ? "#1281c4" : "transparent", display: "grid", placeItems: "center", flexShrink: 0, transition: "all .12s" }}>
              {checked.includes(m) && <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3.5" strokeLinecap="round"><path d="M5 13l4 4L19 7" /></svg>}
            </div>
            <span style={{ fontSize: 14, color: checked.includes(m) ? "var(--ink3)" : "var(--ink)", textDecoration: checked.includes(m) ? "line-through" : "none" }}>{m}</span>
          </div>
        )}
      </div>
      <div className="card" style={{ padding: 18 }}>
        <div className="eyebrow" style={{ marginBottom: 10 }}>Catering</div>
        <div style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 14, color: "var(--ink2)" }}>
          <Icon name="star" size={15} style={{ color: "#f99d25" }} />
          {ev.catering}
        </div>
      </div>
      <div className="card" style={{ padding: 18 }}>
        <div className="eyebrow" style={{ marginBottom: 10 }}>Venue & notes</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 7, fontSize: 13.5, color: "var(--ink2)" }}>
          <div><b style={{ color: "var(--ink)" }}>Venue:</b> {ev.venue}, {ev.city}</div>
          <div><b style={{ color: "var(--ink)" }}>Room:</b> {ev.room}</div>
          <div><b style={{ color: "var(--ink)" }}>Language:</b> {ev.lang}</div>
          <div style={{ marginTop: 4, padding: "10px 12px", background: "var(--surface-2)", borderRadius: 10, lineHeight: 1.6 }}>{ev.notes}</div>
        </div>
      </div>
    </div>);

}

/* ── COMMUNICATIONS TAB ── */
function CommunicationsTab({ ev }) {
  const [sent, setSent] = useState([]);
  const c = ev.comms;
  const isVirtual = ev.mode !== "physical";
  const plan = c ? [
    { on: c.confirm, phase: "On sign-up", label: "Registration confirmation", when: "Instant", icon: "checkCircle", color: "#2e7d32",
      tags: [c.allergies && ev.mode !== "virtual" ? "Allergies request" : null, c.location ? (isVirtual ? "Join link" : "Location info") : null, c.attach || null].filter(Boolean) },
    { on: c.rem1On, phase: "Before", label: "Reminder 1", when: c.rem1When, icon: "bell", color: "#e65100" },
    { on: c.rem2On, phase: "Before", label: "Reminder 2", when: c.rem2When, icon: "bell", color: "#e65100" },
    { on: c.evalOn, phase: "After", label: "Evaluation survey", when: c.evalWhen, icon: "star", color: "#7c3aed" },
    { on: c.recapOn, phase: "After", label: "Event content & recap", when: c.recapWhen, icon: "download", color: "#00838f" }
  ].filter((x) => x.on) : null;

  const templates = [
  { id: "invite", icon: "share", label: "Send invitation", desc: "Registration link + event details", color: "#1281c4" },
  { id: "reminder", icon: "bell", label: "Send reminder", desc: "1 week before the event", color: "#f99d25" },
  { id: "logistics", icon: "list", label: "Send logistics info", desc: "Venue, materials & practical info", color: "#3bc1ce" },
  { id: "cert", icon: "cert", label: "Issue certificates", desc: "After event completion", color: "#7c3aed" }];

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      {plan &&
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 8 }}>
          <Icon name="mail" size={15} style={{ color: "var(--vh-blue-500)" }} />
          <span style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)" }}>Automated sequence</span>
          <span style={{ marginLeft: "auto", fontSize: 11.5, fontWeight: 700, color: "#2e7d32", background: "#e8f5e9", padding: "2px 9px", borderRadius: 999 }}>{plan.length} active</span>
        </div>
        {plan.map((p, i) =>
        <div key={i} style={{ display: "flex", alignItems: "flex-start", gap: 11, padding: "11px 16px", borderBottom: i < plan.length - 1 ? "1px solid var(--line-2)" : "none" }}>
          <div style={{ width: 30, height: 30, borderRadius: 8, background: p.color + "18", display: "grid", placeItems: "center", flexShrink: 0 }}><Icon name={p.icon} size={15} style={{ color: p.color }} /></div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)" }}>{p.label}</div>
            <div style={{ fontSize: 11.5, color: "var(--ink3)" }}>{p.phase} · {p.when}</div>
            {p.tags && p.tags.length > 0 &&
            <div style={{ display: "flex", flexWrap: "wrap", gap: 5, marginTop: 6 }}>
              {p.tags.map((t, ti) => <span key={ti} style={{ fontSize: 10.5, fontWeight: 600, color: "var(--ink2)", background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 6, padding: "2px 7px" }}>{t}</span>)}
            </div>}
          </div>
          <span style={{ fontSize: 11, fontWeight: 700, color: "var(--ink3)", display: "inline-flex", alignItems: "center", gap: 4, flexShrink: 0, marginTop: 2 }}><Icon name="clock" size={11} />Scheduled</span>
        </div>
        )}
      </div>
      }
      <div className="eyebrow" style={{ marginTop: plan ? 4 : 0 }}>Send now</div>
      {templates.map((t) =>
      <div key={t.id} className="card" style={{ padding: "14px 18px", display: "flex", alignItems: "center", gap: 14 }}>
          <div style={{ width: 40, height: 40, borderRadius: 11, background: t.color + "18", display: "grid", placeItems: "center", flexShrink: 0 }}>
            <Icon name={t.icon} size={18} style={{ color: t.color }} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: "var(--ink)" }}>{t.label}</div>
            <div style={{ fontSize: 12.5, color: "var(--ink3)" }}>{t.desc}</div>
          </div>
          {sent.includes(t.id) ?
        <span style={{ fontSize: 12.5, fontWeight: 700, color: "#2e7d32" }}>✓ Sent (demo)</span> :

        <button className="btn btn-ghost btn-sm" onClick={() => setSent((s) => [...s, t.id])} title="Demo — echte e-mail volgt in een latere fase">Send</button>
        }
        </div>
      )}
    </div>);

}

/* ── EVENT DETAIL PANEL ── */
function EventDetail({ ev, onClose, onHost, onPreviewReg }) {
  const [tab, setTab] = useState("overview");
  const pct = Math.round(ev.registered / ev.capacity * 100);
  const isVirtual = ev.mode !== "physical";
  const plat = ev.platform && PLATFORMS[ev.platform];
  const regUrl = "learn.vanharen.net/e/" + ev.regSlug;
  const TABS = [["overview", "Overview"], ["participants", "Participants"], ["logistics", "Logistics"], ["comms", "Communications"]];
  return (
    <div style={{ width: 400, flexShrink: 0, display: "flex", flexDirection: "column", gap: 0 }}>
      <div className="card" style={{ overflow: "hidden", flex: 1 }}>
        {/* header */}
        <div style={{ padding: "18px 20px 14px", borderBottom: "1px solid var(--line)", background: ev.colorHex + "10" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".1em", color: ev.colorHex, marginBottom: 4 }}>{ev.type}</div>
              <h2 style={{ fontSize: 17, fontWeight: 800, color: "var(--ink)", lineHeight: 1.2, marginBottom: 8 }}>{ev.title}</h2>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}><EvBadge status={ev.status} /><ModeChip mode={ev.mode} platform={ev.platform} /></div>
            </div>
            <button onClick={onClose} style={{ width: 30, height: 30, borderRadius: 8, background: "var(--surface-2)", border: "none", cursor: "pointer", display: "grid", placeItems: "center", flexShrink: 0 }}>
              <Icon name="x" size={15} style={{ color: "var(--ink3)" }} />
            </button>
          </div>
          <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 5 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 13, color: "var(--ink2)" }}>
              <Icon name="calendar" size={13} style={{ color: "var(--ink3)" }} />{ev.start} – {ev.end} · {ev.days} days · {ev.time}
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 13, color: "var(--ink2)" }}>
              <Icon name={isVirtual ? "video" : "pin"} size={13} style={{ color: "var(--ink3)" }} />{ev.mode === "virtual" ? plat.label : ev.venue + ", " + ev.city}
            </div>
          </div>
        </div>
        {/* tabs */}
        <div style={{ display: "flex", borderBottom: "1px solid var(--line)" }}>
          {TABS.map(([id, lbl]) =>
          <button key={id} onClick={() => setTab(id)} style={{ flex: 1, padding: "10px 4px", fontSize: 12, fontWeight: 700, border: "none", background: "none", cursor: "pointer", color: tab === id ? "var(--blue)" : "var(--ink3)", borderBottom: tab === id ? "2px solid var(--blue)" : "2px solid transparent", transition: "all .13s" }}>{lbl}</button>
          )}
        </div>
        {/* tab content */}
        <div style={{ padding: 16, overflowY: "auto", maxHeight: "calc(100vh - 360px)" }} className="scroll">
          {tab === "overview" &&
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                {[["Host", ev.trainer], ["Language", ev.lang], [isVirtual ? "Format" : "Room", isVirtual ? MODE_META[ev.mode].label : ev.room], [isVirtual ? "Registered" : "Capacity", ev.registered + "/" + ev.capacity]].map(([k, v]) =>
              <div key={k} style={{ background: "var(--surface-2)", borderRadius: 10, padding: "10px 12px" }}>
                    <div style={{ fontSize: 11, fontWeight: 700, color: "var(--ink3)", textTransform: "uppercase", letterSpacing: ".08em", marginBottom: 3 }}>{k}</div>
                    <div style={{ fontSize: 14, fontWeight: 600, color: "var(--ink)" }}>{v}</div>
                  </div>
              )}
              </div>
              <div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, fontWeight: 600, color: "var(--ink3)", marginBottom: 6 }}>
                  <span>Registration</span><span>{pct}%</span>
                </div>
                <div className="bar" style={{ height: 10 }}><i style={{ width: pct + "%", background: pct >= 95 ? "#c62828" : pct >= 75 ? "#e65100" : "#1281c4" }} /></div>
              </div>

              {isVirtual &&
            <div style={{ border: "1px solid var(--line)", borderRadius: 12, overflow: "hidden" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "12px 13px", background: plat.color + "0e" }}>
                  <PlatformChip id={ev.platform} size={34} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 10.5, fontWeight: 700, color: "var(--ink3)", textTransform: "uppercase", letterSpacing: ".08em" }}>Hosted on</div>
                    <div style={{ fontSize: 14, fontWeight: 700, color: "var(--ink)" }}>{plat.label}</div>
                  </div>
                  {plat.built && <span style={{ fontSize: 10.5, fontWeight: 800, color: plat.color, background: plat.color + "18", padding: "3px 8px", borderRadius: 999 }}>BUILT-IN</span>}
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "10px 13px", borderTop: "1px solid var(--line)" }}>
                  <Icon name="link" size={13} style={{ color: "var(--ink3)", flexShrink: 0 }} />
                  <span style={{ flex: 1, fontSize: 12.5, color: "var(--ink2)", fontFamily: "var(--display)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{ev.joinUrl}</span>
                  <CopyBtn text={ev.joinUrl} />
                </div>
              </div>
            }

              {/* Hosted registration / sign-on page */}
              <div style={{ border: "1px solid var(--line)", borderRadius: 12, overflow: "hidden" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "11px 13px", background: "var(--surface-2)" }}>
                  <div style={{ width: 30, height: 30, borderRadius: 8, background: ev.regPublished ? "#e8f5e9" : "#f5f5f5", display: "grid", placeItems: "center", flexShrink: 0 }}>
                    <Icon name="globe" size={16} style={{ color: ev.regPublished ? "#2e7d32" : "var(--ink3)" }} />
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)" }}>Sign-up page</div>
                    <div style={{ fontSize: 11.5, fontWeight: 700, color: ev.regPublished ? "#2e7d32" : "var(--ink3)" }}>{ev.regPublished ? "● Published & live" : "○ Not published"}</div>
                  </div>
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "10px 13px", borderTop: "1px solid var(--line)" }}>
                  <Icon name="link" size={13} style={{ color: "var(--ink3)", flexShrink: 0 }} />
                  <span style={{ flex: 1, fontSize: 12.5, color: "var(--vh-blue-600)", fontFamily: "var(--display)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{regUrl}</span>
                  <CopyBtn text={regUrl} />
                </div>
                <div style={{ display: "flex", gap: 8, padding: "0 13px 12px" }}>
                  <button onClick={() => onPreviewReg && onPreviewReg(ev)} className="btn btn-pri btn-sm" style={{ flex: 1 }}><Icon name="eye" size={13} />Preview page</button>
                  <button onClick={() => onPreviewReg && onPreviewReg(ev)} className="btn btn-ghost btn-sm" style={{ flex: 1 }}><Icon name="gear" size={13} />Page settings</button>
                </div>
              </div>
              <div style={{ display: "flex", gap: 8 }}>
                <button className="btn btn-pri btn-sm" style={{ flex: 1, opacity:.5, cursor:"not-allowed" }} disabled title="Binnenkort"><Icon name="check" size={13} />Confirm event</button>
                <button className="btn btn-ghost btn-sm" style={{ flex: 1, opacity:.5, cursor:"not-allowed" }} disabled title="Binnenkort"><Icon name="edit" size={13} />Edit</button>
              </div>
              <button onClick={() => onHost && onHost(ev)} style={{ width: "100%", display: "flex", alignItems: "center", justifyContent: "center", gap: 8, padding: "11px 0", borderRadius: 10, border: "none", background: "linear-gradient(135deg,#e0506a,#c0394f)", color: "#fff", fontFamily: "var(--display)", fontWeight: 800, fontSize: 14, cursor: "pointer", boxShadow: "0 6px 18px rgba(224,80,106,.3)" }}>
                <span style={{ width: 8, height: 8, borderRadius: "50%", background: "#fff" }} />{isVirtual ? "Go live · host webinar" : "Go live · host event"}
              </button>
            </div>
          }
          {tab === "participants" && <ParticipantsTab ev={ev} />}
          {tab === "logistics" && <LogisticsTab ev={ev} />}
          {tab === "comms" && <CommunicationsTab ev={ev} />}
        </div>
      </div>
    </div>);

}

/* ── NEW EVENT MODAL ── */
const VH_FIELD = { width: "100%", padding: "10px 12px", borderRadius: 9, border: "1.5px solid var(--line)", outline: "none", fontSize: 14, fontFamily: "var(--body)" };
const VH_LABEL = { fontSize: 12.5, fontWeight: 700, color: "var(--ink2)", display: "block", marginBottom: 5 };

function slugify(s) {return (s || "").toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");}
function fmtRange(sd, ed) {
  const M = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  const s = new Date(sd + "T00:00"),e = new Date(ed + "T00:00");
  const start = s.getDate() + " " + M[s.getMonth()];
  const end = e.getDate() + " " + M[e.getMonth()] + " " + e.getFullYear();
  const days = Math.max(1, Math.round((e - s) / 864e5) + 1);
  const juneDays = [];if (s.getMonth() === 5) for (let d = s.getDate(); d <= Math.min(30, s.getMonth() === e.getMonth() ? e.getDate() : 30); d++) juneDays.push(d);
  return { start, end, days, juneDays };
}

/* ── COMMS PLAN PRIMITIVES ── */
const REMINDER_WHENS = ["2 weeks before", "1 week before", "3 days before", "1 day before", "Morning of event"];
const AFTER_WHENS = ["Same day", "Next morning", "1 day after", "3 days after", "1 week after"];

function MiniSwitch({ on, onClick, color = "#2e7d32" }) {
  return (
    <button onClick={onClick} style={{ width: 40, height: 23, borderRadius: 999, background: on ? color : "var(--line)", position: "relative", flexShrink: 0, border: "none", cursor: "pointer", transition: "background .15s", padding: 0 }}>
      <span style={{ position: "absolute", top: 3, left: on ? 20 : 3, width: 17, height: 17, borderRadius: "50%", background: "#fff", transition: "left .15s", boxShadow: "0 1px 3px rgba(0,0,0,.25)" }} />
    </button>);
}

function CommRow({ icon, color = "#1281c4", title, desc, when, whenOpts, onWhen, on, onToggle, children }) {
  return (
    <div style={{ borderTop: "1px solid var(--line)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "11px 14px" }}>
        <div style={{ width: 30, height: 30, borderRadius: 8, background: on ? color + "18" : "var(--surface-3)", display: "grid", placeItems: "center", flexShrink: 0 }}>
          <Icon name={icon} size={15} style={{ color: on ? color : "var(--ink3)" }} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13.5, fontWeight: 700, color: on ? "var(--ink)" : "var(--ink2)" }}>{title}</div>
          <div style={{ fontSize: 11.5, color: "var(--ink3)" }}>{desc}</div>
        </div>
        {whenOpts && on &&
        <select value={when} onChange={(e) => onWhen(e.target.value)} style={{ fontSize: 11.5, fontWeight: 600, color: "var(--ink2)", border: "1px solid var(--line)", borderRadius: 7, padding: "5px 6px", background: "#fff", fontFamily: "var(--body)", maxWidth: 130, flexShrink: 0 }}>
          {whenOpts.map((w) => <option key={w}>{w}</option>)}
        </select>
        }
        <MiniSwitch on={on} onClick={onToggle} color={color} />
      </div>
      {on && children && <div style={{ padding: "0 14px 12px 55px", display: "flex", flexDirection: "column", gap: 9 }}>{children}</div>}
    </div>);
}

function CommCheck({ on, onClick, label }) {
  return (
    <label onClick={onClick} style={{ display: "flex", alignItems: "center", gap: 9, cursor: "pointer", fontSize: 12.5, color: on ? "var(--ink)" : "var(--ink2)" }}>
      <span style={{ width: 18, height: 18, borderRadius: 5, border: "2px solid " + (on ? "#1281c4" : "var(--line)"), background: on ? "#1281c4" : "transparent", display: "grid", placeItems: "center", flexShrink: 0 }}>
        {on && <Icon name="check" size={11} style={{ color: "#fff" }} stroke={3} />}
      </span>{label}
    </label>);
}

function PhaseLabel({ children }) {
  return <div style={{ padding: "9px 14px 7px", background: "var(--surface-2)", borderTop: "1px solid var(--line)", fontSize: 10.5, fontWeight: 800, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ink3)" }}>{children}</div>;
}

function NewEventModal({ onClose, onCreate }) {
  const eventTypes = ["Seminar", "Webinar", "Masterclass", "Workshop", "Pizza session", "Drinks & networking", "Hackathon", "Meetup", "Conference"];
  const trainers = [["Jonas Bakker", "JB"], ["Eva Groot", "EG"], ["Pieter van Dam", "PD"], ["Maria Santos", "MS"]];
  const [mode, setMode] = useState("physical");
  const [platform, setPlatform] = useState("vanharen");
  const [title, setTitle] = useState("");
  const [type, setType] = useState(eventTypes[0]);
  const [trainer, setTrainer] = useState(trainers[0][0]);
  const [sd, setSd] = useState("2026-07-01");
  const [ed, setEd] = useState("2026-07-03");
  const [st, setSt] = useState("09:00");
  const [et, setEt] = useState("17:00");
  const [venue, setVenue] = useState(VENUES[0]);
  const [room, setRoom] = useState("");
  const [cap, setCap] = useState(16);
  const [lang, setLang] = useState("Dutch");
  const [price, setPrice] = useState("");
  const [notes, setNotes] = useState("");
  const [publish, setPublish] = useState(true);
  const [comms, setComms] = useState({
    confirm: true, allergies: true, location: true,
    attach: "Joining instructions.pdf",
    rem1On: true, rem1When: "1 week before",
    rem2On: true, rem2When: "1 day before",
    evalOn: true, evalWhen: "Next morning",
    recapOn: true, recapWhen: "1 day after" });
  const cset = (p) => setComms((c) => ({ ...c, ...p }));

  const isVirtual = mode !== "physical";
  const slug = slugify(title) || "new-event";

  function create(asDraft) {
    const colorByMode = mode === "virtual" ? PLATFORMS[platform].color : "#1281c4";
    const r = fmtRange(sd, ed);
    const ti = trainers.find((t) => t[0] === trainer)[1];
    const ev = {
      id: Date.now(), title: title.trim() || "Untitled event", type, colorHex: colorByMode,
      mode, price: price.trim() || (isVirtual ? "€39" : "Free"),
      regSlug: slug, regPublished: asDraft ? false : publish,
      start: r.start, end: r.end, juneDays: r.juneDays, days: r.days, time: st + "–" + et,
      venue: isVirtual ? mode === "hybrid" ? venue : "Online" : venue.split(",")[0],
      city: isVirtual ? PLATFORMS[platform].label : (venue.split(",")[1] || "").trim(),
      room: isVirtual ? mode === "hybrid" ? room : "—" : room || "—",
      capacity: +cap || (isVirtual ? 250 : 40), registered: 0, trainer, ti,
      status: asDraft ? "draft" : "pending", lang,
      blurb: notes.trim() || type + " — hosted by Van Haren.",
      materials: [], catering: isVirtual ? "—" : "Refreshments included",
      notes: notes.trim() || "—",
      platform: isVirtual ? platform : undefined,
      joinUrl: isVirtual ? platform === "vanharen" ? "live.vanharen.net/r/" + slug : platform + ".vanharen.net/" + slug : undefined,
      comms: { ...comms },
      participants: [] };
    onCreate(ev);onClose();
  }

  const modeOpts = [["physical", "In-person", "pin"], ["virtual", "Online webinar", "video"], ["hybrid", "Hybrid", "globe"]];

  return (
    <div style={{ position: "fixed", inset: 0, background: "rgba(13,26,52,.5)", backdropFilter: "blur(3px)", zIndex: 200, display: "grid", placeItems: "center", padding: 24 }} onClick={(e) => {if (e.target === e.currentTarget) onClose();}}>
      <div className="card scroll" style={{ width: "100%", maxWidth: 580, maxHeight: "90vh", overflow: "auto", padding: 28 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20 }}>
          <h2 style={{ fontSize: 20, fontWeight: 800 }}>New event</h2>
          <button onClick={onClose} style={{ width: 32, height: 32, borderRadius: 9, background: "var(--surface-2)", border: "none", cursor: "pointer", display: "grid", placeItems: "center" }}>
            <Icon name="x" size={16} style={{ color: "var(--ink3)" }} />
          </button>
        </div>

        {/* MODE SELECTOR */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8, marginBottom: 18 }}>
          {modeOpts.map(([id, lbl, ic]) =>
          <button key={id} onClick={() => setMode(id)} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6, padding: "13px 6px", borderRadius: 12, cursor: "pointer", border: "1.5px solid " + (mode === id ? MODE_META[id].color : "var(--line)"), background: mode === id ? MODE_META[id].color + "0e" : "#fff" }}>
              <Icon name={ic} size={20} style={{ color: mode === id ? MODE_META[id].color : "var(--ink3)" }} />
              <span style={{ fontSize: 12.5, fontWeight: 700, color: mode === id ? MODE_META[id].color : "var(--ink2)" }}>{lbl}</span>
            </button>
          )}
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div><label style={VH_LABEL}>Event title</label><input value={title} onChange={(e) => setTitle(e.target.value)} style={VH_FIELD} placeholder="e.g. Pizza & Projects — June" /></div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <div><label style={VH_LABEL}>Event type</label><select value={type} onChange={(e) => setType(e.target.value)} style={{ ...VH_FIELD, background: "#fff" }}>{eventTypes.map((c) => <option key={c}>{c}</option>)}</select></div>
            <div><label style={VH_LABEL}>Host</label><select value={trainer} onChange={(e) => setTrainer(e.target.value)} style={{ ...VH_FIELD, background: "#fff" }}>{trainers.map((t) => <option key={t[0]}>{t[0]}</option>)}</select></div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <div><label style={VH_LABEL}>Start date</label><input type="date" value={sd} onChange={(e) => setSd(e.target.value)} style={VH_FIELD} /></div>
            <div><label style={VH_LABEL}>End date</label><input type="date" value={ed} onChange={(e) => setEd(e.target.value)} style={VH_FIELD} /></div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <div><label style={VH_LABEL}>Start time</label><input type="time" value={st} onChange={(e) => setSt(e.target.value)} style={VH_FIELD} /></div>
            <div><label style={VH_LABEL}>End time</label><input type="time" value={et} onChange={(e) => setEt(e.target.value)} style={VH_FIELD} /></div>
          </div>

          {/* PLATFORM PICKER (virtual / hybrid) */}
          {isVirtual &&
          <div style={{ background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 14, padding: 16 }}>
            <label style={{ ...VH_LABEL, marginBottom: 10 }}>Hosting tool</label>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
              {Object.keys(PLATFORMS).map((k) =>
              <button key={k} onClick={() => setPlatform(k)} style={{ display: "flex", alignItems: "center", gap: 10, padding: "11px 12px", borderRadius: 11, cursor: "pointer", textAlign: "left", border: "1.5px solid " + (platform === k ? PLATFORMS[k].color : "var(--line)"), background: platform === k ? PLATFORMS[k].color + "0e" : "#fff" }}>
                  <PlatformChip id={k} size={30} />
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: "var(--ink)", display: "flex", alignItems: "center", gap: 5 }}>{PLATFORMS[k].short}{PLATFORMS[k].built && <span style={{ fontSize: 9, fontWeight: 800, color: PLATFORMS[k].color, background: PLATFORMS[k].color + "1c", padding: "1px 5px", borderRadius: 4 }}>BUILT-IN</span>}</div>
                    <div style={{ fontSize: 11, color: "var(--ink3)" }}>{platform === k ? "Selected" : "Tap to use"}</div>
                  </div>
                </button>
              )}
            </div>
            <div style={{ marginTop: 11, fontSize: 12.5, color: "var(--ink2)", lineHeight: 1.5, display: "flex", gap: 8 }}>
              <PlatformChip id={platform} size={18} /><span>{PLATFORMS[platform].desc}</span>
            </div>
          </div>
          }

          {/* VENUE (physical / hybrid) */}
          {mode !== "virtual" &&
          <div>
            <label style={VH_LABEL}>{mode === "hybrid" ? "On-site venue (for in-room attendees)" : "Venue"}</label>
            <select value={venue} onChange={(e) => setVenue(e.target.value)} style={{ ...VH_FIELD, background: "#fff" }}>{VENUES.map((v) => <option key={v}>{v}</option>)}<option>+ Add new venue…</option></select>
          </div>
          }
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
            {mode !== "virtual" && <div><label style={VH_LABEL}>Room</label><input value={room} onChange={(e) => setRoom(e.target.value)} style={VH_FIELD} placeholder="Room A" /></div>}
            <div><label style={VH_LABEL}>{isVirtual ? "Max attendees" : "Capacity"}</label><input type="number" value={cap} onChange={(e) => setCap(e.target.value)} style={VH_FIELD} /></div>
            <div><label style={VH_LABEL}>Price</label><input value={price} onChange={(e) => setPrice(e.target.value)} style={VH_FIELD} placeholder={isVirtual ? "€295 / Free" : "€1.395"} /></div>
            <div style={mode !== "virtual" ? {} : { gridColumn: "span 1" }}><label style={VH_LABEL}>Language</label><select value={lang} onChange={(e) => setLang(e.target.value)} style={{ ...VH_FIELD, background: "#fff" }}><option>Dutch</option><option>English</option><option>German</option></select></div>
          </div>
          <div><label style={VH_LABEL}>Description &amp; notes</label><textarea rows={3} value={notes} onChange={(e) => setNotes(e.target.value)} style={{ ...VH_FIELD, resize: "vertical" }} placeholder="Shown on the sign-up page. Catering, parking, joining instructions…" /></div>

          {/* HOSTED SIGN-UP PAGE */}
          <div style={{ border: "1px solid var(--line)", borderRadius: 14, overflow: "hidden" }}>
            <button onClick={() => setPublish((p) => !p)} style={{ width: "100%", display: "flex", alignItems: "center", gap: 12, padding: "13px 15px", background: publish ? "#e8f5e9" : "var(--surface-2)", border: "none", cursor: "pointer", textAlign: "left" }}>
              <div style={{ width: 34, height: 34, borderRadius: 9, background: publish ? "#2e7d32" : "var(--surface-3)", display: "grid", placeItems: "center", flexShrink: 0 }}><Icon name="globe" size={18} style={{ color: publish ? "#fff" : "var(--ink3)" }} /></div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)" }}>Host a public sign-up page</div>
                <div style={{ fontSize: 12, color: "var(--ink2)" }}>A branded registration webpage learners can sign on through.</div>
              </div>
              <span style={{ width: 42, height: 24, borderRadius: 999, background: publish ? "#2e7d32" : "var(--line)", position: "relative", flexShrink: 0, transition: "background .15s" }}>
                <span style={{ position: "absolute", top: 3, left: publish ? 21 : 3, width: 18, height: 18, borderRadius: "50%", background: "#fff", transition: "left .15s", boxShadow: "0 1px 3px rgba(0,0,0,.25)" }} />
              </span>
            </button>
            {publish &&
            <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "11px 15px", borderTop: "1px solid var(--line)" }}>
              <Icon name="link" size={13} style={{ color: "var(--ink3)", flexShrink: 0 }} />
              <span style={{ fontSize: 12.5, color: "var(--ink2)", fontFamily: "var(--display)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>learn.vanharen.net/e/<b style={{ color: "var(--vh-blue-600)" }}>{slug}</b></span>
            </div>
            }
          </div>

          {/* AUTOMATED COMMUNICATIONS */}
          <div style={{ border: "1px solid var(--line)", borderRadius: 14, overflow: "hidden" }}>
            <div style={{ padding: "13px 15px", background: "var(--surface-2)", display: "flex", alignItems: "center", gap: 11 }}>
              <div style={{ width: 34, height: 34, borderRadius: 9, background: "var(--vh-blue-500)", display: "grid", placeItems: "center", flexShrink: 0 }}><Icon name="mail" size={18} style={{ color: "#fff" }} /></div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)" }}>Automated communications</div>
                <div style={{ fontSize: 12, color: "var(--ink2)" }}>Emails sent to registrants automatically around the event.</div>
              </div>
            </div>

            <PhaseLabel>On registration</PhaseLabel>
            <CommRow icon="checkCircle" color="#2e7d32" title="Registration confirmation" desc="Sent the moment someone signs up"
              on={comms.confirm} onToggle={() => cset({ confirm: !comms.confirm })}>
              {mode !== "virtual" &&
              <CommCheck on={comms.allergies} onClick={() => cset({ allergies: !comms.allergies })} label="Ask for allergies & dietary requirements" />}
              <CommCheck on={comms.location} onClick={() => cset({ location: !comms.location })} label={isVirtual ? "Include joining instructions & link" : "Include location, route & parking info"} />
              {/* attachment */}
              {comms.attach ?
              <div style={{ display: "flex", alignItems: "center", gap: 8, background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 9, padding: "7px 10px" }}>
                <Icon name="file" size={14} style={{ color: "var(--vh-blue-500)", flexShrink: 0 }} />
                <span style={{ flex: 1, fontSize: 12.5, fontWeight: 600, color: "var(--ink)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{comms.attach}</span>
                <span style={{ fontSize: 10.5, fontWeight: 700, color: "var(--ink3)" }}>auto-attached</span>
                <button onClick={() => cset({ attach: "" })} style={{ background: "none", border: "none", cursor: "pointer", display: "grid", placeItems: "center", padding: 2 }}><Icon name="x" size={13} style={{ color: "var(--ink3)" }} /></button>
              </div> :
              <button onClick={() => cset({ attach: isVirtual ? "Joining instructions.pdf" : "Route & parking.pdf" })} style={{ display: "inline-flex", alignItems: "center", gap: 7, fontSize: 12.5, fontWeight: 700, color: "var(--vh-blue-600)", background: "none", border: "1px dashed var(--line)", borderRadius: 9, padding: "7px 11px", cursor: "pointer", alignSelf: "flex-start" }}><Icon name="plus" size={13} />Attach a file to the mail</button>
              }
            </CommRow>

            <PhaseLabel>Before the event</PhaseLabel>
            <CommRow icon="bell" color="#e65100" title="Reminder 1" desc="Practical recap & what to bring"
              when={comms.rem1When} whenOpts={REMINDER_WHENS} onWhen={(w) => cset({ rem1When: w })}
              on={comms.rem1On} onToggle={() => cset({ rem1On: !comms.rem1On })} />
            <CommRow icon="bell" color="#e65100" title="Reminder 2" desc={isVirtual ? "Final reminder with the join link" : "Final reminder with directions"}
              when={comms.rem2When} whenOpts={REMINDER_WHENS} onWhen={(w) => cset({ rem2When: w })}
              on={comms.rem2On} onToggle={() => cset({ rem2On: !comms.rem2On })} />

            <PhaseLabel>After the event</PhaseLabel>
            <CommRow icon="star" color="#7c3aed" title="Evaluation survey" desc="Collect feedback & NPS"
              when={comms.evalWhen} whenOpts={AFTER_WHENS} onWhen={(w) => cset({ evalWhen: w })}
              on={comms.evalOn} onToggle={() => cset({ evalOn: !comms.evalOn })} />
            <CommRow icon="download" color="#00838f" title="Event content & recap" desc={isVirtual ? "Recording, slides & certificate" : "Slides, materials & certificate"}
              when={comms.recapWhen} whenOpts={AFTER_WHENS} onWhen={(w) => cset({ recapWhen: w })}
              on={comms.recapOn} onToggle={() => cset({ recapOn: !comms.recapOn })} />
          </div>

          <div style={{ display: "flex", gap: 10, marginTop: 4 }}>
            <button className="btn btn-pri" style={{ flex: 1, padding: "12px", borderRadius: 11 }} onClick={() => create(false)}><Icon name="plus" size={16} />Create &amp; publish</button>
            <button className="btn btn-ghost" style={{ flex: 1, padding: "12px", borderRadius: 11 }} onClick={() => create(true)}>Save as draft</button>
          </div>
        </div>
      </div>
    </div>);

}

/* ── MAIN EVENTS SCREEN ── */
function Events() {
  const [view, setView] = useState("list");
  const [selected, setSelected] = useState(null);
  const [events, setEvents] = useState(PHYS_EVENTS);
  const [showNew, setShowNew] = useState(false);
  const [filter, setFilter] = useState("all");
  const [modeFilter, setModeFilter] = useState("all");
  const [hosting, setHosting] = useState(null);
  const [previewReg, setPreviewReg] = useState(null);

  const filters = ["all", "confirmed", "pending", "full", "draft"];
  const byMode = modeFilter === "all" ? events : events.filter((e) => e.mode === modeFilter);
  const filtered = filter === "all" ? byMode : byMode.filter((e) => e.status === filter);
  const totalReg = events.reduce((s, e) => s + e.registered, 0);
  const totalCap = events.reduce((s, e) => s + e.capacity, 0);
  const virtualCount = events.filter((e) => e.mode !== "physical").length;

  function selectEv(ev) {setSelected(ev === selected ? null : ev);setView("list");}
  function createEvent(ev) {setEvents((prev) => [ev, ...prev]);setSelected(ev);}

  return (
    <div>
      {/* Page head */}
      <div className="between" style={{ marginBottom: 22 }}>
        <div className="page-head" style={{ marginBottom: 0 }}>
          <h1>Events &amp; Webinars</h1>
          <p>Plan seminars, webinars, meetups and social sessions — each with a hosted sign-up page.</p>
        </div>
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
          <div className="segtabs">
            <button className={"segtab" + (view === "list" ? " on" : "")} onClick={() => setView("list")} style={{ display: "flex", alignItems: "center", gap: 6 }}><Icon name="list" size={14} />List</button>
            <button className={"segtab" + (view === "calendar" ? " on" : "")} onClick={() => setView("calendar")} style={{ display: "flex", alignItems: "center", gap: 6 }}><Icon name="calendar" size={14} />Calendar</button>
          </div>
          <button className="btn btn-acc" onClick={() => setShowNew(true)}><Icon name="plus" size={16} />New event</button>
        </div>
      </div>

      {/* Stats */}
      <div className="stat-grid" style={{ marginBottom: 20 }}>
        {[
        { label: "Upcoming events", val: events.filter((e) => e.status !== "cancelled").length, icon: "calendar", bg: "var(--vh-blue-50)", ic: "var(--vh-blue-500)" },
        { label: "Online webinars", val: virtualCount, icon: "video", bg: "#f3e8ff", ic: "#7c3aed" },
        { label: "Registered", val: totalReg.toLocaleString(), icon: "users", bg: "#e8f5e9", ic: "#2e7d32" },
        { label: "Sign-up pages live", val: events.filter((e) => e.regPublished).length, icon: "globe", bg: "#e0f7fa", ic: "#00838f" }].
        map((s) =>
        <div key={s.label} className="card stat-card">
            <div className="between" style={{ marginBottom: 12 }}>
              <div className="eyebrow">{s.label}</div>
              <div className="stat-ico" style={{ background: s.bg }}><Icon name={s.icon} size={17} style={{ color: s.ic }} /></div>
            </div>
            <div className="kpi" style={{ fontSize: 30 }}>{s.val}</div>
          </div>
        )}
      </div>

      {/* Filters */}
      {view === "list" &&
      <div style={{ display: "flex", gap: 8, marginBottom: 16, flexWrap: "wrap", alignItems: "center" }}>
          <div className="segtabs">
            {[["all", "All"], ["physical", "In-person"], ["virtual", "Webinars"], ["hybrid", "Hybrid"]].map(([id, lbl]) =>
          <button key={id} className={"segtab" + (modeFilter === id ? " on" : "")} onClick={() => setModeFilter(id)}>{lbl}</button>
          )}
          </div>
          <span style={{ width: 1, height: 22, background: "var(--line)" }} />
          {filters.map((f) =>
        <button key={f} onClick={() => setFilter(f)} className={"filter-chip" + (filter === f ? " on" : "")}>
              {f === "all" ? "All statuses" : EV_STATUS[f]?.label || f}
              {f !== "all" && <span style={{ marginLeft: 6, fontWeight: 800, fontSize: 12 }}>{events.filter((e) => e.status === f).length}</span>}
            </button>
        )}
        </div>
      }

      {/* Main content */}
      <div style={{ display: "flex", gap: 18, alignItems: "flex-start" }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          {view === "list" &&
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {filtered.length === 0 &&
            <div className="card" style={{ padding: 32, textAlign: "center", color: "var(--ink3)" }}>No events match this filter.</div>
            }
              {filtered.map((ev) => <EventCard key={ev.id} ev={ev} selected={selected?.id === ev.id} onSelect={selectEv} />)}
            </div>
          }
          {view === "calendar" && <EventCalendar events={events} onSelect={selectEv} />}
        </div>
        {selected && <EventDetail ev={selected} onClose={() => setSelected(null)} onHost={setHosting} onPreviewReg={setPreviewReg} />}
      </div>

      {showNew && <NewEventModal onClose={() => setShowNew(false)} onCreate={createEvent} />}
      {hosting && <EventHostRoom ev={hosting} onClose={() => setHosting(null)} />}
      {previewReg && <RegistrationPage ev={previewReg} onClose={() => setPreviewReg(null)} onRegister={() => setEvents((prev) => prev.map((e) => e.id === previewReg.id ? { ...e, registered: e.registered + 1 } : e))} />}
    </div>);

}

Object.assign(window, { Events, PLATFORMS, PlatformChip, ModeChip, MODE_META, EvBadge, EV_STATUS });