/* Modals, Notifications panel, Command palette, Toasts */
const { createPortal } = ReactDOM;

/* ------------ Modal primitive ------------ */
const Modal = ({ open, onClose, title, sub, children, footer, size = "md" }) => {
  useEffect(() => {
    if (!open) return;
    const h = (e) => e.key === "Escape" && onClose && onClose();
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [open, onClose]);
  if (!open) return null;
  const maxW = size === "sm" ? 420 : size === "lg" ? 760 : 560;
  return createPortal(
    <div className="mk-modal-backdrop" onClick={onClose}>
      <div className="mk-modal" style={{ maxWidth: maxW }} onClick={e => e.stopPropagation()}>
        <div className="mk-modal-head">
          <div>
            <div style={{ fontSize: 16, fontWeight: 500 }}>{title}</div>
            {sub && <div style={{ fontSize: 13, color: "var(--fg-muted)", marginTop: 4 }}>{sub}</div>}
          </div>
          <button className="btn btn-ghost btn-icon btn-sm" onClick={onClose} aria-label="Close"><Icon name="x"/></button>
        </div>
        <div className="mk-modal-body">{children}</div>
        {footer && <div className="mk-modal-foot">{footer}</div>}
      </div>
    </div>,
    document.body
  );
};

/* ------------ Toast system ------------ */
const ToastCtx = React.createContext(null);
const ToastProvider = ({ children }) => {
  const [toasts, setToasts] = useState([]);
  const push = (t) => {
    const id = Math.random().toString(36).slice(2, 8);
    setToasts(ts => [...ts, { id, ...t }]);
    setTimeout(() => setToasts(ts => ts.filter(x => x.id !== id)), t.duration || 3400);
  };
  return (
    <ToastCtx.Provider value={push}>
      {children}
      {createPortal(
        <div className="mk-toast-wrap">
          {toasts.map(t => (
            <div key={t.id} className={"mk-toast " + (t.kind || "")}>
              <div className="row gap-2" style={{ marginBottom: t.body ? 4 : 0 }}>
                <Icon name={t.kind === "danger" ? "x" : "check"} size={14} style={{ color: t.kind === "danger" ? "var(--mk-danger)" : "var(--mk-success)" }}/>
                <div style={{ fontWeight: 500, fontSize: 13.5 }}>{t.title}</div>
              </div>
              {t.body && <div style={{ fontSize: 12.5, color: "var(--fg-muted)" }}>{t.body}</div>}
            </div>
          ))}
        </div>, document.body
      )}
    </ToastCtx.Provider>
  );
};
const useToast = () => React.useContext(ToastCtx) || (() => {});

/* ------------ Add Number modal ------------ */
const AddNumberModal = ({ open, onClose }) => {
  const toast = useToast();
  const [country, setCountry] = useState("Kenya");
  const [area, setArea] = useState("Nairobi");
  const [type, setType] = useState("local");
  const [busy, setBusy] = useState(false);
  const submit = async () => {
    setBusy(true);
    const res = await api.numbers.add(country);
    setBusy(false);
    onClose();
    toast({ title: "Number reserved", body: res.number + " · activating in ~12 min" });
  };
  return (
    <Modal open={open} onClose={onClose} title="Add a number" sub="Local, toll-free or mobile short code. Most activate in under 15 minutes."
      footer={<>
        <button className="btn btn-outline" onClick={onClose}>Cancel</button>
        <button className="btn btn-accent" onClick={submit} disabled={busy}>{busy ? "Reserving…" : "Reserve & activate"}</button>
      </>}>
      <div className="stack gap-4">
        <div className="grid grid-2">
          <div className="field"><label>Country</label>
            <select className="input" value={country} onChange={e => setCountry(e.target.value)}>
              <option>Kenya</option><option>Nigeria</option><option>Ghana</option><option>Tanzania</option><option>Uganda</option><option>South Africa</option>
            </select>
          </div>
          <div className="field"><label>Area / city</label>
            <select className="input" value={area} onChange={e => setArea(e.target.value)}>
              <option>Nairobi</option><option>Mombasa</option><option>Kisumu</option><option>Nakuru</option>
            </select>
          </div>
        </div>
        <div className="field">
          <label>Number type</label>
          <div className="grid grid-3" style={{ gap: 8 }}>
            {[["local", "Local", "+254 20 xxx"], ["toll", "Toll-free", "+254 800 xxx"], ["mobile", "Mobile", "+254 7xx xxx"]].map(([k, l, d]) => (
              <div key={k} onClick={() => setType(k)} className="pick" data-on={type === k}>
                <div style={{ fontWeight: 500, fontSize: 13.5 }}>{l}</div>
                <div className="mono" style={{ fontSize: 11, color: "var(--fg-muted)" }}>{d}</div>
              </div>
            ))}
          </div>
        </div>
        <div style={{ padding: 12, background: "var(--bg-sunken)", borderRadius: 10, fontSize: 12.5, color: "var(--fg-muted)" }}>
          <b style={{ color: "var(--fg)" }}>KSh 900 / month</b> · includes 500 minutes. Overage: KSh 3.50/min. Billed on your next invoice.
        </div>
      </div>
    </Modal>
  );
};

/* ------------ Invite member modal ------------ */
const InviteMemberModal = ({ open, onClose }) => {
  const toast = useToast();
  const [email, setEmail] = useState("");
  const [role, setRole] = useState("Agent");
  const submit = async () => {
    if (!email) return;
    await api.team.invite(email, role);
    onClose();
    toast({ title: "Invite sent", body: email + " will get an email shortly." });
    setEmail("");
  };
  return (
    <Modal open={open} onClose={onClose} title="Invite a teammate" sub="They'll receive an email to set up their account."
      footer={<>
        <button className="btn btn-outline" onClick={onClose}>Cancel</button>
        <button className="btn btn-accent" onClick={submit} disabled={!email}>Send invite</button>
      </>}>
      <div className="stack gap-4">
        <div className="field"><label>Email</label><input className="input" type="email" autoFocus value={email} onChange={e => setEmail(e.target.value)} placeholder="colleague@acme.ke"/></div>
        <div className="field">
          <label>Role</label>
          <div className="stack gap-2">
            {[
              ["Owner", "Everything, including billing and deleting the workspace."],
              ["Admin", "Manage team, receptionist, numbers and integrations."],
              ["Agent", "View calls, handle callbacks. Can't change settings."],
            ].map(([r, d]) => (
              <div key={r} onClick={() => setRole(r)} className="pick" data-on={role === r} style={{ textAlign: "left" }}>
                <div className="row between" style={{ marginBottom: 2 }}><div style={{ fontWeight: 500, fontSize: 13.5 }}>{r}</div>{role === r && <Icon name="check" size={14} style={{ color: "var(--mk-orange)" }}/>}</div>
                <div style={{ fontSize: 12.5, color: "var(--fg-muted)" }}>{d}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </Modal>
  );
};

/* ------------ New playbook modal ------------ */
const NewPlaybookModal = ({ open, onClose }) => {
  const toast = useToast();
  const [name, setName] = useState("");
  const [tpl, setTpl] = useState("dental");
  const templates = [
    { k: "dental", t: "Dental clinic", d: "Bookings, emergencies, pricing FAQ." },
    { k: "ecom", t: "E-commerce", d: "Order status, returns, delivery ETA." },
    { k: "sacco", t: "SACCO / Bank", d: "Balance checks, loan status, KYC deflection." },
    { k: "clinic", t: "Medical clinic", d: "Appointments, triage, prescriptions." },
    { k: "blank", t: "Blank", d: "Start from scratch." },
  ];
  const submit = () => {
    onClose();
    toast({ title: "Playbook created", body: "Now describe the business and we'll populate the FAQ." });
    setName(""); setTpl("dental");
  };
  return (
    <Modal open={open} onClose={onClose} title="New playbook" sub="Pick a starter — you can edit everything after."
      size="lg"
      footer={<>
        <button className="btn btn-outline" onClick={onClose}>Cancel</button>
        <button className="btn btn-accent" onClick={submit} disabled={!name}>Create playbook</button>
      </>}>
      <div className="stack gap-4">
        <div className="field"><label>Name</label><input className="input" autoFocus value={name} onChange={e => setName(e.target.value)} placeholder="e.g. After-hours line"/></div>
        <div className="field"><label>Starter template</label>
          <div className="grid grid-3" style={{ gap: 10 }}>
            {templates.map(x => (
              <div key={x.k} onClick={() => setTpl(x.k)} className="pick" data-on={tpl === x.k}>
                <div style={{ fontWeight: 500, fontSize: 13.5, marginBottom: 2 }}>{x.t}</div>
                <div style={{ fontSize: 12, color: "var(--fg-muted)" }}>{x.d}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </Modal>
  );
};

/* ------------ Notifications panel (right drawer) ------------ */
const NotificationsPanel = ({ open, onClose }) => {
  const store = MK_USE();
  if (!open) return null;
  const unread = store.notifications.filter(n => !n.read).length;
  return createPortal(
    <div className="mk-drawer-backdrop" onClick={onClose}>
      <div className="mk-drawer" onClick={e => e.stopPropagation()}>
        <div className="row between" style={{ padding: "18px 20px", borderBottom: "1px solid var(--border)" }}>
          <div>
            <div style={{ fontSize: 15, fontWeight: 500 }}>Notifications</div>
            <div style={{ fontSize: 12.5, color: "var(--fg-muted)" }}>{unread ? unread + " unread" : "You're all caught up"}</div>
          </div>
          <div className="row gap-2">
            {unread > 0 && <button className="btn btn-ghost btn-sm" onClick={() => api.notifications.markAllRead()}>Mark all read</button>}
            <button className="btn btn-ghost btn-icon btn-sm" onClick={onClose}><Icon name="x"/></button>
          </div>
        </div>
        <div style={{ overflowY: "auto", flex: 1 }}>
          {store.notifications.length === 0 ? (
            <div style={{ padding: 48, textAlign: "center", color: "var(--fg-muted)", fontSize: 14 }}>Nothing here yet.</div>
          ) : store.notifications.map(n => (
            <div key={n.id} onClick={() => api.notifications.markRead(n.id)}
              style={{ padding: "16px 20px", borderBottom: "1px solid var(--border)", display: "flex", gap: 12, cursor: "pointer", background: n.read ? "transparent" : "var(--accent-soft)" }}>
              <div style={{ width: 8, height: 8, borderRadius: 99, marginTop: 6, background: n.kind === "danger" ? "var(--mk-danger)" : n.kind === "warn" ? "var(--mk-warning)" : n.kind === "live" ? "var(--mk-success)" : "var(--fg-faint)" }}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: n.read ? 400 : 500, fontSize: 13.5, marginBottom: 4 }}>{n.title}</div>
                <div style={{ fontSize: 12.5, color: "var(--fg-muted)", marginBottom: 6, lineHeight: 1.45 }}>{n.body}</div>
                <div style={{ fontSize: 11.5, color: "var(--fg-faint)" }} className="mono">{n.when}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>,
    document.body
  );
};

/* ------------ Command palette ⌘K ------------ */
const CommandPalette = ({ open, onClose, onGo }) => {
  const [q, setQ] = useState("");
  const inputRef = useRef(null);
  const items = [
    { t: "Go to Home", k: "home", r: "tenant-dashboard", i: "home" },
    { t: "Go to AI Receptionist", k: "receptionist", r: "ai-receptionist", i: "bot" },
    { t: "Go to Calls", k: "calls", r: "tenant-calls", i: "phone" },
    { t: "Go to Insights", k: "insights", r: "tenant-insights", i: "chart" },
    { t: "Go to Numbers", k: "numbers", r: "tenant-numbers", i: "hash" },
    { t: "Go to Team", k: "team", r: "tenant-team", i: "users" },
    { t: "Go to Billing", k: "billing", r: "tenant-billing", i: "card" },
    { t: "Go to Connections", k: "connections", r: "connections", i: "link" },
    { t: "Go to Settings", k: "settings", r: "tenant-settings", i: "settings" },
    { t: "Go to Help & support", k: "help support", r: "support", i: "book" },
    { t: "— Admin —", sep: true },
    { t: "Go to Control plane", k: "dashboard admin", r: "dashboard", i: "home" },
    { t: "Go to Tenants", k: "tenants admin", r: "tenants", i: "users" },
    { t: "Go to All calls", k: "calls global admin", r: "calls-global", i: "phone" },
    { t: "Go to AT setup queue", k: "at setup", r: "at-setup", i: "inbox" },
    { t: "Go to Number pool", k: "number pool", r: "number-pool", i: "hash" },
    { t: "Go to Audit trail", k: "audit", r: "audit", i: "log" },
    { t: "— Actions —", sep: true },
    { t: "Start test call", k: "test call", act: "test", i: "play" },
    { t: "Log out", k: "logout", act: "logout", i: "log-out" },
  ];
  useEffect(() => { if (open) setTimeout(() => inputRef.current && inputRef.current.focus(), 20); setQ(""); }, [open]);
  if (!open) return null;
  const filtered = items.filter(it => it.sep || (it.k || "").includes(q.toLowerCase()) || it.t.toLowerCase().includes(q.toLowerCase()));
  const go = (it) => {
    if (it.sep) return;
    if (it.r) onGo(it.r);
    if (it.act === "logout") onGo("login");
    onClose();
  };
  return createPortal(
    <div className="mk-modal-backdrop" onClick={onClose} style={{ alignItems: "flex-start", paddingTop: "12vh" }}>
      <div className="mk-cmdk" onClick={e => e.stopPropagation()}>
        <div className="row gap-2" style={{ padding: "14px 16px", borderBottom: "1px solid var(--border)" }}>
          <Icon name="search" size={16} style={{ color: "var(--fg-faint)" }}/>
          <input ref={inputRef} value={q} onChange={e => setQ(e.target.value)} placeholder="Type a command or search…" style={{ flex: 1, border: 0, background: "transparent", outline: "none", fontSize: 15, color: "var(--fg)" }}/>
          <span className="kbd" style={{ position: "static" }}>ESC</span>
        </div>
        <div style={{ maxHeight: "50vh", overflowY: "auto", padding: 6 }}>
          {filtered.length === 0 && <div style={{ padding: 24, textAlign: "center", color: "var(--fg-muted)", fontSize: 13 }}>No matches.</div>}
          {filtered.map((it, i) => it.sep
            ? <div key={i} style={{ padding: "8px 10px 4px", fontSize: 10.5, letterSpacing: ".14em", color: "var(--fg-faint)", textTransform: "uppercase" }}>{it.t.replace(/—/g, "").trim()}</div>
            : <div key={i} className="cmdk-item" onClick={() => go(it)}>
                <Icon name={it.i} size={14} style={{ color: "var(--fg-muted)" }}/><span>{it.t}</span><Icon name="chevron-right" size={12} style={{ marginLeft: "auto", color: "var(--fg-faint)" }}/>
              </div>)}
        </div>
      </div>
    </div>,
    document.body
  );
};

Object.assign(window, { Modal, ToastProvider, useToast, AddNumberModal, InviteMemberModal, NewPlaybookModal, NotificationsPanel, CommandPalette });
