// Modal primitives + the specific admin modals.

const Modal = ({ title, sub, children, footer, onClose, width = 440 }) => {
  React.useEffect(() => {
    const k = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", k);
    return () => window.removeEventListener("keydown", k);
  }, [onClose]);
  return (
    <div className="modal-backdrop" onMouseDown={onClose}>
      <div className="modal" style={{ width }} onMouseDown={e => e.stopPropagation()}>
        <div className="modal-head">
          <div className="t">{title}</div>
          {sub && <div className="s">{sub}</div>}
        </div>
        <div className="modal-body">{children}</div>
        <div className="modal-foot">{footer}</div>
      </div>
    </div>
  );
};

// Kick
const KickModal = ({ player, server, onClose, onConfirm }) => {
  const [reason, setReason] = React.useState("AFK / inactive");
  return (
    <Modal
      title={`Kick ${player.name}`}
      sub={`From ${server.name} · ${server.region.toUpperCase()}`}
      onClose={onClose}
      footer={<>
        <button className="btn" onClick={onClose}>Cancel</button>
        <button className="btn warn" onClick={() => onConfirm(reason)}>Kick player</button>
      </>}
    >
      <div className="field">
        <label>Reason (shown to player)</label>
        <input value={reason} onChange={e => setReason(e.target.value)} />
      </div>
      <div className="muted" style={{ fontSize: 11.5 }}>Player can rejoin immediately. Use Ban for repeat offenders.</div>
    </Modal>
  );
};

// Ban
const BanModal = ({ player, server, onClose, onConfirm }) => {
  const auth = useAuth();
  const tempCheck = auth.check("player.tempban");
  const canPerm = auth.can("player.permban");
  const canNetwork = auth.can("player.networkban");
  const allDurations = [
    { id:"1h",  mins:60 },{ id:"6h",  mins:360 },{ id:"24h", mins:1440 },
    { id:"3d",  mins:4320 },{ id:"7d",  mins:10080 },{ id:"30d", mins:43200 }
  ];
  const cap = tempCheck.cap || Infinity;
  const durations = allDurations.filter(d => d.mins <= cap).map(d => d.id);
  const [mode, setMode] = React.useState("temp");
  const [duration, setDuration] = React.useState(durations[0] || "1h");
  const [scope, setScope] = React.useState("server");
  const [reason, setReason] = React.useState("");
  return (
    <Modal
      title={`Ban ${player.name}`}
      sub={mode === "temp" ? "Temporary ban — auto-expires" : "Permanent — manual reversal required"}
      onClose={onClose}
      footer={<>
        <button className="btn" onClick={onClose}>Cancel</button>
        <button className="btn danger" onClick={() => onConfirm({ mode, duration, scope, reason })}>
          {mode === "temp" ? `Apply ${duration} ban` : "Permanent ban"}
        </button>
      </>}
    >
      <div className="field">
        <label>Ban type</label>
        <div className="seg">
          <button className={mode==="temp"?"active":""} onClick={() => setMode("temp")}>Temporary</button>
          <button
            className={mode==="perm"?"active":""}
            onClick={() => canPerm && setMode("perm")}
            disabled={!canPerm}
            title={canPerm ? "" : "Permanent bans are restricted to Admin and above."}
            style={!canPerm ? { opacity: 0.45, cursor: "not-allowed" } : undefined}>Permanent</button>
        </div>
      </div>
      {mode === "temp" && (
        <div className="field">
          <label>Duration</label>
          <div className="seg">
            {durations.map(d => (
              <button key={d} className={duration===d?"active":""} onClick={() => setDuration(d)}>{d}</button>
            ))}
          </div>
        </div>
      )}
      <div className="field">
        <label>Scope</label>
        <div className="seg">
          <button className={scope==="server"?"active":""} onClick={() => setScope("server")}>This server</button>
          <button
            className={scope==="all"?"active":""}
            onClick={() => canNetwork && setScope("all")}
            disabled={!canNetwork}
            title={canNetwork ? "" : "Network-wide bans are restricted to Senior Admin and above."}
            style={!canNetwork ? { opacity: 0.45, cursor: "not-allowed" } : undefined}>All 5 servers</button>
        </div>
      </div>
      {tempCheck.cap && mode === "temp" && (
        <div className="muted" style={{ fontSize: 11.5 }}>
          Your tier (Trial Admin) is capped at 24h temporary bans. Need longer? Escalate to an Admin.
        </div>
      )}
      <div className="field">
        <label>Reason (logged)</label>
        <textarea value={reason} onChange={e => setReason(e.target.value)} placeholder="e.g. repeated team-killing after warning" />
      </div>
      <div className="muted" style={{ fontSize: 11.5 }}>
        <span className="mono">{auth.maskGUID(player.guid)}</span> · <span className="mono">{auth.maskIP(player.ip)}</span>
      </div>
    </Modal>
  );
};

// PM
const PMModal = ({ player, server, onClose, onConfirm }) => {
  const [msg, setMsg] = React.useState("");
  return (
    <Modal
      title={`Message ${player.name}`}
      sub="Private — only this player sees it in-game"
      onClose={onClose}
      footer={<>
        <button className="btn" onClick={onClose}>Cancel</button>
        <button className="btn primary" onClick={() => onConfirm(msg)} disabled={!msg.trim()}>Send</button>
      </>}
    >
      <div className="field">
        <label>Message</label>
        <textarea value={msg} onChange={e => setMsg(e.target.value)} placeholder="Quick warning, instruction, or question…" autoFocus />
      </div>
    </Modal>
  );
};

// Broadcast
const BroadcastModal = ({ server, onClose, onConfirm }) => {
  const auth = useAuth();
  const canAll = auth.can("server.broadcast.all");
  const [msg, setMsg] = React.useState("");
  const [scope, setScope] = React.useState("server");
  return (
    <Modal
      title="Broadcast to server"
      sub="Pinned at top of all players' screens for 8s"
      onClose={onClose}
      footer={<>
        <button className="btn" onClick={onClose}>Cancel</button>
        <button className="btn primary" onClick={() => onConfirm({ msg, scope })} disabled={!msg.trim()}>Broadcast</button>
      </>}
    >
      <div className="field">
        <label>Scope</label>
        <div className="seg">
          <button className={scope==="server"?"active":""} onClick={() => setScope("server")}>{server.name}</button>
          <button
            className={scope==="all"?"active":""}
            onClick={() => canAll && setScope("all")}
            disabled={!canAll}
            title={canAll ? "" : "Network broadcast is restricted to Senior Admin and above."}
            style={!canAll ? { opacity: 0.45, cursor: "not-allowed" } : undefined}>All 5 servers</button>
        </div>
      </div>
      <div className="field">
        <label>Message</label>
        <textarea value={msg} onChange={e => setMsg(e.target.value)} placeholder="e.g. Restart in 5 minutes — save your progress." autoFocus />
      </div>
    </Modal>
  );
};

// Restart / shutdown
const PowerModal = ({ server, onClose, onConfirm }) => {
  const [mode, setMode] = React.useState("restart");
  const [delay, setDelay] = React.useState(5);
  const [reason, setReason] = React.useState("");
  return (
    <Modal
      title={`${mode === "restart" ? "Restart" : "Shutdown"} ${server.name}`}
      sub={`Current uptime ${server.uptimeHrs}h · ${server.players.length} players online`}
      onClose={onClose}
      footer={<>
        <button className="btn" onClick={onClose}>Cancel</button>
        <button className="btn danger" onClick={() => onConfirm({ mode, delay, reason })}>
          {mode === "restart" ? `Restart in ${delay}m` : `Shutdown in ${delay}m`}
        </button>
      </>}
    >
      <div className="field">
        <label>Action</label>
        <div className="seg">
          <button className={mode==="restart"?"active":""} onClick={() => setMode("restart")}>Rolling restart</button>
          <button className={mode==="shutdown"?"active":""} onClick={() => setMode("shutdown")}>Shutdown</button>
        </div>
      </div>
      <div className="field">
        <label>Warn players for</label>
        <div className="seg">
          {[1,5,10,15].map(d => (
            <button key={d} className={delay===d?"active":""} onClick={() => setDelay(d)}>{d}m</button>
          ))}
        </div>
      </div>
      <div className="field">
        <label>Reason (optional, broadcast to players)</label>
        <input value={reason} onChange={e => setReason(e.target.value)} placeholder="e.g. mission rotation" />
      </div>
    </Modal>
  );
};

// Settings — account + (owner) staff management
const SettingsModal = ({ live, onClose }) => {
  const auth = useAuth();
  const toast = useToast();
  const isOwner = auth.role === "owner";
  const [tab, setTab] = React.useState("account");

  // -- account: change own password --
  const [cur, setCur] = React.useState("");
  const [next, setNext] = React.useState("");
  const [confirm, setConfirm] = React.useState("");
  const [busy, setBusy] = React.useState(false);

  const changePw = async () => {
    if (next !== confirm) { toast("New passwords don't match", "bad"); return; }
    if (next.length < 8) { toast("New password must be at least 8 characters", "bad"); return; }
    setBusy(true);
    try {
      await API.changePassword(cur, next);
      toast("Password changed", "ok");
      setCur(""); setNext(""); setConfirm("");
    } catch (e) { toast(e.message, "bad"); }
    setBusy(false);
  };

  // -- staff management --
  const [staff, setStaff] = React.useState(null);
  const loadStaff = React.useCallback(async () => {
    try { setStaff(await API.staff()); }
    catch (e) { toast(e.message, "bad"); }
  }, []);
  React.useEffect(() => { if (isOwner && tab === "staff" && live) loadStaff(); }, [isOwner, tab, live]);

  const [nh, setNh] = React.useState("");
  const [nn, setNn] = React.useState("");
  const [nr, setNr] = React.useState("trial");
  const [np, setNp] = React.useState("");
  const addStaff = async () => {
    try {
      await API.addStaff({ handle: nh, display_name: nn, role: nr, password: np });
      toast(`Added ${nh}`, "ok");
      setNh(""); setNn(""); setNr("trial"); setNp("");
      loadStaff();
    } catch (e) { toast(e.message, "bad"); }
  };
  const changeRole = async (id, role) => {
    try { await API.setStaffRole(id, role); toast("Role updated", "ok"); loadStaff(); }
    catch (e) { toast(e.message, "bad"); }
  };
  const resetPw = async (id, handle) => {
    const pw = window.prompt(`New password for ${handle} (min 8 chars):`);
    if (!pw) return;
    try { await API.resetStaffPassword(id, pw); toast(`Password reset for ${handle}`, "ok"); }
    catch (e) { toast(e.message, "bad"); }
  };
  const removeStaff = async (id, handle) => {
    if (!window.confirm(`Remove ${handle}? They lose access immediately.`)) return;
    try { await API.removeStaff(id); toast(`Removed ${handle}`, "ok"); loadStaff(); }
    catch (e) { toast(e.message, "bad"); }
  };

  return (
    <Modal
      title="Settings"
      sub={`${auth.user.display_name || auth.user.handle} · ${auth.roleMeta.label}`}
      onClose={onClose}
      width={isOwner ? 560 : 440}
      footer={<button className="btn" onClick={onClose}>Close</button>}
    >
      {isOwner && (
        <div className="seg" style={{ marginBottom: 16 }}>
          <button className={tab==="account"?"active":""} onClick={() => setTab("account")}>My account</button>
          <button className={tab==="staff"?"active":""} onClick={() => setTab("staff")}>Staff</button>
        </div>
      )}

      {tab === "account" && (
        <>
          <div className="field">
            <label>Current password</label>
            <input type="password" value={cur} onChange={e => setCur(e.target.value)} autoComplete="current-password" />
          </div>
          <div className="field">
            <label>New password</label>
            <input type="password" value={next} onChange={e => setNext(e.target.value)} autoComplete="new-password" />
          </div>
          <div className="field">
            <label>Confirm new password</label>
            <input type="password" value={confirm} onChange={e => setConfirm(e.target.value)} autoComplete="new-password" />
          </div>
          <button className="btn primary" onClick={changePw} disabled={busy || !cur || !next}>
            {busy ? "Saving…" : "Change password"}
          </button>
          {!live && <div className="muted" style={{ fontSize: 11.5, marginTop: 10 }}>Password changes only work against the live bridge.</div>}
        </>
      )}

      {tab === "staff" && isOwner && (
        <>
          {!live && <div className="muted" style={{ fontSize: 11.5 }}>Staff management only works against the live bridge.</div>}
          <div className="staff-list">
            {(staff || []).map(u => (
              <div className="staff-row" key={u.id}>
                <div className="flex1">
                  <div className="name">{u.display_name || u.handle} <span className="muted mono" style={{fontSize:11}}>@{u.handle}</span></div>
                  <div className="muted" style={{fontSize:11}}>{u.last_login ? "last in " + new Date(u.last_login).toLocaleDateString() : "never signed in"}</div>
                </div>
                <select value={u.role} onChange={e => changeRole(u.id, e.target.value)} disabled={u.id === auth.user.id}>
                  <option value="owner">Owner</option>
                  <option value="senior">Senior</option>
                  <option value="admin">Admin</option>
                  <option value="trial">Trial</option>
                </select>
                <button className="btn sm" onClick={() => resetPw(u.id, u.handle)} title="Reset password">Reset</button>
                <button className="btn sm danger" onClick={() => removeStaff(u.id, u.handle)} disabled={u.id === auth.user.id} title="Remove">✕</button>
              </div>
            ))}
            {staff && staff.length === 0 && <div className="muted" style={{fontSize:12}}>No staff yet.</div>}
          </div>

          <div className="staff-add">
            <div className="sub-label">Add staff member</div>
            <div className="staff-add-grid">
              <input placeholder="handle" value={nh} onChange={e => setNh(e.target.value)} />
              <input placeholder="display name" value={nn} onChange={e => setNn(e.target.value)} />
              <select value={nr} onChange={e => setNr(e.target.value)}>
                <option value="owner">Owner</option>
                <option value="senior">Senior</option>
                <option value="admin">Admin</option>
                <option value="trial">Trial</option>
              </select>
              <input placeholder="password (min 8)" type="password" value={np} onChange={e => setNp(e.target.value)} />
            </div>
            <button className="btn primary" onClick={addStaff} disabled={!nh || !np}>Add member</button>
          </div>
        </>
      )}
    </Modal>
  );
};

Object.assign(window, { Modal, KickModal, BanModal, PMModal, BroadcastModal, PowerModal, SettingsModal });
